<?php

defined('ROOT') or define('ROOT', realpath(dirname(__FILE__) . '/..'));
defined('PUBLIC_PATH') or define('PUBLIC_PATH', ROOT . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR);
defined('LOG_PATH') or define('LOG_PATH', ROOT . DIRECTORY_SEPARATOR . 'log' . DIRECTORY_SEPARATOR);

$appConfig = include_once '../configs/app.php';
$resolutions = include_once '../configs/resolutions.php';

output();

function output() {
    global $appConfig, $resolutions;
    $pathInfo = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
    $pathInfo = preg_replace('/\?(.*)(?=.*)/', '', $pathInfo);
    $cache = isset($_GET['cache']) ? ($_GET['cache'] == 'false' ? false : true) : true;
    $paths = explode('/', $pathInfo);
    $template = NULL;
    $size = NULL;
    $checkSum = '';
    $index = 0;
    try {
        if (count($paths)) {
            if (!$paths[$index]) {
                unset($paths[$index++]);
            }
            $checkSum = reset($paths);
            if ($checkSum) {
                unset($paths[$index++]);
            } else {
                throw new Exception('Image is not exist');
            }
            while ($next = reset($paths)) {
                if (!$next) { break; }
                if (!$size && preg_match('/^\d{1,}x\d{1,}$/', $next)) {
                    $size = $next;
                    unset($paths[$index++]);
                } else if (!$template && ($templateFile = getTemplateFile($next))) {
                    $template = $templateFile;
                    unset($paths[$index++]);
                }
                else {
                    // if (preg_match('/^' . $appConfig['json_prefix'] . '/', $next)) {
                    //     $next = preg_replace('/^' . $appConfig['json_prefix'] . '/', '', $next);
                    //     $extraInfo = getExtraInfo($next);
                    //     unset($paths[$index++]);
                    // }
                    break;
                }
            }

            $file = implode('/', $paths);
            $file = preg_replace('/_img_\d{3,4}x\d{3,4}_[a-zA-Z\d]{6}_fit_center/', '', $file);
            // checkSum($checkSum, $file, $size);
            if ($checkSum != $appConfig['key']) {
                throw new Exception('Image is not exist');
            }
            $localPath = getLocalPath($file, $size, $template);
            $img = NULL;
            if ($cache && $localPath) {
                $time = filectime($localPath);
                if (time() - $time < $appConfig['cache_time']) {
                    $img = initImageFromLocal($localPath);
                }
            }
            if (!$img) {
                $productId = isset($_REQUEST['product_id']) ? $_REQUEST['product_id'] : 0;
                $extraInfo = extraInfoProduct($productId);
                $img = initImage($file, $size, $template, $extraInfo);
                $img->setImageCompressionQuality($appConfig['compression']);
                saveFile($img, $file, $size, $template);
            }
            header('Content-Type: ' . $img->getImageMimeType());
            // header('Content-Length: ' . $img->getImageLength());
            echo $img->getImageBlob();
        }
    } catch (Exception $e) {
        logError($e);
        header('Content-Type: image/jpg');
        echo file_get_contents($appConfig['templates_path'] . $appConfig['default_img']);
    }
    exit();
}

function logError($e) {
    $str = '';
    $str .= date('Y-m-d H:i:s') . ': ' . $e->getMessage() . PHP_EOL;
    $str .= 'Throw exception at line ' . $e->getLine() . PHP_EOL;
    $str .= $e->getTraceAsString() . PHP_EOL;
    $logFile = LOG_PATH . 'error_' . date('Ymd') . '.log';
    $handle = fopen($logFile, 'a+');
    fwrite($handle, $str);
    fclose($handle);
}

function logInfo($content) {
    $logFile = LOG_PATH . 'info_' . date('Ymd') . '.log';
    $handle = fopen($logFile, 'a+');
    fwrite($handle, date('Y-m-d H:i:s') . ': ' . $content . PHP_EOL);
    fclose($handle);
}

function checkSum($checkSum, $fileName, $size) {
    global $appConfig;
    $hash = substr(md5($fileName . $size . $appConfig['salt']), 0, 10);
    if ($checkSum != $hash) {
        throw new Exception('Image is not exist');
    }
}

function getTemplateFile($template) {
    global $appConfig;
    $files = scandir($appConfig['templates_path']);
    foreach ($files as $f) {
        if (in_array($f, ['.', '..', '.DS_Store', $appConfig['default_img']])) {
            continue;
        }
        if ($template == preg_replace('/\.(.+)$/', '', $f)) {
            return $f;
        }
    }
    return NULL;
}

function getExtraInfo($str) {
    $str = base64_decode($str);
    $arr = @json_decode($str, true);
    if (isset($arr['title']) || isset($arr['gift_image_path']) || isset($arr['price']) || isset($arr['main_price'])) {
        return [
            'title' => isset($arr['title']) ? $arr['title'] : '',
            'gift_image_path' => isset($arr['gift_image_path']) ? $arr['gift_image_path'] : '',
            'price' => isset($arr['price']) ? $arr['price'] : '',
            'main_price' => isset($arr['main_price']) ? $arr['main_price'] : ''
        ];
    }
    return NULL;
}

