<?php
require_once __DIR__ . '/../config/config.php';

/**
 * Process uploaded image: resize max 1200px, compress JPEG 80% / WebP, and create thumbnail
 * Uses PHP GD Library
 */
function processAndUploadImage($file, $subDir = 'products') {
    if (!isset($file['tmp_name']) || empty($file['tmp_name']) || $file['error'] !== UPLOAD_ERR_OK) {
        return ['success' => false, 'error' => 'ไม่มีไฟล์อัปโหลดหรือเกิดข้อผิดพลาด'];
    }

    $allowedMimes = ['image/jpeg', 'image/png', 'image/webp'];
    $fileMime = mime_content_type($file['tmp_name']);
    if (!in_array($fileMime, $allowedMimes)) {
        return ['success' => false, 'error' => 'อนุญาตเฉพาะไฟล์รูปภาพ (JPG, PNG, WebP) เท่านั้น'];
    }

    // Check size limit (max 10MB input)
    if ($file['size'] > 10 * 1024 * 1024) {
        return ['success' => false, 'error' => 'ขนาดไฟล์เกิน 10MB'];
    }

    $targetDir = UPLOAD_DIR . $subDir . '/';
    $thumbDir = UPLOAD_DIR . $subDir . '/thumbs/';

    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0777, true);
    }
    if (!file_exists($thumbDir)) {
        mkdir($thumbDir, 0777, true);
    }

    // Check if GD extension & required functions are available
    $hasGD = extension_loaded('gd') && function_exists('imagecreatefromjpeg') && function_exists('imagecreatetruecolor');

    if (!$hasGD) {
        // Fallback: Upload file directly via move_uploaded_file without GD processing
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (empty($ext)) {
            $ext = ($fileMime === 'image/png') ? 'png' : (($fileMime === 'image/webp') ? 'webp' : 'jpg');
        }
        $filename = uniqid('img_', true) . '.' . $ext;
        $mainPath = $targetDir . $filename;
        $thumbPath = $thumbDir . 'thumb_' . $filename;

        if (move_uploaded_file($file['tmp_name'], $mainPath)) {
            copy($mainPath, $thumbPath);
            $sizeKb = round($file['size'] / 1024, 1);
            return [
                'success' => true,
                'main_path' => $subDir . '/' . $filename,
                'thumb_path' => $subDir . '/thumbs/thumb_' . $filename,
                'orig_size_kb' => $sizeKb,
                'comp_size_kb' => $sizeKb
            ];
        } else {
            return ['success' => false, 'error' => 'ไม่สามารถย้ายไฟล์อัปโหลดไปยังโฟลเดอร์ปลายทางได้'];
        }
    }

    // Process via GD Library
    switch ($fileMime) {
        case 'image/jpeg':
            $srcImage = @imagecreatefromjpeg($file['tmp_name']);
            break;
        case 'image/png':
            $srcImage = @imagecreatefrompng($file['tmp_name']);
            break;
        case 'image/webp':
            $srcImage = function_exists('imagecreatefromwebp') ? @imagecreatefromwebp($file['tmp_name']) : false;
            break;
        default:
            $srcImage = false;
    }

    if (!$srcImage) {
        // Fallback if GD fails to parse image resource
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (empty($ext)) $ext = 'jpg';
        $filename = uniqid('img_', true) . '.' . $ext;
        $mainPath = $targetDir . $filename;
        $thumbPath = $thumbDir . 'thumb_' . $filename;

        if (move_uploaded_file($file['tmp_name'], $mainPath)) {
            copy($mainPath, $thumbPath);
            $sizeKb = round($file['size'] / 1024, 1);
            return [
                'success' => true,
                'main_path' => $subDir . '/' . $filename,
                'thumb_path' => $subDir . '/thumbs/thumb_' . $filename,
                'orig_size_kb' => $sizeKb,
                'comp_size_kb' => $sizeKb
            ];
        }
        return ['success' => false, 'error' => 'ไม่สามารถประมวลผลไฟล์รูปภาพด้วย GD Library ได้'];
    }

    $origWidth = imagesx($srcImage);
    $origHeight = imagesy($srcImage);

    // 1. Resize Main Image if width > MAX_IMAGE_WIDTH (1200px)
    if ($origWidth > MAX_IMAGE_WIDTH) {
        $newWidth = MAX_IMAGE_WIDTH;
        $newHeight = (int)($origHeight * ($newWidth / $origWidth));
    } else {
        $newWidth = $origWidth;
        $newHeight = $origHeight;
    }

    $mainResized = imagecreatetruecolor($newWidth, $newHeight);
    imagealphablending($mainResized, false);
    imagesavealpha($mainResized, true);
    imagecopyresampled($mainResized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight);

    $filename = uniqid('img_', true) . '.webp';
    $mainPath = $targetDir . $filename;

    $saveMainSuccess = false;
    if (function_exists('imagewebp')) {
        $saveMainSuccess = imagewebp($mainResized, $mainPath, JPEG_QUALITY);
    } else {
        $filename = uniqid('img_', true) . '.jpg';
        $mainPath = $targetDir . $filename;
        $saveMainSuccess = imagejpeg($mainResized, $mainPath, JPEG_QUALITY);
    }
    imagedestroy($mainResized);

    if (!$saveMainSuccess) {
        error_log("[Image Upload] Failed to save main image to path: " . $mainPath);
        return ['success' => false, 'error' => 'เซิร์ฟเวอร์ไม่สามารถบันทึกไฟล์รูปภาพหลักได้ (Check Permissions)'];
    }

    // 2. Create Thumbnail
    $thumbWidth = THUMB_WIDTH;
    $thumbHeight = (int)($origHeight * ($thumbWidth / $origWidth));
    $thumbResized = imagecreatetruecolor($thumbWidth, $thumbHeight);
    imagealphablending($thumbResized, false);
    imagesavealpha($thumbResized, true);
    imagecopyresampled($thumbResized, $srcImage, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $origWidth, $origHeight);

    $thumbFilename = 'thumb_' . $filename;
    $thumbPath = $thumbDir . $thumbFilename;

    $saveThumbSuccess = false;
    if (function_exists('imagewebp')) {
        $saveThumbSuccess = imagewebp($thumbResized, $thumbPath, JPEG_QUALITY);
    } else {
        $saveThumbSuccess = imagejpeg($thumbResized, $thumbPath, JPEG_QUALITY);
    }

    imagedestroy($thumbResized);
    imagedestroy($srcImage);

    if (!$saveThumbSuccess) {
        error_log("[Image Upload] Failed to save thumbnail image to path: " . $thumbPath);
        // We can still return success for main image, but log the error for thumbnail
    }

    $originalSizeKb = round($file['size'] / 1024, 1);
    $compressedSizeKb = file_exists($mainPath) ? round(filesize($mainPath) / 1024, 1) : $originalSizeKb;

    return [
        'success' => true,
        'main_path' => $subDir . '/' . $filename,
        'thumb_path' => $subDir . '/thumbs/' . $thumbFilename,
        'orig_size_kb' => $originalSizeKb,
        'comp_size_kb' => $compressedSizeKb
    ];
}

