<?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 GenerateDpiImage() {

        if (!$this->request->post) {
            die;
        }
        
        
        $o_id = isset($this->request->post['order_product_id'])?$this->request->post['order_product_id']:-1;
        $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']:'';
        
        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)?$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)?$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:'';
        
        $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;
        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 ($product_type == '4') {
            $pattern = DIR_IMAGE . 'patterns/type5_pattern.png';
        }

        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 {
            $picture = imagecreatefrompng($pattern);
        }

        imagesavealpha($picture, true);
        if ($text) {
            if ($product_type == 4) {
                $angle = 0;
                if ($text_position == 'Vertical') {
                    $angle = 90;
                }
                if ($font_family == 'Glitter') {
                    $font = 'glitter.ttf';
                    $font_size = 130;
                    $text = '[' . $text . ']';
                } else if ($font_family == 'RobotoMono') {
                    $font = 'roboto-mono.ttf';
                    $font_size = 150;
                } else if ($font_family == 'Runway') {
                    $font = 'runway.ttf';
                    $font_size = 150;
                }
            } else {
                $angle = 0;
                if ($font_family == 'Glitter') {
                    $font = 'glitter.ttf';
                    $font_size = 130;
                    $text = '[' . $text . ']';
                } else if ($font_family == 'RobotoMono') {
                    $font = 'roboto-mono.ttf';
                    $font_size = 80;
                } else if ($font_family == 'Runway') {
                    $font = 'runway.ttf';
                    $font_size = 80;
                }
            }

            $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);


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

            ##Bilal 22-12-19
            if ($font_family == 'Glitter' AND $product_type != 4) {
                if (strlen($text) == 3) {
                    $font_size -= 45;
                } 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;
                }
            } 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;
                }
            }
            ##Bilal 22-12-19


            $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;
                }

                //$x = $x + round($font_size / 2);
                //var_dump($x);
                //var_dump($y); die();
            } 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 == 'Bottom' || $text_position == '') {
                    $y = $height - 180;
                }

                ##Bilal 22-12-19
                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;
                    }
                    ##Bilal 22-12-19
                } 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;
                    }
                }
            }

            $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 = 15;
            $border_pixel = 10;



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


            $xSize = imagesx($picture);
            $ySize = imagesy($picture);

            $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
        if ($product_type != '4') {
            // Marka - Model - Koleksiyon - Renk
            $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'] . "' ")->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;
            $file_name = $new_file_name . '.png';
        }else {
            $file_name = time() . '.png';
        }
        ##Bilal 23-12-2019


        $target_file_name = 'admin_pattern_images/' . $file_name;
        $res = imagepng(($text ? $newPicture : $picture), DIR_IMAGE . $target_file_name);
        if ($text)
            imagedestroy($newPicture);
        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);
            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 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, 55, 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() {
        //die('here');
        $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 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 = time() . '.' . $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);
            $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'];
                $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 = 'cropped' . $pathinfo['basename'];
                $target_file_name = 'upload/' . $fileName;
                $imagick->writeImage(DIR_IMAGE . $target_file_name);



                $im = new Imagick();
                $orignal_img = file_get_contents(DIR_IMAGE . $target_file_name);
                $im->readImageblob($orignal_img);
                if (1 == 2) {
                    $orignal_width = $im->getImageWidth();
                    $orignal_height = $im->getImageHeight();
                    $desire_width = 1080;
                    $desire_height = 1920;
                    $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;
                    }
                    $scale_value = $width / $prewidth;

                    $width = $im->getImageWidth() * round($scale_value, 4);

                    // $x = round($x * $desire_width);
                    //$y = round($y * $desire_height);

                    $im->scaleImage($width, 0);
                    $im->rotateImage(new \ImagickPixel(), $angle);
                    $im->cropImage($desire_width, $desire_height, 0, 0);
                }

                $im->resizeImage(1080, 1920, Imagick::FILTER_LANCZOS, 1);
                $orignal_file_name = 'upload/' . $pathinfo['basename'];
                $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 */

        $pattern = file_get_contents($pattern);
        $image = new Imagick();
        $image->readImageblob($pattern);
        $length = strlen($gradient_text);
        if (1 == 2 && $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 = 250;
                $y = 1050;
            } elseif ($length == 3) {
                $font_size = 170;
                $y = 1030;
            }
        }

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


        $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') {
            $img_d = $image->getImageGeometry();
            $img_w = $img_d['width'];
            $img_h = $img_d['height'];
            $crop_w = 600;
            $crop_h = 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;
        }
        $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 = 256;
            $y = 290;
            $angle = 0;
            if ($length == 2) {
                $font_size = 70;
                $x = 255;
                $y = 273;
            } elseif ($length == 3) {
                $font_size = 50;
                $x = 256;
                $y = 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 = file_get_contents($pattern);
        $image = new Imagick();
        $image->readImageblob($pattern);
        $image->resizeImage(500, 500, Imagick::FILTER_LANCZOS, 1);

        $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);
        $target_file_name = 'storage/' . time() . '.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;
        }

        $text = strtoupper($this->request->post['customizetext']);
        $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'];

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));
       
        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 = 60;
            }

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

            $newFontSize = 0;
            $angle = 90;

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

            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 {
                for ($i = 10; $i > strlen($text); $i--) {
                    $font_size += 15;
                }
            }

            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);

            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);
       }
        $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 saveCanvasImage() {
        if (!$this->request->post) {
            die;
        }

        $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 . '.png';
            $file = DIR_IMAGE . $customer_order_image;
            file_put_contents($file, $imagedata);
            $this->model_piyersoft_cases->updateCanvasImage($cart_id, $customer_order_image);
        }
    }

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

        var_dump($html);
        die();
    }

}