function extraPath($extraInfo) {
    $extraPath = '';
    if ($extraInfo) {
        $extraPath = md5(implode('', array_values($extraInfo))) . DIRECTORY_SEPARATOR;
    }
    return $extraPath;
}

function getLocalPath($file, $size, $template) {
    global $appConfig;
    $path = $appConfig['cache_path'] . ($size ? $size . DIRECTORY_SEPARATOR : '') . ($template ? $template . DIRECTORY_SEPARATOR : '') . $file;
    if (file_exists($path)) {
        return $path;
    }
    return NULL;
}

function saveFile($img, $file, $size, $template) {
    global $appConfig;
    $path = $appConfig['cache_path'] . ($size ? $size . DIRECTORY_SEPARATOR : '') . ($template ? $template . DIRECTORY_SEPARATOR : '') . $file;
    $dir = preg_replace('/\/[^\/]*$/', '', $path);
    if (!file_exists($dir) && !mkdir($dir, 0755, true)) {
        // $fileName = array_pop(explode($file));
        return;
    }
    file_put_contents($path, $img->getImageBlob());
}

function removeFile($file, $size, $template) {
    global $appConfig;
    $path = $appConfig['cache_path'] . ($size ? $size . DIRECTORY_SEPARATOR : '') . ($template ? $template . DIRECTORY_SEPARATOR : '') . $fileName;
    if (file_exists($path)) {
        unlink($path);
    }
}

function initImageFromLocal($file) {
    $img = new Imagick($file);
    return $img;
}

function getProduct($productId) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.hasaki.vn/mobile/v1/detail/product?product_id=" . $productId);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    if (!$res = curl_exec($ch)){
        logInfo(curl_error($ch));
        return NULL;
    }
    curl_close($ch);
    return $res;
}

function extraInfoProduct($productId) {
    $product = $productId ? getProduct($productId) : NULL;
    $default = [
        'gift' => '',
        'gift_price' => '',
        'gift_text' => '',
        'market_price' => '',
        'real_price' => '',
        'promotion_text' => '', //'Miễn phí giao hàng 2H - HCM từ 90k trừ Huyện',
        'name' => ''
    ];
    if ($product && ($product = @json_decode($product, true)) && !$product['status']['error_code']) {
        if (isset($product['data']['blocks'])) {
            $blocks = $product['data']['blocks'];
            foreach ($blocks as $b) {
                if ($b['type'] == 'CommonInfo') {
                    if (isset($b['common_data']['market_price'])) {
                        $default['market_price'] = number_format($b['common_data']['market_price'], 0, ',', '.') . 'Đ';
                    }
                    if (isset($b['common_data']['name'])) {
                        $default['name'] = $b['common_data']['name'];
                    }
                    //
                    if (isset($b['common_data']['price'])) {
                        $default['real_price'] = number_format($b['common_data']['price'], 0, ',', '.') . 'Đ';
                    }

                    // if (isset($b['common_data']['promotion_text'])) {
                    //     $default['promotion_text'] = $b['common_data']['promotion_text'];
                    // }

                    if (isset($b['common_data']['gift']['group_selection'][0]['items'][0])) {
                        $g = $b['common_data']['gift']['group_selection'][0]['items'][0];
                        $g['image'] = preg_replace('/_img_\d{3,4}x\d{3,4}_[a-zA-Z\d]{6}_fit_center/', '', $g['image']);
                        $default['gift'] = $g['image'];
                        $default['gift_price'] = $g['price'] / 1000 . 'K';
                        $default['gift_text'] = $g['name'];
                    }
                    break;
                }
            }
        }
    }

    return $default;
}

// function initImage($fileName, $size, $template, $extraInfo) {
//     $blob = @file_get_contents($fileName);
//     if ($blob) {
//         $img = new Imagick();
//         if ($img->readImageBlob($blob)) {
//             if ($size) {
//                 list($width, $height) = explode('x', $size);
//                 $img = resizeImage($img, $width, $height);
//             }
//             if ($template) {
//                 $img = applyTemplate($img, $template, $extraInfo);
//             } elseif ($extraInfo) {
//                 $img = applyExtraGift($img, $extraInfo);
//             }
//             if ($extraInfo) {
//                 $img = applyExtraText($img, $extraInfo);
//             }
//             return $img;
//         }
//     }
//     throw new Exception('Image is not exist');
// }

function initImage($fileName, $size, $template, $extraInfo) {
    $img = image($fileName);
    $imgGift = $extraInfo['gift'] ? image($extraInfo['gift'], true) : NULL;
    $last = draw($img, $imgGift, $size, $template, $extraInfo);
    return $last;
}

function resizeImage($img, $width, $height) {
    $imgWidth = $img->getImageWidth();
    $imgHeight = $img->getImageHeight();

    $ratioImg = $imgWidth / $imgHeight;
    $ratio = $width / $height;

    if ($ratioImg > $ratio) { // hinh goc co ti le chieu rong > hinh can lay => lay chieu dai lam chuan
        $newWidth = $imgHeight * $ratio;
        $img->cropImage($newWidth, $imgHeight, ($imgWidth - $newWidth) / 2, 0);
    } else if ($ratioImg < $ratio) {
        $newHeight = $imgWidth * $ratio;
        $img->cropImage($width, $newHeight, 0, ($imgHeight - $newHeight) / 2);
    }
    if ($imgWidth > $width) {
        $img->resizeImage($width, $height, Imagick::FILTER_UNDEFINED, 1);
        $img->unsharpMaskImage(0 , 0.5 , 1 , 0.05);
    }
    return $img;
}

