<?php

class ControllerpiyerSoftCases extends Controller {

    public function index() {

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

    public function GenerateDpiImage() {
        //die("HEHEHE");

        if (!$this->request->post) {
            //die;
        }
        $this->load->model('piyersoft/cases');
        $order_product_id = $this->request->post['order_product_id'];
        $customer_pattern_data = json_decode(str_replace('&quot;', '"', $this->request->post['customer_pattern_data']));
        $pattern = DIR_IMAGE . 'patterns/' . strtoupper($this->request->post['pattern_code']) . '.png';
        $text = $customer_pattern_data->pattern_text;
        $font_family = $customer_pattern_data->font;
        $font_color = $customer_pattern_data->font_color;
        $text_position = $customer_pattern_data->text_pos;
        if (!is_file($pattern)) {

            die('pattern code was not found');
        }

        //die($pattern);

        $picture = imagecreatefrompng($pattern);

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

        // Get sizes and set up new picture
        $width = imagesx($picture);
        $height = imagesy($picture);
        imagesavealpha($picture, true);
        $color = $this->GetColor($picture, $font_color);

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

        if ($text) {

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

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

            $xr = abs(max($box[2], $box[4]));
            $yr = abs(max($box[5], $box[7]));

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

            // check text position
            if ($text_position == 'Bottom' || $text_position == '') {
                $y = $height - 180;
            }

//            $bg_color = imagecolorallocate($picture, 0, 102, 204); // blue border 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
            }
            $border_pixel = 15;

            $this->imagettfborder($picture, $font_size, $angle, $x, $y, -$bg_color, $font, $text, $border_pixel);
            imagettftext($picture, $font_size, $angle, $x, $y, -$color, $font, $text);
        }
        //var_dump($picture);
        //die();
        $xSize = imagesx($picture);
        $ySize = imagesy($picture);
        //echo $ySize;
        //die();
        $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
                    }
                }
            }
        }

        $file_name = 'pattern_' . time() . '.png';
        $target_file_name = 'admin_pattern_images/' . $file_name;
        $res = imagepng($newPicture, DIR_IMAGE . $target_file_name);
        imagedestroy($newPicture);
        //die();
        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('1^^^' . $target_file_name);
        }
    }

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

    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);
                echo json_encode(array('responce' => 'success', 'file' => $target_file_name));
            }
        }
    }

}
