<?php
class ModelToolCaseImageCrop extends Model{

    public function crop($product)
    {
        $product['model'] = mb_convert_case($product['model'], MB_CASE_UPPER, "UTF-8");
        $pattern_path = DIR_IMAGE . 'patterns/' . $product['model'] . '.png';
        $pattern = $product['model'] . '.png';

        $knife_path = DIR_IMAGE . 'repository/knifes/';
        $mask_url = '';

        if($product['image']){
            $item = explode('/', $product['image']);

            if(isset($item[3]) || isset($item[4])){
                $item = isset($item[4]) ? $item[4] : $item[3];
                $item = explode('.', $item);
                $item = $item[0];
                $item = explode('-', $item);

                if(isset($item[4]) AND $item[4] == '1'){
                    $item = $knife_path . $item[1] . '-' . $item[2] . '-' . $item[3] . '-' . $item[4] . '.png';
                }

                if(isset($item[5]) AND $item[5] == '1'){
                    $item = $knife_path . $item[1] . '-' . $item[2] . '-' . $item[3] . '-' . $item[4] . '.png';
                }

                if(isset($item[6]) AND $item[6] == '1'){
                    $item = $knife_path . $item[1] . '-' . $item[2] . '-' . $item[3] . '-' . $item[4] . '-' . $item[5] . '.png';
                }
               // $this->product->dump($item);
                if(file_exists($item)){
                    $mask_url = $this->image($pattern, $item, $product['product_id']);
                    $this->db->query("UPDATE ps_product SET mask = '". $this->db->escape($mask_url) ."' WHERE product_id = '". (int)$product['product_id'] ."' ");
                }

            }
        }

        return $mask_url;


    }

    public function image($model, $knife, $product_id)
    {

        if(!file_exists($knife))
            return '';

        if(file_exists(DIR_IMAGE . 'catalog/mask/' . $product_id . '.png'))
            return 'catalog/mask/' . $product_id . '.png';

        $pattern = DIR_IMAGE . 'patterns/' . $model;
        $mask = $knife;

        $base = new Imagick($pattern);
        $mask = new Imagick($mask);

        $base->setImageMatte(1);

        $base->compositeImage($mask, Imagick::COMPOSITE_DSTIN, 0, 0); //orignal transparent
        //$base->scaleImage(528, 960, false);
        $base->scaleImage(275, 500, false);
        $base->borderImage('rgba(0%, 0%, 0%, 0.0)', 112, 0);

        $base->writeImage(DIR_IMAGE . 'catalog/mask/' . $product_id . '.png');

        return 'catalog/mask/' . $product_id . '.png';



    }


}