function applyTemplate($img, $templateFile, $extraInfo, $paddingCustom = NULL) {
    global $appConfig;
    $imgWidth = $img->getImageWidth();
    $imgHeight = $img->getImageHeight();
    $templateImg = new Imagick($appConfig['templates_path'] . $templateFile);
    if ($imgWidth != $templateImg->getImageWidth() || $imgHeight!= $templateImg->getImageHeight()) {
        $templateImg->resizeImage($imgWidth, $imgHeight, Imagick::FILTER_UNDEFINED, 1);
    }
    $padding = $paddingCustom ? $paddingCustom / 100 : ($extraInfo['real_price'] ? $appConfig['padding_main_price'] : $appConfig['padding']) / 100;
    if ($padding) {
        // tao 1 background = voi kich thuoc cua hinh
        $backgroundImg = new Imagick();
        $backgroundImg->newImage($imgWidth, $imgHeight, new ImagickPixel('white'), str_replace('image/', '', $img->getImageMimeType()));
        //  scale lai img dua tren padding
        $img->resizeImage($imgWidth * (1 - $padding * 2), $imgHeight * (1 - $padding * 2), Imagick::FILTER_UNDEFINED, 1);
        $img->unsharpMaskImage(0 , 0.5 , 1 , 0.05);
        if ($paddingCustom) {
            $backgroundImg->compositeImage($img, Imagick::COMPOSITE_OVER, $imgWidth * $padding, $imgHeight * $padding);
        } else {
            $backgroundImg->compositeImage($img, Imagick::COMPOSITE_OVER, $imgWidth * $padding, $imgHeight * $padding * ($extraInfo['real_price'] ? 1.3 : 1));
        }
        // if ($extraInfo) {
        //     applyExtraGift($backgroundImg, $extraInfo);
        // }
        $backgroundImg->compositeImage($templateImg, Imagick::COMPOSITE_OVER, 0, 0);
        return $backgroundImg;
    } else {
        // if ($extraInfo) {
        //     applyExtraGift($img, $extraInfo);
        // }
        $img->compositeImage($templateImg, Imagick::COMPOSITE_OVER, 0, 0);
        return $img;
    }
}

function applyExtraGift($img, $extraInfo) {
    global $appConfig;
    $imgWidth = $img->getImageWidth();
    $imgHeight = $img->getImageHeight();
    if ($extraInfo['gift']) {
        $blob = @file_get_contents($appConfig['src_host'] . $extraInfo['gift']);
        $giftImgWidth = $imgWidth / 5;
        $giftImgHeight = $imgHeight / 5;
        $giftImg = new Imagick();
        if ($giftImg->readImageBlob($blob)) {
            $giftImg->resizeImage($giftImgWidth, $giftImgHeight, Imagick::FILTER_UNDEFINED, 1);
            $giftImg->unsharpMaskImage(0 , 0.5 , 1 , 0.05);
            $img->compositeImage($giftImg, Imagick::COMPOSITE_OVER, $imgWidth / 5 * 3.8, $imgHeight * 0.91 - $giftImgHeight);
        }
    }
    return $img;
}

function applyExtraText($img, $extraInfo) {
    global $appConfig;
    $imgWidth = $img->getImageWidth();
    $imgHeight = $img->getImageHeight();
    if ($extraInfo['promotion_text']) {
        $draw = new ImagickDraw();
        $draw->setFont(PUBLIC_PATH . '/fonts/montserrat/Montserrat-Black.otf');
        $draw->setTextAlignment(Imagick::ALIGN_LEFT);
        $draw->setFontSize(extraTitleFontSize($imgWidth));
        $draw->setFillColor(new ImagickPixel('#450145'));
        // $metrics = $img->queryFontMetrics($draw, $extraInfo['title']);
        $draw->annotation($imgWidth * 0.03, $imgHeight - $imgHeight * 0.037, mb_strtoupper($extraInfo['promotion_text']));
        $img->drawImage($draw);
    }

    if ($extraInfo['gift_price']) {
        $draw = new ImagickDraw();
        $draw->setFont(PUBLIC_PATH . '/fonts/montserrat/Montserrat-Bold.otf');
        $draw->setTextAlignment(Imagick::ALIGN_CENTER);
        $draw->setFontSize(extraPriceFontSize($imgWidth));
        $draw->setFillColor(new ImagickPixel('white'));
        $draw->annotation($imgWidth * 0.86, $imgHeight * 0.712, $extraInfo['gift_price']);
        $img->drawImage($draw);
    }

    if ($extraInfo['real_price']) {

        // draw the main price first
        $drawMainPrice = new ImagickDraw();
        $drawMainPrice->setFont(PUBLIC_PATH . '/fonts/montserrat/Montserrat-Bold.otf');
        $drawMainPrice->setTextAlignment(Imagick::ALIGN_CENTER);
        $drawMainPrice->setFontSize(extraMainPriceFontSize($imgWidth));
        $drawMainPrice->setFillColor(new ImagickPixel('white'));
        $drawMainPrice->annotation($imgWidth * 0.5, $imgHeight * 0.125, $extraInfo['real_price']);

        // get the metrics after draw the main price
        $metrics = $img->queryFontMetrics($drawMainPrice, $extraInfo['real_price']);

        // calculate the background of main price
        $textWidth = $metrics['textWidth'];
        $textHeight = $metrics['textHeight'];
        $x1 = $imgWidth / 2 - $textWidth / 2 - 10;
        $y1 = $imgHeight * 0.05;
        $x2 = $imgWidth / 2 + $textWidth / 2 + 10;
        $y2 = $imgHeight * 0.05 + $textHeight;
        $draw = new ImagickDraw();
        $draw->setFillColor(new ImagickPixel('#cc0102'));
        $draw->roundrectangle($x1, $y1, $x2, $y2, 5, 5);
        $img->drawImage($draw);
        $img->drawImage($drawMainPrice);
    }

    return $img;
}

