<?php
class ControllerpiyerSoftCases extends Controller {

    public function index() {



        $product_type = $this->request->post['product_type'];
        if ($product_type == '1') {
            $text = strtoupper($this->request->post['customizetext']);
            $pattern = $this->request->post['pattern_url'];
            $mask = $this->request->post['pattern_mask'];
            $font_color = $this->request->post['customizeColor'];

            $text_position = $this->request->post['customizetextPosition'];

            $target_file_name = '';
            $font_family = 'Glitter';
            $font_color = '000000';
            $font_size = 20;
            if ($this->request->post['customizeFont'] != '') {
                $font_family = $this->request->post['customizeFont'];
            }
            if ($this->request->post['customizeColor'] != '') {
                $font_color = $this->request->post['customizeColor'];
            }

            if (strpos($pattern, '.png') == false || strpos($mask, '.png') == false) {
                echo json_encode(array('responce' => 'error'));
                die;
            }

            // Load pattern and mask
            $picture = imagecreatefrompng($pattern);
            $xSize = imagesx($picture);
            $ySize = imagesy($picture);
            imagesavealpha($picture, true);
            $mask = imagecreatefrompng($mask);


            if ($font_family == 'Glitter') {
                $font = 'glitter.ttf';
                $font_size = 41;
                if ($ySize > 500) {
                    $font_size = 48;
                }
                $text = '[' . $text . ']';
            } else if ($font_family == 'RobotoMono') {
                $font = 'roboto-mono.ttf';
                $font_size = 20;
            } else if ($font_family == 'Runway') {
                $font = 'runway.ttf';
                $font_size = 18;
            }
            $color = $this->GetColor($picture, $font_color);
            $font = DIR_APPLICATION . 'view/theme/' . $this->config->get('theme_default_directory') . '/font/' . $font;

            if ($text) {
                $angle = 0;
                if ($font_family == 'Glitter') {
                    for ($i = 1; $i <= $xSize; $i++) {
                        $box = imagettfbbox($i, $angle, $font, $text);
                        $lT = $box[2] - $box[0];
                        $cP = round(($lT / $xSize) * 100, 1);
                        if ($cP >= $font_size) {
                            $newFontSize = $i;
                            break;
                        }
                    }
                    $font_size = $newFontSize;
                }

                $box = imagettfbbox($font_size, $angle, $font, $text);
                $xr = abs(max($box[2], $box[4]));
                $yr = abs(max($box[5], $box[7]));
                $x = intval(($xSize - $xr) / 2);
                $y = intval(($ySize + $yr) / 2);

                // check text position
                if ($text_position == 'Bottom' || $text_position == '') {
                    if ($ySize > 500)
                        $y = $ySize - 120;
                    else
                        $y = $ySize - 50;
                }

                $bg_color = imagecolorallocate($picture, 254, 253, 253); // white border color
                $border_pixel = 5;
                if ($font_color == '000000') {
                    $bg_color = imagecolorallocate($picture, 0, 0, 1); // black border color
                }


                $this->imagettfborder($picture, $font_size, $angle, $x, $y, -$bg_color, $font, $text, $border_pixel);
                imagettftext($picture, $font_size, $angle, $x, $y, -$color, $font, $text);
            }

            // Resize mask if necessary
            if ($xSize != imagesx($mask) || $ySize != imagesy($mask)) {
                //  $this->resize($xSize, $ySize, $mask);
                $tempPic = imagecreatetruecolor($xSize, $ySize);
                imagealphablending($tempPic, false);
                imagesavealpha($tempPic, true);
                $transparency = imagecolorallocatealpha($tempPic, 255, 255, 255, 127);
                imagefilledrectangle($tempPic, 0, 0, $xSize, $ySize, $transparency);
                imagecopyresampled($tempPic, $mask, 0, 0, 0, 0, $xSize, $ySize, imagesx($mask), imagesy($mask));
                imagedestroy($mask);
                $mask = $tempPic;
            }


            // Get sizes and set up new picture
            $newPicture = imagecreatetruecolor($xSize, $ySize);
            imagesavealpha($newPicture, true);
            imagefill($newPicture, 0, 0, imagecolorallocatealpha($newPicture, 0, 0, 0, 127));


            // Perform pixel-based alpha map application
            for ($x = 0; $x < $xSize; $x++) {
                for ($y = 0; $y < $ySize; $y++) {
                    $alpha = imagecolorsforindex($mask, imagecolorat($mask, $x, $y));

                    if (($alpha['red'] == 0) && ($alpha['green'] == 0) && ($alpha['blue'] == 0) && ($alpha['alpha'] == 0)) {
                        // It'   s a black part of the mask
                        imagesetpixel($newPicture, $x, $y, imagecolorallocatealpha($newPicture, 0, 0, 0, 127)); // Stick a black, but totally transparent, pixel in.
                    } else {

                        // Check the alpha state of the corresponding pixel of the image we're dealing with.
                        $alphaSource = imagecolorsforindex($picture, imagecolorat($picture, $x, $y));
                        if (($alphaSource['red'] == ($font_color == '000000' ? 0 : 254)) && ($alphaSource['green'] == ($font_color == '000000' ? 0 : 253)) && ($alphaSource['blue'] == ($font_color == '000000' ? 1 : 253)) && ($alphaSource['alpha'] == 0)) { // white/black border color that has to remove
                            imagesetpixel($newPicture, $x, $y, imagecolorallocatealpha($newPicture, 0, 0, 0, 127));
                        } else if (($alphaSource['alpha'] == 127)) {
                            imagesetpixel($newPicture, $x, $y, imagecolorallocatealpha($newPicture, 0, 0, 0, 127)); // Stick a black, but totally transparent, pixel in.
                        } else {
                            $color = imagecolorsforindex($picture, imagecolorat($picture, $x, $y));
                            imagesetpixel($newPicture, $x, $y, imagecolorallocatealpha($newPicture, $color['red'], $color['green'], $color['blue'], $color['alpha'])); // Stick the pixel from the source image in
                        }
                    }
                }
            }
            imagedestroy($picture);
            $file_name = 'pattern_' . time() . '.png';
            $target_file_name = 'pattern_resize/' . $file_name;
            imagepng($newPicture, DIR_IMAGE . $target_file_name);
            imagedestroy($newPicture);
            echo json_encode(array('responce' => 'success', 'order_img' => $file_name));
        } else {
            echo json_encode(array('responce' => ''));
            die;
        }
    }

