<?php
$uploadDir = __DIR__ . '../../../uploads/';
$uploadUrl = 'https://senarulodge.com/uploads/';
$maxFileSize = 1 * 1024 * 1024; // Maks 1MB

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['upload'])) {
    $file = $_FILES['upload'];
    $imageFileType = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

    // Validasi tipe file
    if (!in_array($imageFileType, array('jpg', 'jpeg', 'png', 'gif'))) {
        $response = [
            'uploaded' => false,
            'error' => ['message' => 'Hanya gambar JPG, JPEG, PNG, dan GIF yang diizinkan.']
        ];
    }
    // Validasi ukuran file
    elseif ($file['size'] > $maxFileSize) {
        $response = [
            'uploaded' => false,
            'error' => ['message' => 'Ukuran file terlalu besar. Maksimal 1MB.']
        ];
    }
    else {
        $rand = rand();
        $filenameNoExt = pathinfo($file['name'], PATHINFO_FILENAME);
        $targetFile = $uploadDir . $rand . '_' . $filenameNoExt;
        $finalFileName = '';

        list($orig_width, $orig_height) = getimagesize($file['tmp_name']);
        $new_width = 600;
        $new_height = ($new_width / $orig_width) * $orig_height;

        // Baca gambar sumber
        if ($imageFileType == 'jpg' || $imageFileType == 'jpeg') {
            $src_image = imagecreatefromjpeg($file['tmp_name']);
        } elseif ($imageFileType == 'png') {
            $src_image = imagecreatefrompng($file['tmp_name']);
        } elseif ($imageFileType == 'gif') {
            $src_image = imagecreatefromgif($file['tmp_name']);
        }

        if ($src_image) {
            $dst_image = imagecreatetruecolor($new_width, $new_height);

            // Preserve transparansi PNG & GIF
            if ($imageFileType == 'png' || $imageFileType == 'gif') {
                imagecolortransparent($dst_image, imagecolorallocatealpha($dst_image, 0, 0, 0, 127));
                imagealphablending($dst_image, false);
                imagesavealpha($dst_image, true);
            }

            imagecopyresampled($dst_image, $src_image, 0, 0, 0, 0, $new_width, $new_height, $orig_width, $orig_height);

            // Coba simpan ke WebP kalau fungsi tersedia
            if (function_exists('imagewebp')) {
                $finalFileName = $rand . '_' . $filenameNoExt . '.webp';
                $finalPath = $uploadDir . $finalFileName;
                imagewebp($dst_image, $finalPath, 70);
            } else {
                // Kalau nggak support WebP, simpan sesuai tipe awal
                if ($imageFileType == 'png') {
                    $finalFileName = $rand . '_' . $filenameNoExt . '.png';
                    $finalPath = $uploadDir . $finalFileName;
                    imagepng($dst_image, $finalPath);
                } elseif ($imageFileType == 'gif') {
                    $finalFileName = $rand . '_' . $filenameNoExt . '.gif';
                    $finalPath = $uploadDir . $finalFileName;
                    imagegif($dst_image, $finalPath);
                } else {
                    $finalFileName = $rand . '_' . $filenameNoExt . '.jpg';
                    $finalPath = $uploadDir . $finalFileName;
                    imagejpeg($dst_image, $finalPath, 80);
                }
            }

            imagedestroy($src_image);
            imagedestroy($dst_image);

            $response = [
                'uploaded' => true,
                'url' => $uploadUrl . $finalFileName
            ];
        } else {
            $response = [
                'uploaded' => false,
                'error' => ['message' => 'Gagal memproses gambar.']
            ];
        }
    }

    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}
?>