function extraTitleFontSize($imgWidth) {
    if ($imgWidth < 200) {
        return 3;
    } else if ($imgWidth < 300) {
        return 7;
    } else if ($imgWidth < 400) {
        return 11;
    } else if ($imgWidth < 500) {
        return 13;
    } else if ($imgWidth < 600) {
        return 16;
    } else if ($imgWidth < 700) {
        return 20;
    } else if ($imgWidth < 800) {
        return 22;
    } else if ($imgWidth < 900) {
        return 26;
    } else if ($imgWidth < 1000) {
        return 30;
    }
}

function extraPriceFontSize($imgWidth) {
    if ($imgWidth < 200) {
        return 3;
    } else if ($imgWidth < 300) {
        return 7;
    } else if ($imgWidth < 400) {
        return 12;
    } else if ($imgWidth < 500) {
        return 16;
    } else if ($imgWidth < 600) {
        return 20;
    } else if ($imgWidth < 700) {
        return 24;
    } else if ($imgWidth < 800) {
        return 28;
    } else if ($imgWidth < 900) {
        return 32;
    } else if ($imgWidth < 1000) {
        return 36;
    }
}

function extraMainPriceFontSize($imgWidth) {
    if ($imgWidth < 200) {
        return 10;
    } else if ($imgWidth < 300) {
        return 18;
    } else if ($imgWidth < 400) {
        return 24;
    } else if ($imgWidth < 500) {
        return 30;
    } else if ($imgWidth < 600) {
        return 40;
    } else if ($imgWidth < 700) {
        return 46;
    } else if ($imgWidth < 800) {
        return 54;
    } else if ($imgWidth < 900) {
        return 62;
    } else if ($imgWidth < 1000) {
        return 70;
    }
}

// -------------------------------------------- //

function image($fileName, $includeHost = false) {
    global $appConfig;
    $blob = @file_get_contents($includeHost ? $fileName : ($appConfig['src_host'] . $fileName));
    if ($blob) {
        $img = new Imagick();
        if ($img->readImageBlob($blob)) {
            return $img;
        }
    }
    throw new Exception('Image is not exist');
}

function draw($img, $imgGift, $size, $template, $extraInfo) {
    global $appConfig;
    if ($size) {
        list($width, $height) = explode('x', $size);
        $img = resizeImage($img, $width, $height);
    } else {
        $width = $appConfig['def_width'];
        $height = $appConfig['def_height'];
    }
    if ($img && $imgGift) {
        $backgroundImg = new Imagick();
        $backgroundImg->newImage($width, $height, new ImagickPixel('white'), str_replace('image/', '', $img->getImageMimeType()));
        $leftImg = leftImg($width, $height);
        $rightImg = rightImg($width, $height);

        $leftImg = drawImg($leftImg, $img);
        $rightImg = drawGift($rightImg, $imgGift);
        $rightImg = giftTextTang($rightImg);
        // $rightImg = giftPrice($rightImg, $extraInfo['gift_price']);
        $rightImg = giftText($rightImg, $extraInfo['gift_text']);

        if ($template == 'template2.png') {
            $backgroundImg->compositeImage($leftImg, Imagick::COMPOSITE_OVER, 0, $height * 0.15);
            $backgroundImg->compositeImage($rightImg, Imagick::COMPOSITE_OVER, $width * 0.6, $height * 0.15);
        } else {
            $backgroundImg->compositeImage($leftImg, Imagick::COMPOSITE_OVER, 0, $height * 0.08);
            $backgroundImg->compositeImage($rightImg, Imagick::COMPOSITE_OVER, $width * 0.6, $height * 0.08);
        }

        if ($template) {
            $backgroundImg = applyTemplate($backgroundImg, $template, $extraInfo);
        }
        // $backgroundImg = mainPrice($backgroundImg, $extraInfo);
        $backgroundImg = promotionText($backgroundImg, $extraInfo);
        if ($template == '800x800-add.png') { 
            if ($extraInfo) {
                $backgroundImg = mainPriceTemplate800x800_add($backgroundImg, $extraInfo, true);
            }
        }
        return $backgroundImg;
    } else {
        if ($template == '800x800-add.png') { // chi xu ly cho template 800x800-add
            $backgroundImg = new Imagick();
            $backgroundImg->newImage($width, $height, new ImagickPixel('white'), str_replace('image/', '', $img->getImageMimeType()));
            // $img->resizeImage($width * 0.88, $height * 0.88, Imagick::FILTER_UNDEFINED, 1);
            // $img->unsharpMaskImage(0, 0.5 , 1 , 0.05);
            // $backgroundImg->compositeImage($img, Imagick::COMPOSITE_OVER, $width * 0.06, $height * -0.08);
            $backgroundImg->compositeImage($img, Imagick::COMPOSITE_OVER, $width * 0.01, $height * 0.05);
            if ($template) {
                $backgroundImg = applyTemplate($backgroundImg, $template, $extraInfo, 7);
            } elseif ($extraInfo) {
                $backgroundImg = applyExtraGift($backgroundImg, $extraInfo);
            }
            if ($extraInfo) {
                $backgroundImg = mainPriceTemplate800x800_add($backgroundImg, $extraInfo, true);
            }
        } else {
            $backgroundImg = new Imagick();
            $backgroundImg->newImage($width, $height, new ImagickPixel('white'), str_replace('image/', '', $img->getImageMimeType()));
            $img->resizeImage($width * 0.88, $height * 0.88, Imagick::FILTER_UNDEFINED, 1);
            $img->unsharpMaskImage(0 , 0.5 , 1 , 0.05);
            $backgroundImg->compositeImage($img, Imagick::COMPOSITE_OVER, $width * 0.06, $height * 0.06);
            if ($template) {
                $backgroundImg = applyTemplate($backgroundImg, $template, $extraInfo);
            } elseif ($extraInfo) {
                $backgroundImg = applyExtraGift($backgroundImg, $extraInfo);
            }
            if ($extraInfo) {
                // $backgroundImg = mainPrice($backgroundImg, $extraInfo);
                // $backgroundImg = promotionText($backgroundImg, $extraInfo);
            }
        }
        return $backgroundImg;
    }
}