    public function GenerateDpiImageType4() {

        ini_set('memory_limit', '256M');



        if (isset($this->request->post['order_product_id'])) {
            $o_id = $this->request->post['order_product_id'];
            $customer_pattern_data = isset($this->request->post['customer_pattern_data']) ? $this->request->post['customer_pattern_data'] : '';
            $pattern_code = isset($this->request->post['pattern_code']) ? $this->request->post['pattern_code'] : '';
            $order_id = $this->request->post['order_id'];
        } else if ($this->request->get['order_product_id']) {
            $this->load->model('account/order');
            $order_product_info = $this->model_account_order->getOrderProduct($this->request->get['order_id'], $this->request->get['order_product_id']);
            $o_id = $this->request->get['order_product_id'];
            $customer_pattern_data = $order_product_info['customer_pattern_data'];
            $pattern_code = isset($this->request->get['pattern_code']) ? $this->request->get['pattern_code'] : '';
            $order_id = $this->request->get['order_id'];
        } else {
            die();
        }


        if ($o_id == -1) {
            die(json_encode(array('responce' => 'No valid Order can be selected')));
        }

        $this->load->model('piyersoft/cases');
        $order_product_id = $o_id;
        $customer_pattern_data = json_decode(@str_replace('&quot;', '"', $customer_pattern_data));
        $pattern = DIR_IMAGE . 'patterns/' . strtoupper($pattern_code) . '.png';


        $pattern_text = isset($customer_pattern_data->pattern_text) ? htmlspecialchars_decode(str_replace("&amp;", "&", $customer_pattern_data->pattern_text)) : '';
        $font = isset($customer_pattern_data->font) ? $customer_pattern_data->font : '';
        $font_color = isset($customer_pattern_data->font_color) ? $customer_pattern_data->font_color : '';
        $text_pos = isset($customer_pattern_data->text_pos) ? $customer_pattern_data->text_pos : '';
        $gradienttext = isset($customer_pattern_data->gradienttext) ? htmlspecialchars_decode(str_replace("&amp;", "&", $customer_pattern_data->gradienttext)) : '';
        $product_type = isset($customer_pattern_data->product_type) ? $customer_pattern_data->product_type : '';
        $texture = isset($customer_pattern_data->texture) ? $customer_pattern_data->texture : '';

        //$this->product->dump($pattern_text);

        if($font != 'RobotoMono'){
            $text = strtolower($pattern_text);
        }else{
            $text = $pattern_text;
        }


        //$text = strtoupper($pattern_text);

        $font_family = $font;
        $font_color = $font_color;
        $text_position = $text_pos;
        $gradient_img = '';


        $gradient_text = $gradienttext;
        $product_type = $product_type;
        $texture = $texture;


        $color = $font_color;
        $texture = DIR_IMAGE . 'texture/' . $texture;


        $gradient_font = DIR_APPLICATION . 'view/theme/' . $this->config->get('theme_default_directory') . '/font/PERTIBD.ttf';

        $pattern = DIR_IMAGE . 'asset.png';


        if (!is_file($pattern)) {
            $pattern = str_replace('png', 'jpg', $pattern);
            if (!is_file($pattern)) {
                die(json_encode(array('responce' => 'pattern image was not found')));
            }
        }


        if (strpos($pattern, '.png') !== false) {
            $picture = imagecreatefrompng($pattern);
            imagesavealpha($picture, true);
        } else {
            $picture = imagecreatefromjpeg($pattern);
        }
        $font = '';
        if ($text) {
            $angle = 0;
            if ($text_position == 'Vertical') {
                $angle = 90;
            }
            if ($text_position == 'VerticalRight') {
                $angle = 90;
            }
            if ($font_family == 'Glitter') {
                $font = 'glitter.ttf';
                $text = '[' . $text . ']';
            } else if ($font_family == 'RobotoMono') {
                $font = 'roboto-mono.ttf';
            } else if ($font_family == 'Runway') {
                $font = 'runway.ttf';
            }else if ($font_family == 'Besiktas') {
                $font = 'besiktas.ttf';
                
            }


            $font = DIR_APPLICATION . 'view/theme/' . $this->config->get('theme_default_directory') . '/font/' . $font;

            // Get sizes and set up new picture

            $width = imagesx($picture);
            $height = imagesy($picture);

            $color = $this->GetColor($picture, $font_color);
            $ySize = 580;

            if ($angle) {
                $font_size = 350;

                if ($font_family == 'Glitter') {
                    for ($i = 1; $i <= $ySize; $i++) {
                        $box = imagettfbbox($i, $angle, $font, $text);
                        $lT = $box[6] - $box[5];
                        $cP = round(($lT / $ySize) * 100, 1);
                        if ($cP >= $font_size) {
                            $newFontSize = $i;
                            break;
                        }
                    }
                    if ($newFontSize != 0)
                        $font_size = $newFontSize;
                }else {
                    $text_count = mb_strlen($text, 'UTF-8');
                    if ($text_count == 1) {
                        $font_size = ($font_family == 'RobotoMono' ? 360 : 350);
                    } else if ($text_count == 2) {
                         $font_size = ($font_family == 'RobotoMono' ? 290 : 280);
                    } else if ($text_count == 3) {
                         $font_size = ($font_family == 'RobotoMono' ? 250 : 230);
                    } else if ($text_count == 4) {
                        $font_size = ($font_family == 'RobotoMono' ? 220 : 180);
                    } else if ($text_count == 5) {
                        $font_size = ($font_family == 'RobotoMono' ? 190 : 150);
                    } else if ($text_count == 6) {
                        $font_size = ($font_family == 'RobotoMono' ? 170 : 120);
                    } else if ($text_count == 7) {
                        $font_size = ($font_family == 'RobotoMono' ? 150 : 130);
                    } else if ($text_count == 8) {
                        $font_size = ($font_family == 'RobotoMono' ? 140 : 130);
                    } else if ($text_count == 9) {
                        $font_size = ($font_family == 'RobotoMono' ? 130 : 120);
                    } else if ($text_count == 10) {
                        $font_size = ($font_family == 'RobotoMono' ? 130 : 120);
                    } else if ($text_count == 11) {
                        $font_size = ($font_family == 'RobotoMono' ? 130 : 120);
                    } else if ($text_count == 12) {
                        $font_size = ($font_family == 'RobotoMono' ? 120 : 110);
                    } else if ($text_count == 13) {
                        $font_size = 110;
                    } else if ($text_count == 14) {
                        $font_size = 100;
                    } else if ($text_count == 15) {
                        $font_size = 100;
                    }
                }
            } else {
                $font_size = 100;
                if ($font_family == 'Glitter') {
                    $text_count = mb_strlen($text, 'UTF-8');
                    if ($text_count == 4) {
                        $font_size = 180;
                    } else if ($text_count == 5) {
                        $font_size = 170;
                    } else if ($text_count == 6) {
                        $font_size = 160;
                    } else if ($text_count == 7) {
                        $font_size = 155;
                    } else if ($text_count == 8) {
                        $font_size = 155;
                    } else if ($text_count == 9) {
                        $font_size = 140;
                    } else if ($text_count == 10) {
                        $font_size = 130;
                    } else if ($text_count == 11) {
                        $font_size = 120;
                    } else if ($text_count == 12) {
                        $font_size = 120;
                    } else if ($text_count == 13) {
                        $font_size = 120;
                    } else if ($text_count == 14) {
                        $font_size = 100;
                    } else if ($text_count == 15) {
                        $font_size = 70;
                    }
                } else if ($font_family == 'RobotoMono') {
                    $font_size = 70;
                } else if ($font_family == 'Besiktas') {
                    $font_size = 80;
                } else if ($font_family == 'Runway') {
                    $font_size = 50;
                }
            }


            //$font_size = 10;
            ##Bilal 22-12-19

            $box = imagettfbbox($font_size, $angle, $font, $text);

            $centerX = $width / 2;
            $centerY = $height / 2;

            list($left, $bottom, $right,,, $top) = imageftbbox($font_size, $angle, $font, $text);
            // Determine offset of text
            $left_offset = ($right - $left) / 2;
            $top_offset = ($bottom - $top) / 2;
            // Generate coordinates
            $x = $centerX - $left_offset;
            $y = $centerY + $top_offset;

            if ($text_position == 'Vertical') {
                $x += 60;
            }
            if ($text_position == 'VerticalRight') {
                   $x += 60;
            }


            $bg_color = imagecolorallocate($picture, 254, 253, 253); // white border color
            if ($font_color == '000000') {
                $bg_color = imagecolorallocate($picture, 0, 0, 1); // black border color
            }

            $border_pixel = 1;

            if (strpos($pattern, '.png') !== false) {
                $this->imagettfborder($picture, $font_size, $angle, $x, $y, -$bg_color, $font, $text, $border_pixel);
            }
            if ($text_position == 'VerticalRight') {
                imagettftext($picture, $font_size, $angle, $x + 240, $y, -$color, $font, $text);
            }else{
                imagettftext($picture, $font_size, $angle, $x, $y, -$color, $font, $text);
 
            }


            $xSize = imagesx($picture);
            $ySize = imagesy($picture);
            if (strpos($pattern, '.png') !== false) {
                $newPicture = imagecreatetruecolor($xSize, $ySize);
                imagesavealpha($newPicture, true);
                imagefill($newPicture, 0, 0, imagecolorallocatealpha($newPicture, 0, 0, 0, 127));

                for ($x = 0; $x < $xSize; $x++) {
                    for ($y = 0; $y < $ySize; $y++) {
                        $alpha = imagecolorsforindex($picture, imagecolorat($picture, $x, $y));

                        if (($alpha['red'] == ($font_color == '000000' ? 0 : 254)) && ($alpha['green'] == ($font_color == '000000' ? 0 : 253)) && ($alpha['blue'] == ($font_color == '000000' ? 1 : 253)) && ($alpha['alpha'] == 0)) { // white/black border color that has to remove
                            imagesetpixel($newPicture, $x, $y, imagecolorallocatealpha($newPicture, 0, 0, 0, 127));
                        } else {
                            $alphaSource = imagecolorsforindex($picture, imagecolorat($picture, $x, $y));
                            if (($alphaSource['alpha'] == 127)) {
                                imagesetpixel($newPicture, $x, $y, imagecolorallocatealpha($newPicture, 0, 0, 0, 127));
                            } else {
                                $color = imagecolorsforindex($picture, imagecolorat($picture, $x, $y));
                                imagesetpixel($newPicture, $x, $y, imagecolorallocatealpha($newPicture, $color['red'], $color['green'], $color['blue'], $color['alpha'])); // Stick the pixel from the source image in
                            }
                        }
                    }
                }
            }
        }

        ##Bilal 23-12-2019

        $file_name_query = $this->db->query("SELECT model2, product_id FROM ps_product WHERE product_id = (SELECT product_id FROM ps_order_product WHERE order_product_id = '" . $order_product_id . "' ) ")->row;
        $file_name_cat_query = $this->db->query("SELECT cd.name FROM ps_product_to_category p2c
            LEFT JOIN ps_category_description cd ON (p2c.category_id = cd.category_id)
            WHERE product_id = '" . $file_name_query['product_id'] . "' LIMIT 3 ")->rows;

        $cat_names = array();
        foreach ($file_name_cat_query as $cat_name) {
            $cat_name = str_replace('Telefon Kılıfı', '', $cat_name['name']);
            $cat_name = rtrim($cat_name);
            $cat_name = mb_convert_case($cat_name, MB_CASE_LOWER, "UTF-8");
            $cat_name = str_replace(' ', '-', $cat_name);
            $cat_names[] = $cat_name;
        }

        if (isset($cat_names[2]))
            unset($cat_names[2]);

        $file_name_query = explode('-', $file_name_query['model2']);
        $file_name_query = $file_name_query[2] . '-' . $file_name_query[3];
        $new_file_name = implode('-', $cat_names) . '-' . $file_name_query;
        if (strpos($pattern, '.png') !== false) {
            $file_name = $new_file_name . '-' . time() . '-' . $order_product_id . '-' . $order_id . '.png';
        } else {
            $file_name = $new_file_name . '-' . time() . '-' . $order_product_id . '-' . $order_id . '.jpg';
        }


        ##Bilal 23-12-2019



        $target_file_name = 'admin_pattern_images/' . $file_name;
        if (strpos($pattern, '.png') !== false) {
            $res = imagepng(($text ? $newPicture : $picture), DIR_IMAGE . $target_file_name);
        } else {
            $res = imagejpeg($picture, DIR_IMAGE . $target_file_name);
        }

        ## Assest & Image -- Marge
         $asset = DIR_IMAGE . 'asset.png';
          $base = new Imagick(DIR_IMAGE . $target_file_name);
          $asset = new Imagick($asset);
          $base->setImageMatte(1);
          $base->compositeImage($asset, Imagick::COMPOSITE_DSTIN, 0, 0); //orignal transparent
          $base->writeImage($res);
        ## Assest & Image -- Marge

        if ($text && strpos($pattern, '.png') !== false)
            imagedestroy($newPicture);
        else
            imagedestroy($picture);

        if ($res) {
            $img_file_72 = DIR_IMAGE . $target_file_name;
            $cmd = "convert -units PixelsPerInch $img_file_72 -density 300 $img_file_72";
            $descriptorspec = [
                0 => ['pipe', 'r'],
                1 => ['pipe', 'w'],
                2 => ['file', DIR_LOGS . '/imageMagic_log', "a"]
            ];
            $proc = proc_open($cmd, $descriptorspec, $pipes);
            $this->model_piyersoft_cases->updateOrderProduct($order_product_id, $target_file_name);
            if (isset($this->request->get['order_product_id'])) {
                $order_product_info = $this->model_account_order->getOrderProduct($this->request->get['order_id'], $this->request->get['order_product_id']);
                echo '<script type="text/javascript">
                   window.location = "' . str_replace('&amp;', '&', HTTPS_SERVER . 'image/' . $order_product_info['admin_pattern_image']) . '"
              </script>';
            } else {
                die(json_encode(array('responce' => 'success', 'pattern_img' => $target_file_name, 'gradient_img' => $gradient_img)));
            }
        }
    }

    public function GenerateDpiImage() {
        ini_set('memory_limit', '256M');

        if (isset($this->request->post['order_product_id'])) {
            $o_id = $this->request->post['order_product_id'];
            $customer_pattern_data = isset($this->request->post['customer_pattern_data']) ? $this->request->post['customer_pattern_data'] : '';
            $pattern_code = isset($this->request->post['pattern_code']) ? $this->request->post['pattern_code'] : '';
            $order_id = $this->request->post['order_id'];
        } else if ($this->request->get['order_product_id']) {
            $this->load->model('account/order');
            $order_product_info = $this->model_account_order->getOrderProduct($this->request->get['order_id'], $this->request->get['order_product_id']);
            $o_id = $this->request->get['order_product_id'];
            $order_id = $this->request->get['order_id'];
            $customer_pattern_data = $order_product_info['customer_pattern_data'];
            $pattern_code = isset($this->request->get['pattern_code']) ? $this->request->get['pattern_code'] : '';
        } else {
            die();
        }


        if ($o_id == -1) {
            die(json_encode(array('responce' => 'No valid Order can be selected')));
        }

        $this->load->model('piyersoft/cases');
        $order_product_id = $o_id;
        $customer_pattern_data = json_decode(@str_replace('&quot;', '"', $customer_pattern_data));
        $pattern = DIR_IMAGE . 'patterns/' . strtoupper($pattern_code) . '.png';


        $pattern_text = isset($customer_pattern_data->pattern_text) ? htmlspecialchars_decode(str_replace("&amp;", "&", $customer_pattern_data->pattern_text)) : '';
        $pattern_text2 = isset($customer_pattern_data->pattern_text2) ? htmlspecialchars_decode(str_replace("&amp;", "&", $customer_pattern_data->pattern_text2)) : '';
        $font = isset($customer_pattern_data->font) ? $customer_pattern_data->font : '';
        $font_color = isset($customer_pattern_data->font_color) ? $customer_pattern_data->font_color : '';
        $text_pos = isset($customer_pattern_data->text_pos) ? $customer_pattern_data->text_pos : '';
        $gradienttext = isset($customer_pattern_data->gradienttext) ? htmlspecialchars_decode(str_replace("&amp;", "&", $customer_pattern_data->gradienttext)) : '';
        $product_type = isset($customer_pattern_data->product_type) ? $customer_pattern_data->product_type : '';
        $texture = isset($customer_pattern_data->texture) ? $customer_pattern_data->texture : '';

        $text1 = $pattern_text2;
        $text2 = $pattern_text;

        $font_family = $font;
        $font_color = $font_color;
        $text_position = $text_pos;
        $gradient_img = '';


        $gradient_text = $gradienttext;
        $product_type = $product_type;
        $texture = $texture;


        $color = $font_color;
        if ($texture == '1.jpg' && $font_color == '000000') {
            $color = '262626';
        }
        if ($texture == '8.jpg') {
            $texture = DIR_IMAGE . 'texture/t.png';
        } else {
            $texture = DIR_IMAGE . 'texture/' . $texture;
        }

        $gradient_font = DIR_APPLICATION . 'view/theme/' . $this->config->get('theme_default_directory') . '/font/PERTIBD.ttf';



        if (!is_file($pattern)) {
            $pattern = str_replace('png', 'jpg', $pattern);
            if (!is_file($pattern)) {
                die(json_encode(array('responce' => 'pattern image was not found')));
            }
        }

        if ($product_type == '2' || $product_type == '3') {
            $gradient_img = $this->GetGradientImage($product_type, $order_product_id, $pattern, $gradient_text, $texture, $gradient_font, $color);
        }


        if ($product_type == '2') {
            $picture = imagecreatefrompng($gradient_img);
            unlink($gradient_img);
            $gradient_img = '';
        } else {

            if (strpos($pattern, '.png') !== false) {
                $picture = imagecreatefrompng($pattern);
                imagesavealpha($picture, true);
            } else
                $picture = imagecreatefromjpeg($pattern);
        }

        $angle = 0;
        if ($font_family == 'Glitter') {
            $font = 'glitter.ttf';
            $font_size = 130;
            if ($text1 != '')
                $text1 = '[' . $text1 . ']';

            if ($text2 != '')
                $text2 = '[' . $text2 . ']';
        } else if ($font_family == 'RobotoMono') {
            $font = 'roboto-mono.ttf';
            $font_size = 80;
        } else if ($font_family == 'Besiktas') {
            $font = 'besiktas.ttf';
            $font_size = 90;
        } else if ($font_family == 'Runway') {
            $font = 'runway.ttf';
            $font_size = 80;
            if(mb_strlen($text2) > 10){
                $font_size = 50;
            }
        }




        $font = DIR_APPLICATION . 'view/theme/' . $this->config->get('theme_default_directory') . '/font/' . $font;

        // Get sizes and set up new picture

        $width = imagesx($picture);
        $height = imagesy($picture);

        $text1_font_size = $text2_font_size = $font_size;

        if ($font_family == 'Glitter') {

            // Get the FontSize  in case of glitter family
            if ($text1 != '') {
                $newFontSize = 0;
                for ($i = 1; $i <= $width; $i++) {
                    $box = imagettfbbox($i, $angle, $font, $text1);
                    $lT = $box[2] - $box[0];
                    $cP = round(($lT / $width) * 100, 1);
                    if ($cP >= $font_size) {
                        $newFontSize = $i;
                        break;
                    }
                }



                if ($newFontSize != 0)
                    $text1_font_size = $newFontSize;
            }


            if ($text2 != '') {
                $newFontSize = 0;
                for ($i = 1; $i <= $width; $i++) {
                    $box = imagettfbbox($i, $angle, $font, $text2);
                    $lT = $box[2] - $box[0];
                    $cP = round(($lT / $width) * 100, 1);
                    if ($cP >= $font_size) {
                        $newFontSize = $i;
                        break;
                    }
                }
                if ($newFontSize != 0)
                    $text2_font_size = $newFontSize;
            }
        }

        $color = $this->GetColor($picture, $font_color);

        $bg_color = imagecolorallocate($picture, 254, 253, 253); // white border color
        if ($font_color == '000000') {
            $bg_color = imagecolorallocate($picture, 0, 0, 1); // black border color
        }

        if (strpos($pattern_code, 'neon') !== false) {
            $border_pixel = 6;
        } else if (strpos($pattern_code, 'aq') !== false) {
            $border_pixel = 6;
        } else if (strpos($pattern_code, 'lms') !== false) {
            $border_pixel = 6;
        } else if (strpos($pattern_code, 'cl') !== false) {
            $border_pixel = 6;
        } else {
            $border_pixel = 1;
        }

        $border_pixel = 1;

        if (strpos($pattern, '.png') !== false) {

            if ($text1 != '') {

                $text1_font_size = $this->GetFontSize($font_family, $text1_font_size, $text1, $product_type);
                $text_pos = $text_position;
                if ($product_type == 6)
                    $text_pos = 'ikili';
                $quardiantes = $this->GetXYQuadinates($width, $height, $font_family, $text1_font_size, $angle, $font, $text1, $text_pos, $product_type);
                $text1_x = $quardiantes['x'];
                $text1_y = $quardiantes['y'];
                $this->imagettfborder($picture, $text1_font_size, $angle, $quardiantes['x'], $quardiantes['y'], -$bg_color, $font, $text1, $border_pixel);
            }

            if ($text2 != '') {

                $text2_font_size = $this->GetFontSize($font_family, $text2_font_size, $text2, $product_type);

                $quardiantes = $this->GetXYQuadinates($width, $height, $font_family, $text2_font_size, $angle, $font, $text2, $text_position, $product_type);
                $text2_x = $quardiantes['x'];
                $text2_y = $quardiantes['y'];
                $this->imagettfborder($picture, $text2_font_size, $angle, $quardiantes['x'], $quardiantes['y'], -$bg_color, $font, $text2, $border_pixel);
            }
        }

        if ($text1 != '')
            imagettftext($picture, $text1_font_size, $angle, $text1_x, $text1_y, -$color, $font, $text1);


        if ($text2 != '')
            imagettftext($picture, $text2_font_size, $angle, $text2_x, $text2_y, -$color, $font, $text2);





        $xSize = imagesx($picture);
        $ySize = imagesy($picture);
        if (strpos($pattern, '.png') !== false) {
            $newPicture = imagecreatetruecolor($xSize, $ySize);
            imagesavealpha($newPicture, true);
            imagefill($newPicture, 0, 0, imagecolorallocatealpha($newPicture, 0, 0, 0, 127));

            for ($x = 0; $x < $xSize; $x++) {
                for ($y = 0; $y < $ySize; $y++) {
                    $alpha = imagecolorsforindex($picture, imagecolorat($picture, $x, $y));

                    if (($alpha['red'] == ($font_color == '000000' ? 0 : 254)) && ($alpha['green'] == ($font_color == '000000' ? 0 : 253)) && ($alpha['blue'] == ($font_color == '000000' ? 1 : 253)) && ($alpha['alpha'] == 0)) { // white/black border color that has to remove
                        imagesetpixel($newPicture, $x, $y, imagecolorallocatealpha($newPicture, 0, 0, 0, 127));
                    } else {
                        $alphaSource = imagecolorsforindex($picture, imagecolorat($picture, $x, $y));
                        if (($alphaSource['alpha'] == 127)) {
                            imagesetpixel($newPicture, $x, $y, imagecolorallocatealpha($newPicture, 0, 0, 0, 127));
                        } else {
                            $color = imagecolorsforindex($picture, imagecolorat($picture, $x, $y));
                            imagesetpixel($newPicture, $x, $y, imagecolorallocatealpha($newPicture, $color['red'], $color['green'], $color['blue'], $color['alpha'])); // Stick the pixel from the source image in
                        }
                    }
                }
            }
        }


        ##Bilal 23-12-2019
        // Marka - Model - Koleksiyon - Renk
        $file_name_query = $this->db->query("SELECT model, model2, product_id FROM ps_product WHERE product_id = (SELECT product_id FROM ps_order_product WHERE order_product_id = '" . $order_product_id . "' ) ")->row;
        $file_name_cat_query = $this->db->query("SELECT cd.name FROM ps_product_to_category p2c
            LEFT JOIN ps_category_description cd ON (p2c.category_id = cd.category_id)
            WHERE product_id = '" . $file_name_query['product_id'] . "' ")->rows;

        $model = $file_name_query['model']; // airpods ürünlerinde airpods pro veya 1.2.nesil özelliğinin belirtilmesi için görsel adı düzenlemesi sırasında gereklidir. -Can 20.01.2022

        $cat_names = array();
        foreach ($file_name_cat_query as $cat_name) {
            $cat_name = str_replace('Telefon Kılıfı', '', $cat_name['name']);
            $cat_name = rtrim($cat_name);
            $cat_name = mb_convert_case($cat_name, MB_CASE_LOWER, "UTF-8");
            $cat_name = str_replace(' ', '-', $cat_name);
            $cat_names[] = $cat_name;
        }
        if (isset($cat_names[2]))
            unset($cat_names[2]);

        $file_name_query = explode('-', $file_name_query['model2']);
        
        if(strpos($model, 'aip')!==false || strpos($model, 'wba')!==false) { // bu koşul airpods ürünlerinde airpods pro veya 1.2.nesil özelliğinin belirtilmesi için görsel adında düzenleme yapar. -Can 20.01.2022
            $file_name_query = $file_name_query[1];
            $file_name_query =  str_replace("_","-",$file_name_query);
            $file_name_query =  str_replace("_","-",$file_name_query);
            if (isset($cat_names[1]))
            unset($cat_names[1]);
        } else {
            $file_name_query = $file_name_query[2] . '-' . $file_name_query[3];
        }
        //$file_name_query = $file_name_query[2] . '-' . $file_name_query[3];

        $new_file_name = implode('-', $cat_names) . '-' . $file_name_query;


        if (strpos($pattern, '.png') !== false) {
            $file_name = $new_file_name . '-' . time() . '-' . $order_product_id . '-' . $order_id . '.png';
        } else {
            $file_name = $new_file_name . '-' . time() . '-' . $order_product_id . '-' . $order_id . '.jpg';
        }

        ##Bilal 23-12-2019



        if($product_type=='8'){
        $product_data = $this->db->query("SELECT name FROM ps_order_product WHERE order_product_id='" . $order_product_id . "' ")->row;
        if (strpos($pattern, '.png') !== false) {
            $file_name=    strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $product_data['name']))). '-' . $order_id .'-'.time() . '.png';
        }
        else {
            $file_name=    strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-',  $product_data['name']))). '-' . $order_id .'-'.time() . '.jpg';
        }
    }

    


