<?php
class ModelToolImage extends Model {

    public function upload($img_url,$prefix,$username)
    {

        $user_path='';//$username;
        // $image_name =  $this->entegrasyon->getImage($img_url, $product_title.'_'.$product['productMainId'] . '_' . $key,$this->user->getUserName().'/');

        $image_url = str_replace(" ", "%20", $img_url);
        $image_name = explode("/", $image_url);
        $image_name = $image_name[count($image_name) - 1];

        $local_upload_file_path=$image_url;
        $storage_zone_path=BUNNY_STORAGE.$user_path;
        $storage_zone_file_path=$prefix.$image_name;
        $res=$this->image->Storage()->PutFile($local_upload_file_path, $storage_zone_path, $storage_zone_file_path);

        return $user_path.$res['cdn_file_path'];

    }

    public function resize($filename, $width, $height) {
		if (!is_file(DIR_IMAGE . $filename) || substr(str_replace('\\', '/', realpath(DIR_IMAGE . $filename)), 0, strlen(DIR_IMAGE)) != str_replace('\\', '/', DIR_IMAGE)) {
			return;
		}

		$extension = pathinfo($filename, PATHINFO_EXTENSION);

		$image_old = $filename;
		$image_new = 'cache/' . utf8_substr($filename, 0, utf8_strrpos($filename, '.')) . '-' . (int)$width . 'x' . (int)$height . '.' . $extension;

		if (!is_file(DIR_IMAGE . $image_new) || (filemtime(DIR_IMAGE . $image_old) > filemtime(DIR_IMAGE . $image_new))) {
			list($width_orig, $height_orig, $image_type) = getimagesize(DIR_IMAGE . $image_old);

			if (!in_array($image_type, array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF))) {
				return DIR_IMAGE . $image_old;
			}

			$path = '';

			$directories = explode('/', dirname($image_new));

			foreach ($directories as $directory) {
				$path = $path . '/' . $directory;

				if (!is_dir(DIR_IMAGE . $path)) {
					@mkdir(DIR_IMAGE . $path, 0777);
				}
			}

			if ($width_orig != $width || $height_orig != $height) {
				$image = new Image(DIR_IMAGE . $image_old);
				$image->resize($width, $height);
				$image->save(DIR_IMAGE . $image_new);
			} else {
				copy(DIR_IMAGE . $image_old, DIR_IMAGE . $image_new);
			}
		}

		$image_new = str_replace(' ', '%20', $image_new);  // fix bug when attach image on email (gmail.com). it is automatic changing space " " to +