function leftImg($width, $height) {
    $width = $width * 0.7;
    $height = $height * 0.75;
    $img = new Imagick();
    $img->newImage($width, $height, new ImagickPixel('white'), 'jpeg');
    return $img;
}

function rightImg($width, $height) {
    $width = $width * 0.4;
    $height = $height * 0.7;
    $img = new Imagick();
    $img->newImage($width, $height, new ImagickPixel('white'), 'jpeg');
    return $img;
}

function drawImg($leftImg, $img) {
    $width = $leftImg->getImageWidth();
    $height = $leftImg->getImageHeight();
    $imgHeight = $height;
    $imgWidth = $img->getImageHeight() / $img->getImageWidth() * $imgHeight;
    $img->resizeImage($imgWidth, $imgHeight, Imagick::FILTER_UNDEFINED, 1);
    $img->unsharpMaskImage(0 , 0.5 , 1 , 0.05);
    $leftImg->compositeImage($img, Imagick::COMPOSITE_OVER, $imgWidth * -0.15, 0);
    return $leftImg;
}

function drawGift($rightImg, $imgGift) {
    $width = $rightImg->getImageWidth();
    $height = $rightImg->getImageHeight();
    $imgGiftHeight = $height * 0.5;
    $imgGiftWidth = $imgGift->getImageWidth() / $imgGift->getImageHeight() * $imgGiftHeight;
    $imgGift->resizeImage($imgGiftWidth, $imgGiftHeight, Imagick::FILTER_UNDEFINED, 1);
    $imgGift->unsharpMaskImage(0 , 0.5 , 1 , 0.05);
    $rightImg->compositeImage($imgGift, Imagick::COMPOSITE_OVER, 0, $height * 0.25);
    return $rightImg;
}

function giftTextTang($rightImg) {

    $width = $rightImg->getImageWidth();
    $height = $rightImg->getImageHeight();

    if ($width >= 300) {
        $size = 35;
    } else if ($width >= 250) {
        $size = 25;
    } else if ($width >= 200) {
        $size = 20;
    } else if ($width >= 150) {
        $size = 15;
    } else if ($width >= 100) {
        $size = 10;
    }

    // draw the main price first
    $drawTang = new ImagickDraw();
    $drawTang->setFont(PUBLIC_PATH . '/fonts/montserrat/Montserrat-ExtraBold.otf');
    $drawTang->setTextAlignment(Imagick::ALIGN_CENTER);
    $drawTang->setFontSize($size);
    $drawTang->setFillColor(new ImagickPixel('white'));
    $drawTang->annotation($width * 0.65, $height * 0.27, 'TẶNG');

    // get the metrics after draw the main price
    $metrics = $rightImg->queryFontMetrics($drawTang, 'TẶNG');

    $textWidth = $metrics['textWidth'];
    $textHeight = $metrics['textHeight'];
    $len = $textWidth > $textHeight ? $textWidth : $textHeight;
    $x1 = $width * 0.65 - $textWidth / 2 - 5;
    $y1 = $height * 0.27 - $len / 2 - $textHeight / 4 - 5;
    $x2 = $x1 + $len + 10;
    $y2 = $y1 + $len + 10;
    $draw = new ImagickDraw();
    $draw->setFillColor(new ImagickPixel('#cc0102'));
    $draw->roundrectangle($x1, $y1, $x2, $y2, $len, $len);
    $rightImg->drawImage($draw);
    $rightImg->drawImage($drawTang);
    return $rightImg;
}