/**
 * Format image URL with full path and fallback image support
 * Supports checking file existence on disk, case sensitivity, relative paths, etc.
 */
function formatImageUrl($imagePath) {
    if (empty($imagePath) || !is_string($imagePath)) {
        return SITE_URL . '/assets/images/no-image.png';
    }

    $trimmed = trim($imagePath);
    if ($trimmed === '' || $trimmed === 'null' || $trimmed === 'undefined') {
        return SITE_URL . '/assets/images/no-image.png';
    }

    // External URL
    if (preg_match('/^https?:\/\//i', $trimmed)) {
        return $trimmed;
    }

    // Strip SITE_URL if already present to work with local path
    if (strpos($trimmed, SITE_URL) === 0) {
        $trimmed = substr($trimmed, strlen(SITE_URL));
    }

    $trimmed = ltrim($trimmed, '/');
    $publicDir = realpath(__DIR__ . '/../public');
    if (!$publicDir) {
        $publicDir = __DIR__ . '/../public';
    }

    // Candidate relative paths on disk
    $candidates = [
        $trimmed,
        'uploads/' . $trimmed,
        'uploads/products/' . $trimmed,
        'uploads/stores/' . $trimmed,
        'uploads/vendors/' . $trimmed,
        'assets/images/' . $trimmed,
        'assets/' . $trimmed
    ];

    // Also try basename only in case $trimmed has redundant folder prefixes
    $baseName = basename($trimmed);
    if ($baseName !== $trimmed) {
        $candidates[] = 'uploads/products/' . $baseName;
        $candidates[] = 'uploads/' . $baseName;
    }

    foreach ($candidates as $relPath) {
        $cleanRel = ltrim($relPath, '/');
        $fullPath = $publicDir . DIRECTORY_SEPARATOR . str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $cleanRel);

        // 1. Direct file_exists check
        if (file_exists($fullPath) && is_file($fullPath)) {
            return SITE_URL . '/' . $cleanRel;
        }

        // 2. Case-insensitive check on Linux (checking actual files in directory)
        $dir = dirname($fullPath);
        $file = basename($fullPath);
        if (is_dir($dir)) {
            $filesInDir = @scandir($dir);
            if ($filesInDir) {
                $lowerFile = strtolower($file);
                foreach ($filesInDir as $f) {
                    if ($f === '.' || $f === '..') continue;
                    if (strtolower($f) === $lowerFile) {
                        $matchedRel = dirname($cleanRel) === '.' ? $f : dirname($cleanRel) . '/' . $f;
                        return SITE_URL . '/' . ltrim($matchedRel, '/');
                    }
                }
            }
        }
    }

    // Fallback if not found on disk: if it explicitly starts with uploads/ or assets/
    if (strpos($trimmed, 'uploads/') === 0 || strpos($trimmed, 'assets/') === 0) {
        return SITE_URL . '/' . $trimmed;
    }

    // If filename given without path, default to uploads/products/
    if (!empty($trimmed)) {
        return SITE_URL . '/uploads/products/' . $trimmed;
    }

    return SITE_URL . '/assets/images/no-image.png';
}
