<?php
// admin/_upload.php — shared file upload helper with automatic WebP conversion

/**
 * Handle image upload from $_FILES and automatically convert to WebP format for optimal performance
 * @param string $fileKey      Key in $_FILES
 * @param string $subDir       Subdirectory under assets/uploads/ (e.g. 'countries', 'itinerary')
 * @param string $existingPath Current image path (kept if no new upload)
 * @param int    $quality      WebP compression quality (default 85)
 * @return array ['path'=>string|null, 'error'=>string|null]
 */
function adm_upload_image(string $fileKey, string $subDir, string $existingPath = '', int $quality = 85): array {
    if (empty($_FILES[$fileKey]['name'])) {
        // No new file — keep existing
        return ['path' => $existingPath, 'error' => null];
    }

    $file     = $_FILES[$fileKey];
    $maxSize  = 5 * 1024 * 1024; // 5 MB
    $allowed  = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];

    if ($file['error'] !== UPLOAD_ERR_OK) {
        return ['path' => $existingPath, 'error' => 'Upload gagal (kode error: ' . $file['error'] . ')'];
    }
    if ($file['size'] > $maxSize) {
        return ['path' => $existingPath, 'error' => 'Ukuran file terlalu besar. Maksimal 5 MB.'];
    }

    // Validate MIME type
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime  = $finfo->file($file['tmp_name']);
    if (!in_array($mime, $allowed, true)) {
        return ['path' => $existingPath, 'error' => 'Format file tidak didukung. Harap gunakan JPG, PNG, WebP, atau GIF.'];
    }

    $uploadDir = dirname(__DIR__) . '/assets/uploads/' . $subDir . '/';
    if (!is_dir($uploadDir)) {
        @mkdir($uploadDir, 0755, true);
    }

    $fileName = uniqid('img_', true) . '.webp';
    $destPath = $uploadDir . $fileName;

    // Load image resource based on MIME
    $tmpPath = $file['tmp_name'];
    $img = null;

    switch ($mime) {
        case 'image/jpeg':
            $img = @imagecreatefromjpeg($tmpPath);
            break;
        case 'image/png':
            $img = @imagecreatefrompng($tmpPath);
            if ($img) {
                imagepalettetotruecolor($img);
                imagealphablending($img, true);
                imagesavealpha($img, true);
            }
            break;
        case 'image/gif':
            $img = @imagecreatefromgif($tmpPath);
            if ($img) {
                imagepalettetotruecolor($img);
            }
            break;
        case 'image/webp':
            $img = @imagecreatefromwebp($tmpPath);
            break;
    }

    $saved = false;
    if ($img) {
        // Save as optimized WebP
        $saved = imagewebp($img, $destPath, $quality);
        imagedestroy($img);
    }

    // Fallback if GD conversion failed
    if (!$saved) {
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $fileName = uniqid('img_', true) . '.' . strtolower($ext);
        $destPath = $uploadDir . $fileName;
        if (!move_uploaded_file($tmpPath, $destPath)) {
            return ['path' => $existingPath, 'error' => 'Gagal menyimpan file gambar ke server.'];
        }
    }

    // Delete previous uploaded file if local
    if ($existingPath && str_starts_with($existingPath, 'assets/uploads/')) {
        $oldFull = dirname(__DIR__) . '/' . $existingPath;
        if (file_exists($oldFull)) @unlink($oldFull);
    }

    return ['path' => 'assets/uploads/' . $subDir . '/' . $fileName, 'error' => null];
}