function giftPrice($rightImg, $price = NULL) {
    $width = $rightImg->getImageWidth();
    $height = $rightImg->getImageHeight();

    $sizeText = 25;
    $sizePrice = 40;
    if ($width >= 300) {
        $sizeText = 25;
        $sizePrice = 40;
    } else if ($width >= 250) {
        $sizeText = 22;
        $sizePrice = 35;
    } else if ($width >= 200) {
        $sizeText = 15;
        $sizePrice = 25;
    } else if ($width >= 150) {
        $sizeText = 12;
        $sizePrice = 22;
    } else if ($width >= 100) {
        $sizeText = 5;
        $sizePrice = 10;
    }

    $drawPriceText = new ImagickDraw();
    $drawPriceText->setFont(PUBLIC_PATH . '/fonts/montserrat/Montserrat-SemiBold.otf');
    $drawPriceText->setTextAlignment(Imagick::ALIGN_RIGHT);
    $drawPriceText->setFontSize($sizeText);
    $drawPriceText->setFillColor(new ImagickPixel('white'));
    $drawPriceText->annotation($width * 0.5, $height * 0.8, 'Trị giá ');

    // draw the main price first
    $drawPrice = new ImagickDraw();
    $drawPrice->setFont(PUBLIC_PATH . '/fonts/montserrat/Montserrat-ExtraBold.otf');
    $drawPrice->setTextAlignment(Imagick::ALIGN_LEFT);
    $drawPrice->setFontSize($sizePrice);
    $drawPrice->setFillColor(new ImagickPixel('white'));
    $drawPrice->annotation($width * 0.5, $height * 0.8, $price);

    // get the metrics after draw the main price
    $metricsPriceText = $rightImg->queryFontMetrics($drawPriceText, 'Trị giá ');
    $metricsPrice = $rightImg->queryFontMetrics($drawPrice, $price);

    $textWidthPriceText = $metricsPriceText['textWidth'];
    $textWidthPrice = $metricsPrice['textWidth'];
    $textHeightPrice = $metricsPrice['textHeight'];
    $x1 = $width / 2 - ($textWidthPriceText + $textWidthPrice) / 2 - $sizePrice * 0.4;
    $y1 = $height * 0.8 - $textHeightPrice / 4 - $textHeightPrice / 2 - $sizePrice * 0.1;
    $x2 = $x1 + ($textWidthPriceText + $textWidthPrice) + $sizePrice * 0.8;
    $y2 = $y1 + $textHeightPrice + $sizePrice * 0.2;
    $draw = new ImagickDraw();
    $draw->setFillColor(new ImagickPixel('#cc0102'));
    $draw->roundrectangle($x1, $y1, $x2, $y2, 5, 5);
    $rightImg->drawImage($draw);
    $rightImg->drawImage($drawPriceText);
    $rightImg->drawImage($drawPrice);
    return $rightImg;
}

function giftText($rightImg, $giftText) {
    if (!$giftText) {
        return $rightImg;
    }
    $width = $rightImg->getImageWidth();
    $height = $rightImg->getImageHeight();

    $size = 18;
    if ($width >= 300) {
        $size = 18;
    } else if ($width >= 250) {
        $size = 16;
    } else if ($width >= 200) {
        $size = 14;
    } else if ($width >= 150) {
        $size = 10;
    } else if ($width >= 100) {
        $size = 8;
    }

    $draw = new ImagickDraw();
    $draw->setFont(PUBLIC_PATH . '/fonts/montserrat/Montserrat-SemiBold.otf');
    $draw->setTextAlignment(Imagick::ALIGN_CENTER);
    $draw->setFontSize($size);
    $draw->setFillColor(new ImagickPixel('#2a2a31'));

    $metrics = $rightImg->queryFontMetrics($draw, $giftText);
    $textHeight = 0;
    $textWidth = $metrics['textWidth'];
    if ($textWidth < $width * 0.9) {
        $draw->annotation($rightImg->getImageWidth() * 0.5, $rightImg->getImageHeight() * 0.87, $giftText);
        $textHeight += $metrics['textHeight'];
    } else {
        $line = [];
        $index = 0;
        $splits = explode(' ', $giftText);
        while($index < count($splits)) {
            $line[] = $splits[$index];
            $metrics = $rightImg->queryFontMetrics($draw, implode(' ', $line));
            if ($metrics['textWidth'] > $width * 0.9) {
                array_pop($line);
                $draw->annotation($rightImg->getImageWidth() * 0.5, $rightImg->getImageHeight() * 0.87 + $textHeight, implode(' ', $line));
                $textHeight += $metrics['textHeight'];
                $line = [];
                continue;
            } else if ($index == count($splits) - 1) {
                $draw->annotation($rightImg->getImageWidth() * 0.5, $rightImg->getImageHeight() * 0.87 + $textHeight, implode(' ', $line));
            }
            $index++;
        }
        $metrics = $rightImg->queryFontMetrics($draw, implode(' ', $line));
        $textHeight += $metrics['textHeight'];
    }

    $rightImg->drawImage($draw);

    $drawLimitText = new ImagickDraw();
    $drawLimitText->setFont(PUBLIC_PATH . '/fonts/montserrat/Montserrat-SemiBold.otf');
    $drawLimitText->setTextAlignment(Imagick::ALIGN_CENTER);
    $drawLimitText->setFontSize($size);
    $drawLimitText->setFillColor(new ImagickPixel('#f3ab73'));
    $drawLimitText->annotation($rightImg->getImageWidth() * 0.5, $rightImg->getImageHeight() * 0.87 + $textHeight, 'Số lượng có hạn');
    $rightImg->drawImage($drawLimitText);

    $metrics = $rightImg->queryFontMetrics($drawLimitText, 'Số lượng có hạn');
    $drawLimitText->annotation($rightImg->getImageWidth() * 0.5, $rightImg->getImageHeight() * 0.87 + $textHeight + $metrics['textHeight'], 'Nhớ kiểm tra quà trong giỏ hàng');
    $rightImg->drawImage($drawLimitText);
    return $rightImg;
}