        $target_file_name = 'admin_pattern_images/' . $file_name;
        if (strpos($pattern, '.png') !== false) {

            $res = imagepng(($text1 != '' || $text2 != '' ? $newPicture : $picture), DIR_IMAGE . $target_file_name);
        } else {
            $res = imagejpeg($picture, DIR_IMAGE . $target_file_name);
        }

        ## Assest & Image -- Marge
        $asset = DIR_IMAGE . 'asset.png';
        $base = new Imagick(DIR_IMAGE . $target_file_name);
        $asset = new Imagick($asset);
        $base->setImageMatte(1);
        $base->compositeImage($asset, Imagick::COMPOSITE_DSTIN, 0, 0); //orignal transparent
        $base->writeImage($res);
        ## Assest & Image -- Marge

        if (($text1 != '' || $text2 != '') && strpos($pattern, '.png') !== false)
            imagedestroy($newPicture);
        else
            imagedestroy($picture);

        if ($res) {
            $img_file_72 = DIR_IMAGE . $target_file_name;
            $cmd = "convert -units PixelsPerInch $img_file_72 -density 300 $img_file_72";
            $descriptorspec = [
                0 => ['pipe', 'r'],
                1 => ['pipe', 'w'],
                2 => ['file', DIR_LOGS . '/imageMagic_log', "a"]
            ];
            $proc = proc_open($cmd, $descriptorspec, $pipes);
            $this->model_piyersoft_cases->updateOrderProduct($order_product_id, $target_file_name);
            if (isset($this->request->get['order_product_id'])) {
                $order_product_info = $this->model_account_order->getOrderProduct($this->request->get['order_id'], $this->request->get['order_product_id']);
                echo '<script type="text/javascript">
                   window.location = "' . str_replace('&amp;', '&', HTTPS_SERVER . 'image/' . $order_product_info['admin_pattern_image']) . '"
              </script>';
            } else {
                die(json_encode(array('responce' => 'success', 'pattern_img' => $target_file_name, 'gradient_img' => $gradient_img)));
            }
        }
    }

    function imagettfborder($im, $size, $angle, $x, $y, $color, $font, $text, $width) {

        for ($i = 1; $i < $width; $i++) {
            // top line
            imagettftext($im, $size, $angle, $x - $i, $y - $width, $color, $font, $text);
            imagettftext($im, $size, $angle, $x + $i, $y - $width, $color, $font, $text);
            // bottom line
            imagettftext($im, $size, $angle, $x - $i, $y + $width, $color, $font, $text);
            imagettftext($im, $size, $angle, $x + $i, $y + $width, $color, $font, $text);
            // left line
            imagettftext($im, $size, $angle, $x - $width, $y - $i, $color, $font, $text);
            imagettftext($im, $size, $angle, $x - $width, $y + $i, $color, $font, $text);
            // right line
            imagettftext($im, $size, $angle, $x + $width, $y - $i, $color, $font, $text);
            imagettftext($im, $size, $angle, $x + $width, $y + $i, $color, $font, $text);
        }
    }

    function GetFontSize($font_family, $font_size, $text, $product_type) {

        $font_size = $font_size;
        if ($product_type == 8) {
            if ($font_family == 'Glitter') {
              //  echo $font_size; die;
                switch (strlen(utf8_decode($text))) {
                    case 3: $font_size = 120;
                        break;
                    case 4: $font_size = 105;
                        break;
                    case 5: $font_size = 95;
                        break;
                    case 6: $font_size = 90;
                        break;
                    case 7: $font_size = 90;
                        break;
                    case 8: $font_size = 80;
                        break;
                    case 9: $font_size = 75;
                        break;
                    case 10: $font_size = 75;
                        break;
                    case 11: $font_size = 70;
                        break;
                    case 12: $font_size = 70;
                        break;
                    case 13: $font_size = 60;
                        break;
                    case 14: $font_size = 60;
                        break;
                    case 15: $font_size = 60;
                        break;
                    case 16: $font_size = 50;
                        break;
                    case 17: $font_size = 50;
                        break;
                }
               
               
            } else if ($font_family == 'RobotoMono') {
                
                switch (strlen(utf8_decode($text))) {
                    case 1: $font_size = 120;
                        break;
                    case 2: $font_size = 120;
                        break;
                    case 3: $font_size = 120;
                        break;
                    case 4: $font_size = 100;
                        break;
                    case 5: $font_size = 90;
                        break;
                    case 6: $font_size = 80;
                        break;
                    case 7: $font_size = 60;
                        break;
                    case 8: $font_size = 50;
                        break;
                    case 9: $font_size = 50;
                        break;
                    case 10: $font_size = 50;
                        break;
                    case 11: $font_size = 45;
                        break;
                    case 12: $font_size = 45;
                        break;
                    case 13: $font_size = 45;
                        break;
                    case 14: $font_size = 40;
                        break;
                    case 15: $font_size = 40;
                        break;
                    case 16: $font_size = 30;
                        break;
                    case 17: $font_size = 30;
                        break;
                }
               
            } else if ($font_family == 'Runway') {
                 switch (strlen(utf8_decode($text))) {
                    case 1: $font_size = 130;
                        break;
                    case 2: $font_size = 130;
                        break;
                    case 3: $font_size = 110;
                        break;
                    case 4: $font_size = 100;
                        break;
                    case 5: $font_size = 80;
                        break;
                    case 6: $font_size = 70;
                        break;
                    case 7: $font_size = 60;
                        break;
                    case 8: $font_size = 50;
                        break;
                    case 9: $font_size = 50;
                        break;
                    case 10: $font_size = 50;
                        break;
                    case 11: $font_size = 45;
                         break;
                    case 12: $font_size = 45;
                         break;
                    case 13: $font_size = 45;
                         break;
                    case 14: $font_size = 40;
                         break;
                    case 15: $font_size = 35;
                         break;
                    case 16: $font_size = 30;
                         break;
                    case 17: $font_size = 30;
                         break;
                }
            }
        } else {
            if ($font_family == 'Glitter' AND $product_type != 4) {
                if (strlen($text) == 3) {
                    $font_size -= 45;
                } elseif (strlen($text) == 12) {
                    $font_size = 110;
                }elseif (strlen($text) == 13) {
                    $font_size = 115;
                }elseif (strlen($text) == 14) {
                    $font_size = 100;
                }elseif (strlen($text) == 15) {
                    $font_size = 90;
                }elseif (strlen($text) == 16) {
                    $font_size = 80;
                }elseif (strlen($text) == 17) {
                    $font_size = 80;
                } elseif (strlen($text) == 11) {
                    $font_size = 120;
                } elseif (strlen($text) == 10) {
                    $font_size = 124;
                } elseif (strlen($text) == 9) {
                    $font_size = 130;
                } elseif (strlen($text) == 8) {
                    $font_size = 136;
                } elseif (strlen($text) == 7) {
                    $font_size = 142;
                } elseif (strlen($text) == 6) {
                    $font_size = 153;
                } elseif (strlen($text) == 5) {
                    $font_size = 170;
                } elseif (strlen($text) == 4) {
                    $font_size = 180;
                }
            } else if ($font_family == 'RobotoMono') {
                if (strlen($text) == 1) {
                    $font_size = 79;
                }elseif (strlen($text) == 12) {
                    $font_size = 65;
                }elseif (strlen($text) == 13) {
                    $font_size = 65;
                }elseif (strlen($text) == 14) {
                    $font_size = 60;
                }elseif (strlen($text) == 15) {
                    $font_size = 60;
                }elseif (strlen($text) == 16) {
                    $font_size = 55;
                }elseif (strlen($text) == 17) {
                    $font_size = 55;
                }
            } else if ($font_family == 'Runway') {
                if (strlen($text) == 1) {
                    $font_size = 44;
                } elseif (strlen($text) == 2) {
                    $font_size = 46;
                } elseif (strlen($text) == 3) {
                    $font_size = 50;
                } elseif (strlen($text) == 4) {
                    $font_size = 51;
                } elseif (strlen($text) == 5) {
                    $font_size = 51;
                } elseif (strlen($text) == 6) {
                    $font_size = 55;
                } elseif (strlen($text) == 7) {
                    $font_size = 58;
                } elseif (strlen($text) == 8) {
                    $font_size = 59;
                } elseif (strlen($text) == 9) {
                    $font_size = 60;
                } elseif (strlen($text) == 10) {
                    $font_size = 62;
                } elseif (strlen($text) == 11) {
                    $font_size = 62;
                }elseif (strlen($text) == 12) {
                    $font_size = 62;
                }elseif (strlen($text) == 13) {
                    $font_size = 45;
                }elseif (strlen($text) == 14) {
                    $font_size = 40;
                }elseif (strlen($text) == 15) {
                    $font_size = 40;
                }elseif (strlen($text) == 16) {
                    $font_size = 35;
                }elseif (strlen($text) == 17) {
                    $font_size = 35;
                }

            }
        }
        return $font_size;
    }

    function GetXYQuadinates($width, $height, $font_family, $font_size, $angle, $font, $text, $text_position, $product_type) {


        $box = imagettfbbox($font_size, $angle, $font, $text);

        if ($product_type == 4) {
            $centerX = $width / 2;
            $centerY = $height / 2;
            list($left, $bottom, $right,,, $top) = imageftbbox($font_size, $angle, $font, $text);
            // Determine offset of text
            $left_offset = ($right - $left) / 2;
            $top_offset = ($bottom - $top) / 2;
            // Generate coordinates
            $x = $centerX - $left_offset;
            $y = $centerY + $top_offset;

            if ($text_position == 'Vertical') {
                $x += 60;
            }
        } else {
            $xr = abs(max($box[2], $box[4]));
            $yr = abs(max($box[5], $box[7]));

            $x = intval(($width - $xr) / 2);
            $y = intval(($height + $yr) / 2);

            if ($text_position == 'ikili')
                $y = $height - 350;
            else if ($text_position == 'Bottom' || $text_position == '') {
                $y = $height - 180;
            }

            if ($text_position != 'ikili') {
                if ($font_family == 'Glitter') {
                    if (strlen($text) == 3) {
                        $y += 14;
                    } elseif (strlen($text) == 11) {
                        $y -= 33;
                    } elseif (strlen($text) == 10) {
                        $y -= 30;
                    } elseif (strlen($text) == 9) {
                        $y -= 27;
                    } elseif (strlen($text) == 8) {
                        $y -= 24;
                    } elseif (strlen($text) == 7) {
                        $y -= 21;
                    } elseif (strlen($text) == 6) {
                        $y -= 18;
                    } elseif (strlen($text) == 5) {
                        $y -= 6;
                    } elseif (strlen($text) == 4) {
                        $y -= 3;
                    }
                } else if ($font_family == 'RobotoMono') {
                    $y -= 40;
                } else if ($font_family == 'Runway') {
                    if (strlen($text) == 1) {
                        $y -= 60;
                    } elseif (strlen($text) == 2) {
                        $y -= 57;
                    } elseif (strlen($text) == 3) {
                        $y -= 54;
                    } elseif (strlen($text) == 4) {
                        $y -= 54;
                    } elseif (strlen($text) == 5) {
                        $y -= 54;
                    } elseif (strlen($text) == 6 OR strlen($text) == 7 OR strlen($text) == 8 OR strlen($text) == 9 OR strlen($text) == 10 OR strlen($text) == 11) {
                        $y -= 62;
                    }
                }
            }
        }

        return array('x' => $x, 'y' => $y);
    }

    function GetColor($picture, $font_color) {

        if ($font_color == '000000') {
            $color = imagecolorallocate($picture, 0, 0, 0); // black
        } else if ($font_color == 'FFFFFF') {
            $color = imagecolorallocate($picture, 255, 255, 255); // white
        } else if ($font_color == '5F4D80') {
            $color = imagecolorallocate($picture, 95, 77, 128); // purple
        } else if ($font_color == '133168') {
            $color = imagecolorallocate($picture, 19, 49, 104); // blue
        } else if ($font_color == 'FFC3D0') {
            $color = imagecolorallocate($picture, 255, 195, 208); // light pink
        } else if ($font_color == 'FF43A5') {
            $color = imagecolorallocate($picture, 255, 67, 165); // dark pink
        } else if ($font_color == 'FA6827') {
            $color = imagecolorallocate($picture, 250, 104, 39); // orange
        } else if ($font_color == 'F4CE11') {
            $color = imagecolorallocate($picture, 244, 206, 17); // yellow
        } else if ($font_color == 'F8F4CA') {
            $color = imagecolorallocate($picture, 248, 244, 202); // cream color
        } else if ($font_color == 'B8DEC6') {
            $color = imagecolorallocate($picture, 184, 222, 198); // sea green
        } else if ($font_color == 'CAE8EA') {
            $color = imagecolorallocate($picture, 202, 232, 234); // light blue
        } else if ($font_color == 'C8AFD5') {
            $color = imagecolorallocate($picture, 200, 175, 213); // purple
        }
        return $color;
    }

    function customcase() {


        $data['column_left'] = $this->load->controller('common/column_left');
        $data['column_right'] = $this->load->controller('common/column_right');
        $data['content_top'] = $this->load->controller('common/content_top');
        $data['content_bottom'] = $this->load->controller('common/content_bottom');
        $data['footer'] = $this->load->controller('common/footer');
        $data['header'] = $this->load->controller('common/header');
        $this->load->language('piyersoft/cases');
        $this->load->model('piyersoft/cases');
        $this->load->model('catalog/category');
        $data['sub_categories'] = array();
        $data['category_id'] = 0;
        $data['sub_category_id'] = 0;
        $data['customer_upload_image'] = '';
        $data['minimum'] = 1;

        if (isset($_FILES['custom_image'])) {
            $dir = 'image/upload';
            $res = $this->upload($dir, $_FILES['custom_image']);
            if (isset($res['success'])) {
                $data['customer_upload_image'] = HTTPS_SERVER . $res['image_file'];
            }
        }

        if (isset($this->request->get['brand'])) {
            $brand = $this->request->get['brand'];

            $category_info = $this->model_piyersoft_cases->getCategorybyname($brand);
            if ($category_info) {
                $data['category_id'] = $category_info['category_id'];
                $sub_categories = $this->model_catalog_category->getCategories($category_info['category_id']);

                if ($sub_categories) {
                    foreach ($sub_categories as $category) {
                        $data['sub_categories'][] = array(
                            'name' => $category['name'],
                            'category_id' => $category['category_id'],
                            'href' => $this->url->link('product/category', 'path=' . $category['category_id'], true)
                        );
                    }
                }
            }
        }
        if (isset($this->request->get['model'])) {

            $sub_category_info = $this->model_catalog_category->getCategory($this->request->get['model']);

            if ($sub_category_info) {
                $data['sub_category_id'] = $this->request->get['model'];
                $model = strtolower($this->request->get['brand'] . '-' . str_replace(' ', '-', trim(str_replace('Telefon Kılıfı', '', $sub_category_info['name']))));
                $data['personal_case_image'] = HTTPS_SERVER . "image/personal/" . $model . ".png";
            }
        }


        $data['form_action'] = $this->url->link('piyerSoft/cases/customcase');
        $data['breadcrumbs'] = array();

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/home')
        );

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_custom_cases'),
            'href' => ''
        );

        $data['button_cart'] = $this->language->get('button_cart');
        $data['text_buynow'] = $this->language->get('text_buynow');
        $data['text_loading'] = $this->language->get('text_loading');
        $data['entry_qty'] = $this->language->get('entry_qty');

        $all_categories = $this->model_catalog_category->getCategories();
        foreach ($all_categories as $category) {
            $data['all_categories'][] = array(
                'name' => $category['name'],
                'category_id' => $category['category_id'],
                'href' => $this->url->link('product/category', 'path=' . $category['category_id'], true)
            );
        }



        if (file_exists(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/piyersoft/cases.tpl')) {
            $this->response->setOutput($this->load->view(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/piyersoft/cases', $data));
        } else {
            $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'default/template/piyersoft/cases', $data));
        }
    }

    function AjaxUploadimage() {

        $json = array();
        if (isset($_FILES['custom_image'])) {
            $dir = 'image/upload';
            try {
                $res = $this->upload($dir, $_FILES['custom_image']);
            }catch(Exception $e){
                echo "mesaj -> ".$e->getMessage(); //hata çıktısı üretilir
            }
            //$res = $this->upload($dir, $_FILES['custom_image']);
            if (isset($res['success']))
                $json['customer_upload_image'] = HTTPS_SERVER . $res['image_file'];
            else
                $json['error'] = $res['error'];
        } else {
            $json['error'] = 'no file chosen';
        }
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    public function getDeeparteffectImage($submissionId = false) {
        $this->load->library('deeparteffects');
        $style_id = $this->request->post['styleId'];
        $filepath = $this->request->post['filepath'];

        if ($style_id == '' || $filepath == '' || !file_get_contents($filepath))
            die;

        $result = $this->deeparteffects->uploadImage($filepath, $style_id);

        $submissionId = '';
        $error = false;
        if (isset($result['submissionId'])) {
            $submissionId = $result['submissionId'];
           // $result = $this->deeparteffects->getStatus($submissionId);
        } else {
            $error = $result['error'];
        }

        $this->getImagebysubmissionId($error, $submissionId);
    }

     public function getImagebysubmissionId($error, $submissionId) {
        $json = array();

        if (!$error) {
            $image = $this->deeparteffects->getImage($submissionId);
            // var_dump($image); die;

            if (isset($image['error'])) {

                $json['error'] = $image['error'];
                $this->response->addHeader('Content-Type: application/json');
                $this->response->setOutput(json_encode($json));

            } else {

                if ($image['url']) {

                    $json['imageUrl'] = $image['url'];
                    $this->response->addHeader('Content-Type: application/json');
                    $this->response->setOutput(json_encode($json));

                } else {
                    sleep(1);
                    $this->getImagebysubmissionId(false, $submissionId);
                }
            }
        } else {
            $json['error'] = $error;
            $this->response->addHeader('Content-Type: application/json');
            $this->response->setOutput(json_encode($json));
        }
    }


    function getsubcategories() {
        if ($this->request->post['category_id'] != '') {
            $category_id = $this->request->post['category_id'];
            $this->load->model('catalog/category');
            $sub_categories = $this->model_catalog_category->getCategories($category_id);
            if ($sub_categories) {
                echo '<option value="">Model</option>';
                foreach ($sub_categories as $category) {
                    $brand_name = str_replace('Telefon Kılıfı', '', $category ['name']);
                    echo '<option value="' . $category['category_id'] . '" >' . $brand_name . '</option>';
                }
            }
        } else {
            echo '<option value="">Model</option>';
        }
    }

    function upload($directory, $file) {

        $json = array();
        if (!empty($file['name']) && is_file($file['tmp_name'])) {
            $this->load->language('common/filemanager');
            // Sanitize the filename
            $filename = basename(html_entity_decode($file['name'], ENT_QUOTES, 'UTF-8'));

            // Validate the filename length
            if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 255)) {
                $json['error'] = $this->language->get('error_filename');
            }

            // Allowed file extension types

            if ($this->config->get('marketplace_status')) {
                $allowed = explode(',', $this->config->get('marketplace_imageex'));
                if ($file['size'] > ($this->config->get('marketplace_imagesize') ? $this->config->get('marketplace_imagesize') * 1000 : 200000 )) { //1000 = 1kb
                    $json['error'] = $this->language->get('error_filesize');
                }
            } else {
                $allowed = array(
                    'jpg',
                    'jpeg',
                    'gif',
                    'png'
                );
            }

            if (!in_array(utf8_strtolower(utf8_substr(strrchr($filename, '.'), 1)), $allowed)) {
                $json['error'] = $this->language->get('error_filetype');
            }

            // Allowed file mime types
            $allowed = array(
                'image/jpeg',
                'image/pjpeg',
                'image/png',
                'image/x-png',
                'image/gif'
            );

            if (!in_array($file['type'], $allowed)) {
                $json['error'] = $this->language->get('error_filetype');
            }

            // Check to see if any PHP files are trying to be uploaded
            $content = file_get_contents($file['tmp_name']);

            if (preg_match('/\<\?php/i', $content)) {
                $json['error'] = $this->language->get('error_filetype');
            }

            // Return any upload error
            if ($file['error'] != UPLOAD_ERR_OK) {
                $json['error'] = $this->language->get('error_upload_' . $file['error']);
            }
        } else {
            $json['error'] = $this->language->get('error_upload');
        }


        if (!$json) {
            $filename = explode('.', $filename);
            $filename = @date('YmdHis') . '_' . @rand(999,999999) . '.' . $filename[1];
            move_uploaded_file($file['tmp_name'], $directory . '/' . $filename);

            $json['success'] = $this->language->get('text_uploaded');
            $json['image_file'] = $directory . '/' . $filename;

            $image = new Imagick();
            $img = file_get_contents($json['image_file']);
            $image->readImageblob($img);
            //imagick::readImageblob();
            $this->autoRotateImage($image);
            $image->writeImage(DIR_IMAGE . 'upload/' . $filename);
        }
        return $json;
    }

    function autoRotateImage($image) {

        $orientation = $image->getImageOrientation();

        switch ($orientation) {
            case imagick::ORIENTATION_BOTTOMRIGHT:
                $image->rotateimage("#000", 180); // rotate 180 degrees
                break;

            case imagick::ORIENTATION_RIGHTTOP:
                $image->rotateimage("#000", 90); // rotate 90 degrees CW
                break;

            case imagick::ORIENTATION_LEFTBOTTOM:
                $image->rotateimage("#000", -90); // rotate 90 degrees CCW
                break;
        }

        // Now that it's auto-rotated, make sure the EXIF data is correct in case the EXIF gets saved with the image!
        $image->setImageOrientation(imagick::ORIENTATION_TOPLEFT);
    }

    public function generatecustomcase() {
        if ($this->request->post) {
            if ($this->request->post['image'] != '') {
                $image = $this->request->post['image'];
                $product_type = $this->request->post['product_type'];
                $pathinfo = pathinfo($image);
                $image_data = $this->request->post['data'];
                
                $w = $image_data['w'];
                $h = $image_data['h'];
                $x = $image_data['x'];
                $y = $image_data['y'];
                $scale = $image_data['scale'];
                $angle = $image_data['angle'];
                $imagick = new Imagick();
                $img = file_get_contents($image);
                $imagick->readImageblob($img);
                $width = $imagick->getImageWidth() * $scale;
                $imagick->scaleImage($width, 0);
                $imagick->rotateImage(new \ImagickPixel(), $angle);
                $imagick->cropImage($w, $h, $x, $y);
                $fileName = @date('Ymdhis') . '_' . @rand(99999,999999) . '.' . $pathinfo['extension'];
                $target_file_name = 'upload/cropped' . $fileName;
                $imagick->writeImage(DIR_IMAGE . $target_file_name);
                $im = new Imagick();

               if ($product_type == 9 || $product_type == 11)
                    $orignal_img = file_get_contents($image);
                else
                    $orignal_img = file_get_contents(DIR_IMAGE . 'upload/' . $pathinfo['basename']);

                $im->readImageblob($orignal_img);
                $desire_width = 1080;
                $desire_height = 1920;
                if (1 == 2) {
                    $orignal_width = $im->getImageWidth();
                    $orignal_height = $im->getImageHeight();
                    $width = $orignal_width / $desire_width;
                    $height = $orignal_height / $desire_height;

                    $prewidth = $width;
                    $relativeRatio = $height / $width;

                    if ($relativeRatio > 1) {
                        $width = 1;
                        $height = $relativeRatio;
                    } else {
                        $width = 1 / $relativeRatio;
                        $height = 1;
                    }
                    if ($angle != 0 && $x == 0) {
                        $ratio = $desire_height / $desire_width;
                        $width = $height * $ratio;
                        $height = $width / $ratio;
                    }
                    $scale_value = $width / $prewidth;
                }
              //  $p_x = $x;
               // $p_y = $y;
               
               
                if ($x != 0)
                    $x = round(($x / $w) * $desire_width);

                if ($y != 0)
                    $y = round(($y / $h) * $desire_height);

                // $p_q = $p_x + $p_y;
                // $q = $x + $y;
                $scale_value = ($scale / 629) * 3000;
                

                $width = $im->getImageWidth() * round($scale_value, 4);
                $im->scaleImage($width, 0);
                $im->rotateImage(new \ImagickPixel(), $angle);
             
             
               
                $im->cropImage($desire_width, $desire_height, $x, $y);


                // $im->resizeImage(1080, 1920, Imagick::FILTER_LANCZOS, 1);
                $orignal_file_name = 'upload/' . $pathinfo['basename'];
               
               
               // if($_SERVER['REMOTE_ADDR']=='111.88.4.111'){
                if (file_exists(DIR_IMAGE . $orignal_file_name)) {
                   
                    unlink(DIR_IMAGE . $orignal_file_name);
                   
                }
                //  $orignal_file_name='uploadtest/' . $pathinfo['basename'];
             // }
               $orignal_file_name = 'upload/' . $fileName;
                $im->writeImage(DIR_IMAGE . $orignal_file_name);

                $img_file_72 = DIR_IMAGE . $orignal_file_name;
                $cmd = "convert -units PixelsPerInch $img_file_72 -density 300 $img_file_72";
                $descriptorspec = [
                    0 => ['pipe', 'r'],
                    1 => ['pipe', 'w'],
                    2 => ['file', DIR_LOGS . '/imageMagic_log', "a"]
                ];
                $proc = proc_open($cmd, $descriptorspec, $pipes);

                echo json_encode(array('responce' => 'success', 'file' => $target_file_name));
            }
        }
    }

    function GetGradientImage($product_type, $order_product_id, $pattern, $gradient_text, $texture, $gradient_font, $font_color) {


        /* Create a new imagick object */
        $gradient_texture = file_get_contents($texture);
        $im = new Imagick();
        $im->readImageblob($gradient_texture);

        /* Start a new pattern called "gradient" */
        $draw = new ImagickDraw();
        $draw->pushPattern('gradient', 0, 0, 80, 80);

        /* Composite the gradient on the pattern */
        $draw->composite(Imagick::COMPOSITE_OVER, 0, 0, 80, 80, $im);

        /* Close the pattern */
        $draw->popPattern();

        /* Use the pattern called "gradient" as the fill */
        $draw->setFillPatternURL('#gradient');

        /* Set the font family */
        $draw->setFont($gradient_font);

        /* Set text border and border width */
        $draw->setStrokeColor('#' . $font_color);
        $draw->setStrokeWidth(4);

        /* Annotate some text */

        $font_size = 500;



        $pattern = file_get_contents($pattern);
        $image = new Imagick();
        $image->readImageblob($pattern);
        $length = strlen($gradient_text);

        $x = 530;
        $y = 1050;
        if ($length == 2) {
            $font_size = 450;
            $y = 1050;
        } elseif ($length == 3) {
            $font_size = 380;
            $y = 1030;
        }

        //if (1 == 2 && $product_type == '3') { // for circluar pattern image -- Ben kapattım burayı => Bilal
        if ($product_type == '3') { // for circluar pattern image
            $font_size = 350;
            $x = 530;
            $y = 1070;
            //$image->resizeImage(486, 486, Imagick::FILTER_LANCZOS, 1);
            if ($length == 2) {
                $font_size = 260; // 250
                $y = 1050;
            } elseif ($length == 3) {
                $font_size = 170;
                $y = 990; //1030
            }
        }

        /*
         * $x = 530;
          $y = 1050;
          if ($length == 2) {
          $font_size = 450;
          $y = 1050;
          } elseif ($length == 3) {
          $font_size = 380;
          $y = 1030;
          }
         */




        //var_dump($font_size); die();


        $draw->setFontSize($font_size);
        // $draw->setGravity(Imagick::GRAVITY_CENTER);
        $draw->setTextAlignment(Imagick::ALIGN_CENTER);
        // $image->annotateImage($draw, 0, 0, 0, $gradient_text);
        $draw->annotation($x, $y, $gradient_text);
        $image->drawImage($draw);
        //if (1 == 2 && $product_type == '3') {
        if ($product_type == '3') {
            $img_d = $image->getImageGeometry();
            $img_w = $img_d['width'];
            $img_h = $img_d['height'];
            $crop_w = 486; // 600
            $crop_h = 486; // 600
            $crop_x = ($img_w - $crop_w) / 2;
            $crop_y = ($img_h - $crop_h) / 2;
            $image->cropImage($crop_w, $crop_h, $crop_x, $crop_y);
        }
        $target_file_name = 'admin_gradient_images/' . time() . '.png';
        $file_path = DIR_IMAGE . $target_file_name;
        if ($product_type == '3') { // for circluar pattern image attribute id
            if ($image->writeImage($file_path)) {
                $this->model_piyersoft_cases->updategradientimage($order_product_id, $target_file_name);
                return $target_file_name;
            } else {
                return false;
            }
        } else {
            $image->writeImage($file_path);
            return $file_path;
        }
    }

    function getimage() {

        if (!$this->request->post) {
            die;
        }

        //var_dump($this->request->post); die();
        $gradient_text = $this->request->post['gradienttext'];
        $pattern = $this->request->post['product_image'];
        $ref_img = $this->request->post['ref_img'];
        $product_type = $this->request->post['product_type'];

        $texture = ($this->request->post['texture'] == '' ? '1.jpg' : $this->request->post['texture']);

        $font_color = $this->request->post['customizeColor'];
        if ($texture == '1.jpg' && $font_color == '000000') {
            $color = '262626';
        }
        if ($texture == '8.jpg') {
            $texture = DIR_IMAGE . 'texture/t.png';
        } else {
            $texture = DIR_IMAGE . 'texture/' . $texture;
        }

        $gradient_font = DIR_APPLICATION . 'view/theme/' . $this->config->get('theme_default_directory') . '/font/PERTIBD.ttf';

        $gradient_texture = file_get_contents($texture);
        $im = new Imagick();
        $im->readImageblob($gradient_texture);

        /* Start a new pattern called "gradient" */
        $draw = new ImagickDraw();
        $draw->pushPattern('gradient', 0, 0, 80, 80);

        /* Composite the gradient on the pattern */
        $draw->composite(Imagick::COMPOSITE_OVER, 0, 0, 80, 80, $im);

        /* Close the pattern */
        $draw->popPattern();

        /* Use the pattern called "gradient" as the fill */
        $draw->setFillPatternURL('#gradient');

        /* Set the font family */
        $draw->setFont($gradient_font);

        /* Set text border and border width */
        $draw->setStrokeColor('#' . $font_color);
        $draw->setStrokeWidth(2);

        $length = strlen($gradient_text);
        if ($length > 3) {
            $gradient_text = substr($gradient_text, 0, 3);
            $length = 3;
        }

        if ($product_type == '3') { // for circular image parameter
            $font_size = 100;
            $x = 250; //256
            $y = 280; //290
            $angle = 0;
            if ($length == 2) {
                $font_size = 60; //70
                $x = 250; //255
                $y = 265; //273
            } elseif ($length == 3) {
                $font_size = 42; //50
                $x = 250; //256
                $y = 260; // 270
            }
        } else {
            $font_size = 150;
            $x = 256;
            $y = 290;
            $angle = 0;
            if ($length == 2) {
                $font_size = 100;
                $x = 252;
                $y = 273;
            } elseif ($length == 3) {
                $font_size = 80;
                $x = 252;
                $y = 270;
            }
        }

        
        $pattern = explode('https://' . $_SERVER['HTTP_HOST'] . '/', $pattern);
        $pattern = file_get_contents($pattern[1]);
        $image = new Imagick();
        $image->readImageblob($pattern);
        //$image->resizeImage(1000, 1000, Imagick::FILTER_LANCZOS, 1);
        $image->resizeImage(1000, 1000, Imagick::FILTER_LANCZOS, 1);

        $draw->setFontSize($font_size * 2);
        // $draw->setGravity(Imagick::GRAVITY_CENTER);
        $draw->setTextAlignment(Imagick::ALIGN_CENTER);
        // $image->annotateImage($draw, 0, 0, 0, $gradient_text);
        $draw->annotation($x * 2, $y * 2, $gradient_text);
        $image->drawImage($draw);
        $target_file_name = 'storage/' . time() . '_' . rand(0, 100000) . '.jpg';
        $file_path = DIR_IMAGE . $target_file_name;
        $image->writeImage($file_path);
        $p_src = HTTPS_SERVER . 'image/' . $target_file_name;
        echo json_encode(array('success' => 'success', 'src' => $p_src, 'ref' => $target_file_name));
        if ($ref_img != '' && file_exists(DIR_IMAGE . $ref_img))
            unlink(DIR_IMAGE . $ref_img);
    }

    function getverticaltextimage() {

        if (!$this->request->post) {
            die;
        }

        //$this->product->dump($this->request->post);
        //var_dump($this->request->post); die();
        $text = strtolower($this->request->post['customizetext']);
        $text = htmlspecialchars_decode(str_replace(array("&amp;", '&QUOT;'), array("&", '"'), $text));
        $product_mask = $this->request->post['product_mask'];
        $ref_img = $this->request->post['ref_img'];
        $font_color = $this->request->post['customizeColor'];
        $font_family = $this->request->post['customizeFont'];
        $product_id = $this->request->post['product_id'];

       // $this->product->dump($text);


        if (strpos($product_mask, '.png') != false) {
            $mask = imagecreatefrompng($product_mask);
            $xSize = imagesx($mask);
            $ySize = imagesy($mask);
        }

        $xSize = 1000;
        $ySize = 1000;

        $Picture = imagecreatetruecolor($xSize, $ySize);
        imagesavealpha($Picture, true);
        imagefill($Picture, 0, 0, imagecolorallocatealpha($Picture, 0, 0, 0, 127));
$font='';
        if ($text != '') {
            if ($font_color == '') {
                $font_color = '000000';
            }
            if ($font_family == '') {
                $font_family = 'Glitter';
            }
            if ($font_family == 'Glitter') {
                $font = 'glitter.ttf';
                $font_size = 100;
                $text = '[' . $text . ']';
            } else if ($font_family == 'RobotoMono') {
                $font = 'roboto-mono.ttf';
                $font_size = 75;
            } else if ($font_family == 'Runway') {
                $font = 'runway.ttf';
                $font_size = 55;
            }else if ($font_family == 'Besiktas') {
                $font = 'besiktas.ttf';
                $font_size = 70;
            }

            $color = $this->GetColor($Picture, $font_color);

            $newFontSize = 0;
            $angle = 90;

            $font = DIR_APPLICATION . 'view/theme/' . $this->config->get('theme_default_directory') . '/font/' . $font;

            //$x_ofset = 90;
            if ($font_family == 'Glitter') {
                //$x_ofset = 70;
                for ($i = 1; $i <= $ySize; $i++) {
                    $box = imagettfbbox($i, $angle, $font, $text);
                    $lT = $box[6] - $box[5];
                    $cP = round(($lT / $ySize) * 100, 1);
                    if ($cP >= $font_size) {
                        $newFontSize = $i;
                        break;
                    }
                }
                if ($newFontSize != 0)
                    $font_size = $newFontSize;
            }else {
                $text_count = mb_strlen($text, 'UTF-8');
                    if ($text_count == 1) {
                        $font_size = ($font_family == 'RobotoMono' ? 130 : 120);
                    } else if ($text_count == 2) {
                         $font_size = ($font_family == 'RobotoMono' ? 120 : 110);
                    } else if ($text_count == 3) {
                         $font_size = ($font_family == 'RobotoMono' ? 110 : 100);
                    } else if ($text_count == 4) {
                        $font_size = ($font_family == 'RobotoMono' ? 105 : 95);
                    } else if ($text_count == 5) {
                        $font_size = ($font_family == 'RobotoMono' ? 100 : 80);
                    } else if ($text_count == 6) {
                        $font_size = ($font_family == 'RobotoMono' ? 90 : 80);
                    } else if ($text_count == 7) {
                        $font_size = ($font_family == 'RobotoMono' ? 80 : 65);
                    } else if ($text_count == 8) {
                        $font_size = ($font_family == 'RobotoMono' ? 70 : 60);
                    } else if ($text_count == 9) {
                        $font_size = ($font_family == 'RobotoMono' ? 65 : 55);
                    } else if ($text_count == 10) {
                        $font_size = ($font_family == 'RobotoMono' ? 60 : 50);
                    } else if ($text_count == 11) {
                        $font_size = ($font_family == 'RobotoMono' ? 60 : 50);
                    } else if ($text_count == 12) {
                        $font_size = ($font_family == 'RobotoMono' ? 60 : 50);
                    } else if ($text_count == 13) {
                        $font_size = 50;
                    } else if ($text_count == 14) {
                        $font_size = 50;
                    } else if ($text_count == 15) {
                        $font_size = 50;
                    }
            }

            if (1 == 2) {
                $box = imagettfbbox($font_size, $angle, $font, $text);

                $xr = abs(max($box[2], $box[0]));
                $yr = abs(max($box[5], $box[3]));
                $x = intval(($xSize - $xr) / 2);
                $y = intval(($ySize + $yr) / 2);
            }
            $centerX = $xSize / 2;
            $centerY = $ySize / 2;

            list($left, $bottom, $right,,, $top) = imageftbbox($font_size, $angle, $font, $text);
            // Determine offset of text
            $left_offset = ($right - $left) / 2;
            $top_offset = ($bottom - $top) / 2;
            // Generate coordinates
            $x = $centerX - $left_offset;
            $y = $centerY + $top_offset;

            // $x = $x + round($font_size / 2);
             if($font_family == 'Glitter'){
                if (mb_strlen($text, 'UTF-8') == 1) {
                    $x += 55;
                } else if (mb_strlen($text, 'UTF-8') == 2) {
                    $x += 50;
                } else if (mb_strlen($text, 'UTF-8') == 3) {
                    $x += 50;
                } else if (mb_strlen($text, 'UTF-8') == 4) {
                    $x += 50;
                } else if (mb_strlen($text, 'UTF-8') == 5) {
                    $x += 45;
                } else if (mb_strlen($text, 'UTF-8') == 6) {
                    $x += 40;
                }
             }



            imagettftext($Picture, $font_size, $angle, $x + 40, $y, $color, $font, $text);

            if (1 == 1 && strpos($product_mask, '.png') != false) {
                $newPicture = imagecreatetruecolor($xSize, $ySize);
                imagesavealpha($newPicture, true);
                imagefill($newPicture, 0, 0, imagecolorallocatealpha($newPicture, 0, 0, 0, 127));
                for ($x = 320; $x < 650; $x++) {
                    for ($y = 100; $y < 950; $y++) {
                        $alpha = imagecolorsforindex($mask, imagecolorat($mask, $x, $y));

                        if (($alpha['red'] == 0) && ($alpha['green'] == 0) && ($alpha['blue'] == 0) && ($alpha['alpha'] == 0)) {
                            // It'   s a black part of the mask
                            imagesetpixel($newPicture, $x, $y, imagecolorallocatealpha($newPicture, 0, 0, 0, 127)); // Stick a black, but totally transparent, pixel in.
                        } else {

                            // Check the alpha state of the corresponding pixel of the image we're dealing with.
                            $alphaSource = imagecolorsforindex($Picture, imagecolorat($Picture, $x, $y));
                            if (($alphaSource['alpha'] == 127)) {
                                imagesetpixel($newPicture, $x, $y, imagecolorallocatealpha($newPicture, 0, 0, 0, 127)); // Stick a black, but totally transparent, pixel in.
                            } else {
                                $color = imagecolorsforindex($Picture, imagecolorat($Picture, $x, $y));
                                imagesetpixel($newPicture, $x, $y, imagecolorallocatealpha($newPicture, $color['red'], $color['green'], $color['blue'], $color['alpha'])); // Stick the pixel from the source image in
                            }
                        }
                    }
                }
            }
        }
        $target_file_name = 'storage/' . time() . '.jpg';
        $file_path = DIR_IMAGE . $target_file_name;
        if (strpos($product_mask, '.png') != false) {
            imagepng(($text != '' ? $newPicture : $Picture), $file_path);
        } else {
            imagepng($Picture, $file_path);
        }

        #------------------------------------------------
        //$mask = DIR_IMAGE . 'repository/knifes/HUAWEI-MATE_10_PRO-SILICON-SILICON_RED.PNG';  @Piyer603#
        //$mask = $this->model_tool_case_image_crop->crop();
        $item = '';
        $this->load->model('catalog/product');
        $product_info = $this->model_catalog_product->getProduct($product_id);
        $knife_path = DIR_IMAGE . 'repository/knifes/';
        $product['model'] = mb_convert_case($product_info['model'], MB_CASE_UPPER, "UTF-8");
        if ($product_info['image']) {
            $item = explode('/', $product_info['image']);

            if (isset($item[3])) {
                $item = $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';
                }

                $item = $knife_path . $item[0] . '-' . $item[1] . '-' . $item[2] . '-' . $item[3] . '.PNG';
            }
        }

        $base = new Imagick($file_path); // isim yazılmış resim

        $mask = new Imagick($item); // telefon kasasının bıçağı
        $mask->scaleImage(1000, 1000, false);

        $base->setImageMatte(1);

        $base->compositeImage($mask, Imagick::COMPOSITE_DSTIN, 0, 0); //orignal transparent

        $masked_image = 'storage/' . time() . '.png';
        $masked_image_dir = DIR_IMAGE . $masked_image;
        $masked_image_url = HTTPS_SERVER . '/image/' . $masked_image;
        $base->writeImage($masked_image_dir);

        #------------------------------------------------


        $p_src = HTTPS_SERVER . 'image/' . $target_file_name;

        echo json_encode(array('success' => 'success', 'src' => $masked_image_url, 'ref' => $target_file_name));
        if ($ref_img != '' && file_exists(DIR_IMAGE . $ref_img))
            unlink(DIR_IMAGE . $ref_img);
    }
    
    function getverticalrighttextimage() {

        if (!$this->request->post) {
            die;
        }

        //$this->product->dump($this->request->post);
        //var_dump($this->request->post); die();
        $text = strtolower($this->request->post['customizetext']);
        $text = htmlspecialchars_decode(str_replace(array("&amp;", '&QUOT;'), array("&", '"'), $text));
        $product_mask = $this->request->post['product_mask'];
        $ref_img = $this->request->post['ref_img'];
        $font_color = $this->request->post['customizeColor'];
        $font_family = $this->request->post['customizeFont'];
        $product_id = $this->request->post['product_id'];


        if (strpos($product_mask, '.png') != false) {
            $mask = imagecreatefrompng($product_mask);
            $xSize = imagesx($mask);
            $ySize = imagesy($mask);
        }

        $xSize = 1000;
        $ySize = 1000;

        $Picture = imagecreatetruecolor($xSize, $ySize);
        imagesavealpha($Picture, true);
        imagefill($Picture, 0, 0, imagecolorallocatealpha($Picture, 0, 0, 0, 127));
$font='';
        if ($text != '') {
            if ($font_color == '') {
                $font_color = '000000';
            }
            if ($font_family == '') {
                $font_family = 'Glitter';
            }
            if ($font_family == 'Glitter') {
                $font = 'glitter.ttf';
                $font_size = 100;
                $text = '[' . $text . ']';
            } else if ($font_family == 'RobotoMono') {
                $font = 'roboto-mono.ttf';
                $font_size = 75;
            } else if ($font_family == 'Runway') {
                $font = 'runway.ttf';
                $font_size = 55;
            }else if ($font_family == 'Besiktas') {
                $font = 'besiktas.ttf';
                $font_size = 70;
            }

            $color = $this->GetColor($Picture, $font_color);

            $newFontSize = 0;
            $angle = 90;

            $font = DIR_APPLICATION . 'view/theme/' . $this->config->get('theme_default_directory') . '/font/' . $font;
            //$x_ofset = 90;
            if ($font_family == 'Glitter') {
                //$x_ofset = 70;
                for ($i = 1; $i <= $ySize; $i++) {
                    $box = imagettfbbox($i, $angle, $font, $text);
                    $lT = $box[6] - $box[5];
                    $cP = round(($lT / $ySize) * 100, 1);
                    if ($cP >= $font_size) {
                        $newFontSize = $i;
                        break;
                    }
                }
                if ($newFontSize != 0)
                    $font_size = $newFontSize;
            }else {
                $text_count = mb_strlen($text, 'UTF-8');
                    if ($text_count == 1) {
                        $font_size = ($font_family == 'RobotoMono' ? 130 : 120);
                    } else if ($text_count == 2) {
                         $font_size = ($font_family == 'RobotoMono' ? 120 : 110);
                    } else if ($text_count == 3) {
                         $font_size = ($font_family == 'RobotoMono' ? 110 : 100);
                    } else if ($text_count == 4) {
                        $font_size = ($font_family == 'RobotoMono' ? 105 : 95);
                    } else if ($text_count == 5) {
                        $font_size = ($font_family == 'RobotoMono' ? 100 : 80);
                    } else if ($text_count == 6) {
                        $font_size = ($font_family == 'RobotoMono' ? 90 : 80);
                    } else if ($text_count == 7) {
                        $font_size = ($font_family == 'RobotoMono' ? 80 : 65);
                    } else if ($text_count == 8) {
                        $font_size = ($font_family == 'RobotoMono' ? 70 : 60);
                    } else if ($text_count == 9) {
                        $font_size = ($font_family == 'RobotoMono' ? 65 : 55);
                    } else if ($text_count == 10) {
                        $font_size = ($font_family == 'RobotoMono' ? 60 : 50);
                    } else if ($text_count == 11) {
                        $font_size = ($font_family == 'RobotoMono' ? 60 : 50);
                    } else if ($text_count == 12) {
                        $font_size = ($font_family == 'RobotoMono' ? 60 : 50);
                    } else if ($text_count == 13) {
                        $font_size = 50;
                    } else if ($text_count == 14) {
                        $font_size = 50;
                    } else if ($text_count == 15) {
                        $font_size = 50;
                    }
            }

            if (1 == 2) {
                $box = imagettfbbox($font_size, $angle, $font, $text);

                $xr = abs(max($box[2], $box[0]));
                $yr = abs(max($box[5], $box[3]));
                $x = intval(($xSize - $xr) / 2);
                $y = intval(($ySize + $yr) / 2);
            }
            $centerX = $xSize / 2;
            $centerY = $ySize / 2;

            list($left, $bottom, $right,,, $top) = imageftbbox($font_size, $angle, $font, $text);
            // Determine offset of text
            $left_offset = ($right - $left) / 2;
            $top_offset = ($bottom - $top) / 2;
            // Generate coordinates
            $x = $centerX - $left_offset;
            $y = $centerY + $top_offset;

            // $x = $x + round($font_size / 2);
             if($font_family == 'Glitter'){
            if (mb_strlen($text, 'UTF-8') == 1) {
                $x += 55;
            } else if (mb_strlen($text, 'UTF-8') == 2) {
                $x += 50;
            } else if (mb_strlen($text, 'UTF-8') == 3) {
                $x += 50;
            } else if (mb_strlen($text, 'UTF-8') == 4) {
                $x += 50;
            } else if (mb_strlen($text, 'UTF-8') == 5) {
                $x += 45;
            } else if (mb_strlen($text, 'UTF-8') == 6) {
                $x += 40;
            }
             }


            imagettftext($Picture, $font_size, $angle, $x + 170, $y, $color, $font, $text);

            if (1 == 1 && strpos($product_mask, '.png') != false) {
                $newPicture = imagecreatetruecolor($xSize, $ySize);
                imagesavealpha($newPicture, true);
                imagefill($newPicture, 0, 0, imagecolorallocatealpha($newPicture, 0, 0, 0, 127));
                for ($x = 320; $x < 650; $x++) {
                    for ($y = 100; $y < 950; $y++) {
                        $alpha = imagecolorsforindex($mask, imagecolorat($mask, $x, $y));

                        if (($alpha['red'] == 0) && ($alpha['green'] == 0) && ($alpha['blue'] == 0) && ($alpha['alpha'] == 0)) {
                            // It'   s a black part of the mask
                            imagesetpixel($newPicture, $x, $y, imagecolorallocatealpha($newPicture, 0, 0, 0, 127)); // Stick a black, but totally transparent, pixel in.
                        } else {

                            // Check the alpha state of the corresponding pixel of the image we're dealing with.
                            $alphaSource = imagecolorsforindex($Picture, imagecolorat($Picture, $x, $y));
                            if (($alphaSource['alpha'] == 127)) {
                                imagesetpixel($newPicture, $x, $y, imagecolorallocatealpha($newPicture, 0, 0, 0, 127)); // Stick a black, but totally transparent, pixel in.
                            } else {
                                $color = imagecolorsforindex($Picture, imagecolorat($Picture, $x, $y));
                                imagesetpixel($newPicture, $x, $y, imagecolorallocatealpha($newPicture, $color['red'], $color['green'], $color['blue'], $color['alpha'])); // Stick the pixel from the source image in
                            }
                        }
                    }
                }
            }
        }
        $target_file_name = 'storage/' . time() . '.jpg';
        $file_path = DIR_IMAGE . $target_file_name;
        if (strpos($product_mask, '.png') != false) {
            imagepng(($text != '' ? $newPicture : $Picture), $file_path);
        } else {
            imagepng($Picture, $file_path);
        }

        #------------------------------------------------
        //$mask = DIR_IMAGE . 'repository/knifes/HUAWEI-MATE_10_PRO-SILICON-SILICON_RED.PNG';  @Piyer603#
        //$mask = $this->model_tool_case_image_crop->crop();
        $item = '';
        $this->load->model('catalog/product');
        $product_info = $this->model_catalog_product->getProduct($product_id);
        $knife_path = DIR_IMAGE . 'repository/knifes/';
        $product['model'] = mb_convert_case($product_info['model'], MB_CASE_UPPER, "UTF-8");
        if ($product_info['image']) {
            $item = explode('/', $product_info['image']);

            if (isset($item[3])) {
                $item = $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';
                }

                $item = $knife_path . $item[0] . '-' . $item[1] . '-' . $item[2] . '-' . $item[3] . '.PNG';
            }
        }

        $base = new Imagick($file_path); // isim yazılmış resim

        $mask = new Imagick($item); // telefon kasasının bıçağı
        $mask->scaleImage(1000, 1000, false);

        $base->setImageMatte(1);

        $base->compositeImage($mask, Imagick::COMPOSITE_DSTIN, 0, 0); //orignal transparent

        $masked_image = 'storage/' . time() . '.png';
        $masked_image_dir = DIR_IMAGE . $masked_image;
        $masked_image_url = HTTPS_SERVER . '/image/' . $masked_image;
        $base->writeImage($masked_image_dir);

        #------------------------------------------------


        $p_src = HTTPS_SERVER . 'image/' . $target_file_name;

        echo json_encode(array('success' => 'success', 'src' => $masked_image_url, 'ref' => $target_file_name));
        if ($ref_img != '' && file_exists(DIR_IMAGE . $ref_img))
            unlink(DIR_IMAGE . $ref_img);
    }

    function saveCanvasImage_bakup() {

        if (!$this->request->post) {
            die;
        }

        $json = array();

        $cart_id = $this->request->post['cart_id'];
        $canvas_img = $this->request->post['canvas_img'];
        $this->load->model('piyersoft/cases');

        //$log = new Log("saveCanvasImage.txt");
        //$log->write($canvas_img);


        if ($cart_id != '' && $canvas_img != '') {

            $imagedata = base64_decode($canvas_img);
            $image = new Imagick();
            $image->readImageblob($imagedata);

            $imageprops = $image->getImageGeometry();
            $width = $imageprops['width'];
            $height = $imageprops['height'];
            if ($width > $height) {
                $newHeight = 100;
                $newWidth = (100 / $height) * $width;
            } else {
                $newWidth = 100;
                $newHeight = (100 / $width) * $height;
            }

            $image->resizeImage($newWidth, $newHeight, imagick::FILTER_LANCZOS, 0.9, true);


            $filename = md5(uniqid(rand(), true));
            $customer_order_image = 'customer_order_images/' . $filename . '.jpg';
            $file = DIR_IMAGE . $customer_order_image;
            $image->writeImage($file);
            $this->model_piyersoft_cases->updateCanvasImage($cart_id, $customer_order_image);
            $json['file'] = $file;
        } else {
            var_dump("Sorun oluştur");
            die();
        }


        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    function saveCanvasImage() {

        if (!$this->request->post) {
            die;
        }

        $json = array();

        $cart_id = $this->request->post['cart_id'];
        $canvas_img = $this->request->post['canvas_img'];


        if ($cart_id != '' && $canvas_img != '') {

            $this->load->model('piyersoft/cases');
            $imagedata = base64_decode($canvas_img);
            $filename = md5(uniqid(rand(), true));
            $customer_order_image = 'customer_order_images/' . $filename . '.jpg';
            $file = DIR_IMAGE . $customer_order_image;
            file_put_contents($file, $imagedata);
            $this->model_piyersoft_cases->updateCanvasImage($cart_id, $customer_order_image);
            $json['file'] = $file;
        } else {
            var_dump("Sorun oluştur");
            die();
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    public function seecreeonshoot() {
        $html = htmlentities($this->request->post['html']);

        var_dump($html);
        die();
    }

    public function deleteGenerateImage() {

        $json = array();
        $json['success'] = 0;
        $json['error'] = '';
        if (isset($this->request->post['order_product_id'])) {
            $order_product_id = $this->request->post['order_product_id'];
            $get_order_product = $this->db->query("SELECT * FROM ps_order_product WHERE order_product_id = '" . (int) $order_product_id . "' ");

            if ($get_order_product->row) {

                if (file_exists(DIR_IMAGE . $get_order_product->row['admin_pattern_image'])) {
                    if (unlink(DIR_IMAGE . $get_order_product->row['admin_pattern_image'])) {
                        $this->db->query("UPDATE ps_order_product SET admin_pattern_image = '' WHERE order_product_id = '" . (int) $order_product_id . "' ");
                    } else {
                        $json['error'] .= DIR_IMAGE . $get_order_product->row['admin_pattern_image'] . ' => Bu dosya silinemedi! <br>';
                    }
                } else if ($get_order_product->row['admin_pattern_image']) {
                    $this->db->query("UPDATE ps_order_product SET admin_pattern_image = '' WHERE order_product_id = '" . (int) $order_product_id . "' ");
                } else {
                    $json['error'] .= DIR_IMAGE . $get_order_product->row['admin_pattern_image'] . ' => Böyle bir dosya yok! <br>';
                }

                if (file_exists(DIR_IMAGE . $get_order_product->row['admin_gradient_pattern_image'])) {
                    if (unlink(DIR_IMAGE . $get_order_product->row['admin_gradient_pattern_image'])) {
                        $this->db->query("UPDATE ps_order_product SET admin_gradient_pattern_image = '' WHERE order_product_id = '" . (int) $order_product_id . "' ");
                    } else {
                        $json['error'] .= DIR_IMAGE . $get_order_product->row['admin_gradient_pattern_image'] . ' => Bu dosya silinemedi! <br>';
                    }
                } else {
                    $json['error'] .= DIR_IMAGE . $get_order_product->row['admin_gradient_pattern_image'] . ' => Böyle bir dosya yok! <br>';
                }

                if (!$json['error']) {
                    $json['success'] = 1;
                }
            }


            //$this->db->query("UPDATE ps_order_product SET admin_gradient_pattern_image = '' AND customer_pattern_data = '' ");
            //$json['success'] = 1;
        } else {
            $json['error'] = 'Başarısız!';
        }




        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

}