		if ($this->request->server['HTTPS']) {
			return $this->config->get('config_ssl') . 'image/' . $image_new;
		} else {
			return $this->config->get('config_url') . 'image/' . $image_new;
		}
	}



    public function getImage($image_url, $name)
    {
        $image_folder = 'catalog/easyentegre/';

        if (!file_exists(DIR_IMAGE . $image_folder)) {

            mkdir(DIR_IMAGE . $image_folder, 0777, true);

        }

        $image_url = str_replace(" ", "%20", $image_url);
        $image_name = explode("/", $image_url);
        $image_name = $image_name[count($image_name) - 1];
        $path_parts = pathinfo($image_name);
        $extension = $path_parts['extension'];

        $image_name = $this->createSEOKeyword($name) . '.' . $extension;




        $image_file = DIR_IMAGE . $image_folder . $image_name;


        //if (!file_exists($image_file)) {

        /*   $ch = curl_init();
           curl_setopt($ch, CURLOPT_URL, $image_url);
           curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
           curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

           curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
           $image_content = curl_exec($ch);*/

        $image_content = file_get_contents($image_url);



        file_put_contents($image_file, $image_content);

        // }

        return $image_folder . $image_name;
    }


    public function createSEOKeyword($title, $options = array('transliterate'))
    {
        // Make sure string is in UTF-8 and strip invalid UTF-8 characters
        $title = mb_convert_encoding((string)$title, 'UTF-8', mb_list_encodings());
        $defaults = array(
            'delimiter' => '-',
            'limit' => null,
            'lowercase' => true,
            'replacements' => array(),
            'transliterate' => true,
        );
        // Merge options
        $options = array_merge($defaults, $options);
        $char_map = array(
            // Latin
            'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Æ' => 'AE', 'Ç' => 'C',
            'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I',
            'Ð' => 'D', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ő' => 'O',
            'Ø' => 'O', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ű' => 'U', 'Ý' => 'Y', 'Þ' => 'TH',
            'ß' => 'ss',
            'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'ae', 'ç' => 'c',
            'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i',
            'ð' => 'd', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ő' => 'o',
            'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ü' => 'u', 'ű' => 'u', 'ý' => 'y', 'þ' => 'th',
            'ÿ' => 'y', 'ž' => 'z',
            // Latin symbols
            '©' => '(c)',
            // Greek
            'Α' => 'A', 'Β' => 'B', 'Γ' => 'G', 'Δ' => 'D', 'Ε' => 'E', 'Ζ' => 'Z', 'Η' => 'H', 'Θ' => '8',
            'Ι' => 'I', 'Κ' => 'K', 'Λ' => 'L', 'Μ' => 'M', 'Ν' => 'N', 'Ξ' => '3', 'Ο' => 'O', 'Π' => 'P',
            'Ρ' => 'R', 'Σ' => 'S', 'Τ' => 'T', 'Υ' => 'Y', 'Φ' => 'F', 'Χ' => 'X', 'Ψ' => 'PS', 'Ω' => 'W',
            'Ά' => 'A', 'Έ' => 'E', 'Ί' => 'I', 'Ό' => 'O', 'Ύ' => 'Y', 'Ή' => 'H', 'Ώ' => 'W', 'Ϊ' => 'I',
            'Ϋ' => 'Y',
            'α' => 'a', 'β' => 'b', 'γ' => 'g', 'δ' => 'd', 'ε' => 'e', 'ζ' => 'z', 'η' => 'h', 'θ' => '8',
            'ι' => 'i', 'κ' => 'k', 'λ' => 'l', 'μ' => 'm', 'ν' => 'n', 'ξ' => '3', 'ο' => 'o', 'π' => 'p',
            'ρ' => 'r', 'σ' => 's', 'τ' => 't', 'υ' => 'y', 'φ' => 'f', 'χ' => 'x', 'ψ' => 'ps', 'ω' => 'w',
            'ά' => 'a', 'έ' => 'e', 'ί' => 'i', 'ό' => 'o', 'ύ' => 'y', 'ή' => 'h', 'ώ' => 'w', 'ς' => 's',
            'ϊ' => 'i', 'ΰ' => 'y', 'ϋ' => 'y', 'ΐ' => 'i',
            // Turkish
            'Ş' => 'S', 'İ' => 'I', 'Ç' => 'C', 'Ü' => 'U', 'Ö' => 'O', 'Ğ' => 'G',
            'ş' => 's', 'ı' => 'i', 'ç' => 'c', 'ü' => 'u', 'ö' => 'o', 'ğ' => 'g',
            // Russian
            'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D', 'Е' => 'E', 'Ё' => 'Yo', 'Ж' => 'Zh',
            'З' => 'Z', 'И' => 'I', 'Й' => 'J', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'О' => 'O',
            'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C',
            'Ч' => 'Ch', 'Ш' => 'Sh', 'Щ' => 'Sh', 'Ъ' => '', 'Ы' => 'Y', 'Ь' => '', 'Э' => 'E', 'Ю' => 'Yu',
            'Я' => 'Ya',
            'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'yo', 'ж' => 'zh',
            'з' => 'z', 'и' => 'i', 'й' => 'j', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o',
            'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c',
            'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sh', 'ъ' => '', 'ы' => 'y', 'ь' => '', 'э' => 'e', 'ю' => 'yu',
            'я' => 'ya',
            // Ukrainian
            'Є' => 'Ye', 'І' => 'I', 'Ї' => 'Yi', 'Ґ' => 'G',
            'є' => 'ye', 'і' => 'i', 'ї' => 'yi', 'ґ' => 'g',
            // Czech
            'Č' => 'C', 'Ď' => 'D', 'Ě' => 'E', 'Ň' => 'N', 'Ř' => 'R', 'Š' => 'S', 'Ť' => 'T', 'Ů' => 'U',
            'Ž' => 'Z',
            'č' => 'c', 'ď' => 'd', 'ě' => 'e', 'ň' => 'n', 'ř' => 'r', 'š' => 's', 'ť' => 't', 'ů' => 'u',
            'ž' => 'z',
            // Polish
            'Ą' => 'A', 'Ć' => 'C', 'Ę' => 'e', 'Ł' => 'L', 'Ń' => 'N', 'Ó' => 'o', 'Ś' => 'S', 'Ź' => 'Z',
            'Ż' => 'Z',
            'ą' => 'a', 'ć' => 'c', 'ę' => 'e', 'ł' => 'l', 'ń' => 'n', 'ó' => 'o', 'ś' => 's', 'ź' => 'z',
            'ż' => 'z',
            // Latvian
            'Ā' => 'A', 'Č' => 'C', 'Ē' => 'E', 'Ģ' => 'G', 'Ī' => 'i', 'Ķ' => 'k', 'Ļ' => 'L', 'Ņ' => 'N',
            'Š' => 'S', 'Ū' => 'u', 'Ž' => 'Z',
            'ā' => 'a', 'č' => 'c', 'ē' => 'e', 'ģ' => 'g', 'ī' => 'i', 'ķ' => 'k', 'ļ' => 'l', 'ņ' => 'n',
            'š' => 's', 'ū' => 'u', 'ž' => 'z',
            //special
            'Ľ' => 'L', 'ľ' => 'l',
        );
        // Make custom replacements
        $title = preg_replace(array_keys($options['replacements']), $options['replacements'], $title);
        // Transliterate characters to ASCII
        if ($options['transliterate']) {
            $title = str_replace(array_keys($char_map), $char_map, $title);
        }
        // Replace non-alphanumeric characters with our delimiter
        $title = preg_replace('/[^\p{L}\p{Nd}]+/u', $options['delimiter'], $title);
        // Remove duplicate delimiters
        $title = preg_replace('/(' . preg_quote($options['delimiter'], '/') . '){2,}/', '$1', $title);
        // Truncate slug to max. characters
        $title = mb_substr($title, 0, ($options['limit'] ? $options['limit'] : mb_strlen($title, 'UTF-8')), 'UTF-8');
        // Remove delimiter from ends
        $title = trim($title, $options['delimiter']);
        return $options['lowercase'] ? mb_strtolower($title, 'UTF-8') : $title;
    }


    public function uploadBunnyFromUrl($image_url, $file_name = '')
    {
        // ==========================
        //  Bunny.net AYARLARI
        // ==========================
        $storageZoneName = BUNNY_STORAGE;      // Storage Zone Name (ör: 'firat')
        $accessKey       = BUNNY_STORAGE_KEY;  // Storage API/FTP Password
        $region          = '';                 // Varsayılan Frankfurt için boş bırak. Örn: 'ny', 'la', 'sg', 'uk'

        // CDN/Pull Zone alan adın (ör: https://multima.b-cdn.net)
        $cdnBaseUrl      = BUNNY_DOMAIN;

        // ==========================
        //  TEMEL KONTROLLER
        // ==========================
        if (!$image_url || !filter_var($image_url, FILTER_VALIDATE_URL)) {
            return false; // Geçersiz URL
        }

        // GD yoksa, resize yapamayız, ama yine de upload edebiliriz
        $gdAvailable = function_exists('imagecreatefromstring') && function_exists('imagecreatetruecolor');

        // ==========================
        // 1) UZAK GÖRSELİ İNDİR
        // ==========================
        $ch = curl_init($image_url);
        curl_setopt_array($ch, array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_USERAGENT      => 'OpenCart-BunnyUploader/1.0',
            CURLOPT_TIMEOUT        => 30,
        ));

        $fileData = curl_exec($ch);
        $err      = curl_error($ch);
        $info     = curl_getinfo($ch);
        curl_close($ch);

        if ($fileData === false || (isset($info['http_code']) && $info['http_code'] >= 400)) {
            // İndirme başarısız
            // $this->log->write('Bunny download error: ' . $err . ' | URL: ' . $image_url);
            return false;
        }

        // ==========================
        // 2) GÖRSEL BOYUTU KONTROL / GEREKİRSE 1000x1000 YAP
        // ==========================
        if ($gdAvailable) {
            // MIME türünü tespit etmeye çalış
            $mime = '';
            if (!empty($info['content_type'])) {
                $mime = $info['content_type'];
            } else {
                $imgInfo = @getimagesizefromstring($fileData);
                if ($imgInfo && isset($imgInfo['mime'])) {
                    $mime = $imgInfo['mime'];
                }
            }

            $src = @imagecreatefromstring($fileData);
            if ($src !== false) {

                $origW = imagesx($src);
                $origH = imagesy($src);

                // Sadece width < 1000 veya height < 1000 ise büyüt
                if ($origW < 1000 || $origH < 1000) {
                    $targetW = 1000;
                    $targetH = 1000;

                    // Oranı koruyarak 1000x1000 içine sığdır
                    $scale = min($targetW / $origW, $targetH / $origH);
                    $newW  = (int)round($origW * $scale);
                    $newH  = (int)round($origH * $scale);

                    $dst = imagecreatetruecolor($targetW, $targetH);

                    // Arka planı beyaz doldur
                    $white = imagecolorallocate($dst, 255, 255, 255);
                    imagefill($dst, 0, 0, $white);

                    // Ortaya yerleştir
                    $dstX = (int)(($targetW - $newW) / 2);
                    $dstY = (int)(($targetH - $newH) / 2);

                    imagecopyresampled(
                        $dst, $src,
                        $dstX, $dstY,
                        0, 0,
                        $newW, $newH,
                        $origW, $origH
                    );

                    // Çıktıyı buffer'a al ve $fileData'yı güncelle
                    ob_start();
                    if ($mime === 'image/png') {
                        imagepng($dst, null);
                    } elseif ($mime === 'image/webp') {
                        if (function_exists('imagewebp')) {
                            imagewebp($dst, null, 90);
                        } else {
                            imagejpeg($dst, null, 90); // WebP yoksa JPEG fallback
                        }
                    } else {
                        // Varsayılan JPEG
                        imagejpeg($dst, null, 90);
                    }
                    $fileData = ob_get_clean();

                    imagedestroy($dst);
                }

                imagedestroy($src);
            }
        }

        // ==========================
        // 3) DOSYA ADI OLUŞTUR
        // ==========================

        // a) Önce senin gönderdiğin isim
        $basename = trim($file_name);

        // b) Eğer boş ise, URL'den isim üret
        if ($basename === '') {
            $path     = parse_url($image_url, PHP_URL_PATH);
            $basename = $path ? basename($path) : '';
        }

        // c) Hâlâ düzgün isim yoksa random isim üret
        if (!$basename || $basename === '/' || strpos($basename, '.') === false) {
            // URL'den uzantıyı almaya çalış
            $ext = '';
            if (!isset($path)) {
                $path = parse_url($image_url, PHP_URL_PATH);
            }
            if ($path) {
                $tmpBase = basename($path);
                if (strpos($tmpBase, '.') !== false) {
                    $ext = strtolower(strrchr($tmpBase, '.')); // .jpg, .png vs
                }
            }

            if ($ext === '' || strpos($ext, '.') === false) {
                $ext = '.jpg'; // default uzantı
            }

            $randomPart = substr(md5(uniqid(mt_rand(), true)), 0, 8);
            $basename   = 'img_' . date('Ymd_His') . '_' . $randomPart . $ext;
        }

        // d) Sadece dosya adı kalsın
        $basename = basename($basename);

        // e) Dosya adını sadeleştir (Türkçe/özel karakter, boşluk vs)
        $basename = preg_replace('~[^a-zA-Z0-9_\.-]~', '_', $basename);

        // f) Alt klasör yok, direkt root:
        // firat / {basename}
        $remotePath = $basename;

        // ==========================
        // 4) BUNNY UPLOAD URL
        // ==========================
        $baseHost = 'storage.bunnycdn.com';
        $host     = $region ? ($region . '.' . $baseHost) : $baseHost;

        // https://{host}/{storageZoneName}/{remotePath}
        $uploadUrl = 'https://' . $host . '/' . $storageZoneName . '/' . $remotePath;

        // ==========================
        // 5) BUNNY'YE YÜKLE (PUT)
        // ==========================
        $ch = curl_init($uploadUrl);
        curl_setopt_array($ch, array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST  => 'PUT',
            CURLOPT_HTTPHEADER     => array(
                'AccessKey: ' . $accessKey,
                'Content-Type: application/octet-stream',
                'accept: application/json'
            ),
            CURLOPT_POSTFIELDS     => $fileData,
            CURLOPT_TIMEOUT        => 60,
        ));

        $uploadResponse = curl_exec($ch);
        $uploadError    = curl_error($ch);
        $uploadInfo     = curl_getinfo($ch);
        curl_close($ch);

        $httpCode = isset($uploadInfo['http_code']) ? (int)$uploadInfo['http_code'] : 0;

        // 2xx harici her şey hata
        if ($httpCode < 200 || $httpCode >= 300) {
            // $this->log->write('Bunny upload error: ' . $uploadError . ' | Response: ' . $uploadResponse . ' | URL: ' . $uploadUrl);
            return false;
        }

        // ==========================
        // 6) DÖNECEĞİN URL
        // ==========================
        if ($cdnBaseUrl) {
            $cdnBaseUrl = rtrim($cdnBaseUrl, '/');
            $resultUrl  = $cdnBaseUrl . '/' . ltrim($remotePath, '/');
        } else {
            $resultUrl  = 'https://' . $host . '/' . $storageZoneName . '/' . $remotePath;
        }

        return $resultUrl; // Başarılıysa BUNNY'deki tam URL, başarısızsa false
    }

}