function mainPrice($img, $extraInfo) {
    if ($extraInfo['real_price']) {

        $width = $img->getImageWidth();
        $height = $img->getImageHeight();

        $size = 70;
        if ($width >= 800) {
            $size = 60;
        } else if ($width >= 700) {
            $size = 50;
        } else if ($width >= 600) {
            $size = 45;
        } else if ($width >= 500) {
            $size = 40;
        } else if ($width >= 400) {
            $size = 30;
        }

        // draw the main price first
        $drawMainPrice = new ImagickDraw();
        $drawMainPrice->setFont(PUBLIC_PATH . '/fonts/montserrat/Montserrat-ExtraBold.otf');
        $drawMainPrice->setTextAlignment(Imagick::ALIGN_CENTER);
        $drawMainPrice->setFontSize($size);
        $drawMainPrice->setFillColor(new ImagickPixel('white'));
        $drawMainPrice->annotation($width * 0.5, $height * 0.18, $extraInfo['real_price']);

        // get the metrics after draw the main price
        $metrics = $img->queryFontMetrics($drawMainPrice, $extraInfo['real_price']);

        // calculate the background of main price
        $textWidth = $metrics['textWidth'];
        $textHeight = $metrics['textHeight'];
        $x1 = $width / 2 - $textWidth / 2 - 25;
        $y1 = $height * 0.18 - $textHeight / 2 - $textHeight / 4;
        $x2 = $x1 + $textWidth + 50;
        $y2 = $y1 + $textHeight;
        $draw = new ImagickDraw();
        $draw->setFillColor(new ImagickPixel('#cc0102'));
        $draw->roundrectangle($x1, $y1, $x2, $y2, 5, 5);
        $img->drawImage($draw);
        $img->drawImage($drawMainPrice);
    }

    if ($extraInfo['market_price']) {

        $width = $img->getImageWidth();
        $height = $img->getImageHeight();

        $sizeText = 15;
        $sizePrice = 32;
        $padding = 5;
        $top = 10;
        if ($width >= 800) {
            $sizeText = 15;
            $sizePrice = 32;
            $padding = 5;
            $top = 10;
        } else if ($width >= 700) {
            $sizeText = 14;
            $sizePrice = 30;
            $padding = 4;
            $top = 8;
        } else if ($width >= 600) {
            $sizeText = 12;
            $sizePrice = 25;
            $padding = 3;
            $top = 6;
        } else if ($width >= 500) {
            $sizeText = 11;
            $sizePrice = 22;
            $padding = 2;
            $top = 4;
        } else if ($width >= 400) {
            $sizeText = 9;
            $sizePrice = 18;
            $padding = 1;
            $top = 2;
        }

        $drawMarketText = new ImagickDraw();
        $drawMarketText->setFont(PUBLIC_PATH . '/fonts/montserrat/Montserrat-SemiBold.otf');
        $drawMarketText->setTextAlignment(Imagick::ALIGN_RIGHT);
        $drawMarketText->setFontSize($sizeText);
        $drawMarketText->setFillColor(new ImagickPixel('#5a5a5a'));
        $drawMarketText->annotation($width * 0.5 - $padding, $y1 - $top, 'GIÁ TRỊ THỰC');
        $img->drawImage($drawMarketText);

        // draw the main price first
        $drawMarketPrice = new ImagickDraw();
        $drawMarketPrice->setFont(PUBLIC_PATH . '/fonts/montserrat/Montserrat-ExtraBold.otf');
        $drawMarketPrice->setTextAlignment(Imagick::ALIGN_LEFT);
        $drawMarketPrice->setFontSize($sizePrice);
        $drawMarketPrice->setFillColor(new ImagickPixel('#303030'));
        $drawMarketPrice->annotation($width * 0.5 + $padding, $y1 - $top, $extraInfo['market_price']);
        $img->drawImage($drawMarketPrice);
    }

    return $img;
}

function mainPriceTemplate800x800_add($img, $extraInfo, $gift) {
    $width = $img->getImageWidth();
    $height = $img->getImageHeight();

    $sizeName = 32; $size = 48;
    if ($width >= 800) {
        $sizeName = 26;
        $size = 50;
    } else if ($width >= 700) {
        $sizeName = 25;
        $size = 40;
    } else if ($width >= 600) {
        $sizeName = 18;
        $size = 34;
    } else if ($width >= 500) {
        $sizeName = 14;
        $size = 25;
    } else if ($width >= 400) {
        $sizeName = 8;
        $size = 15;
    }

    $name = $extraInfo['name'];
    $drawName = new ImagickDraw();
    $drawName->setFont(PUBLIC_PATH . '/fonts/montserrat/Montserrat-Regular.otf');
    $drawName->setTextAlignment(Imagick::ALIGN_CENTER);
    $drawName->setFontSize($sizeName);
    $drawName->setFillColor(new ImagickPixel('#333333'));
    $metrics = $img->queryFontMetrics($drawName, $name);
    $textHeight = 0;
    $textWidth = $metrics['textWidth'];
    $y = 0.76;
    if ($textWidth < $width * $y) {
        $textHeight += $metrics['textHeight'];
        $drawName->annotation($img->getImageWidth() * 0.5, $img->getImageHeight() * $y + $textHeight, $name);
        $textHeight *= 2;
    } else {
        $line = [];
        $index = 0;
        $splits = explode(' ', $name);
        while($index < count($splits)) {
            $line[] = $splits[$index];
            $metrics = $img->queryFontMetrics($drawName, implode(' ', $line));
            if ($metrics['textWidth'] > $width * $y) {
                array_pop($line);
                $drawName->annotation($width * 0.5, $img->getImageHeight() * $y + $textHeight, implode(' ', $line));
                $textHeight += $metrics['textHeight'];
                $line = [];
                continue;
            } else if ($index == count($splits) - 1) {
                $drawName->annotation($width * 0.5, $img->getImageHeight() * $y + $textHeight, implode(' ', $line));
            }
            $index++;
        }
        $metrics = $img->queryFontMetrics($drawName, implode(' ', $line));
        $textHeight += $metrics['textHeight'];
    }
    if($gift == false) $img->drawImage($drawName);
    if ($extraInfo['real_price']) {

        // draw the main price first
        $drawMainPrice = new ImagickDraw();
        $drawMainPrice->setFont(PUBLIC_PATH . '/fonts/montserrat/Montserrat-SemiBold.otf');
        $drawMainPrice->setTextAlignment(Imagick::ALIGN_RIGHT);
        $drawMainPrice->setFontSize($size);
        $drawMainPrice->setStrokeWidth(2);
        $drawMainPrice->setFontWeight(800);
        $drawMainPrice->setFillColor(new ImagickPixel('#ffffff'));
        $drawMainPrice->annotation($width * 0.785, $height * 0.88 + $textHeight + 10, mb_strtolower($extraInfo['real_price']));
        $img->drawImage($drawMainPrice);
        if ($extraInfo['market_price']) {

            // draw the main price first
            $marketPrice = mb_strtolower($extraInfo['market_price']);
            $drawMarketPrice = new ImagickDraw();
            $drawMarketPrice->setFont(PUBLIC_PATH . '/fonts/montserrat/Montserrat-SemiBold.otf');
            $drawMarketPrice->setTextAlignment(Imagick::ALIGN_LEFT);
            $drawMarketPrice->setFontSize($sizeName);
            $drawMarketPrice->setFillColor(new ImagickPixel('#ffffff'));
            $drawMarketPrice->annotation($width * 0.575, $height * 0.820 + $textHeight + 10, $marketPrice);
            $metrics = $img->queryFontMetrics($drawMarketPrice, $marketPrice);
            $img->drawImage($drawMarketPrice);
            // $drawMarketPrice->setStrokeAntialias(true);
            // $drawMarketPrice->setTextAntialias(true);
            // $drawMarketPrice->setStrokeWidth(2);
            // $drawMarketPrice->setFontSize(100);
            $drawMarketPrice1 = new ImagickDraw();
            $drawMarketPrice1->setFont(PUBLIC_PATH . '/fonts/montserrat/Montserrat-SemiBold.otf');
            $drawMarketPrice1->setFillColor(new ImagickPixel('#cccccc'));
            $drawMarketPrice1->setFontSize(200);
            $drawMarketPrice1->line($width * 0.575, $height * 0.825 + $textHeight + 10 - $metrics['characterHeight'] / 2, $width * 0.575 + $metrics['textWidth'], $height * 0.825 + $textHeight + 10 - $metrics['characterHeight'] / 2);
            $img->drawImage($drawMarketPrice1);
        }
    }

    return $img;
}

function promotionText($img, $extraInfo) {
    if ($extraInfo['promotion_text']) {
        $width = $img->getImageWidth();
        $height = $img->getImageHeight();

        $size = 18;
        if ($width >= 800) {
            $size = 18;
        } else if ($width >= 700) {
            $size = 16;
        } else if ($width >= 600) {
            $size = 14;
        } else if ($width >= 500) {
            $size = 12;
        } else if ($width >= 400) {
            $size = 10;
        }

        $draw = new ImagickDraw();
        $draw->setFont(PUBLIC_PATH . '/fonts/montserrat/Montserrat-SemiBold.otf');
        $draw->setTextAlignment(Imagick::ALIGN_CENTER);
        $draw->setFontSize($size);
        $draw->setFillColor(new ImagickPixel('black'));
        $draw->annotation($width * 0.5, $height * 0.95, $extraInfo['promotion_text']);

        $img->drawImage($draw);
    }
    return $img;
}

function dd($var = '') {
    print_r('<pre>');
    print_r($var);
    print_r('</pre>');
    die;
}
