<?php
session_start();
include '../../koneksi.php'; // Koneksi ke database

if (!isset($_SESSION['user_id'])) {
    header("Location: ../../login/");
    exit();
}

// Dapatkan user_id dari session
$user_id = $_SESSION['user_id'];

$no_template = $_POST['no_template'];
$judul_utama = $_POST['judul_utama'];
$deskripsi_utama = $_POST['deskripsi_utama'];
$tentang_usaha = $_POST['tentang_usaha'];
$keterangan_cta_bawah = $_POST['keterangan_cta_bawah'];

// 🔹 Fungsi untuk upload gambar dengan validasi error
function uploadImage($inputName, $existingImage = null)
{
    $targetDir = "../../uploads/assets/";
    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0777, true);
    }

    if (!isset($_FILES[$inputName]) || $_FILES[$inputName]["error"] !== UPLOAD_ERR_OK) {
        return ["error" => "Gagal mengunggah $inputName. Silakan pilih file yang valid."];
    }

    $fileName = basename($_FILES[$inputName]["name"]);
    $fileType = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    $allowedTypes = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

    if (!in_array($fileType, $allowedTypes)) {
        return ["error" => "Format gambar tidak valid! Gunakan JPG, JPEG, PNG, atau WEBP."];
    }

    // Cek MIME type
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $_FILES[$inputName]['tmp_name']);
    finfo_close($finfo);
    $validMimes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];

    if (!in_array($mime, $validMimes)) {
        return ["error" => "File bukan gambar yang valid."];
    }

    $newFileName = uniqid() . "_" . time() . "." . $fileType;
    $targetFilePath = $targetDir . $newFileName;
    $tmpFile = $_FILES[$inputName]["tmp_name"];

    $compressed = false;
    $quality = 85;

    if ($fileType === 'gif') {
        if (move_uploaded_file($tmpFile, $targetFilePath)) {
            if ($existingImage && file_exists($targetDir . $existingImage)) {
                unlink($targetDir . $existingImage);
            }
            return ["success" => $newFileName];
        } else {
            return ["error" => "Gagal menyimpan file GIF."];
        }
    }

    // Kompres JPEG/PNG/WEBP
    switch ($fileType) {
        case 'jpg':
        case 'jpeg':
            $image = imagecreatefromjpeg($tmpFile);
            break;
        case 'png':
            $image = imagecreatefrompng($tmpFile);
            break;
        case 'webp':
            $image = imagecreatefromwebp($tmpFile);
            break;
        default:
            $image = null;
            break;
    }

    if ($image) {
        do {
            ob_start();
            switch ($fileType) {
                case 'jpg':
                case 'jpeg':
                    imagejpeg($image, null, $quality);
                    break;
                case 'png':
                    imagepng($image, null, (int)((100 - $quality) / 10));
                    break;
                case 'webp':
                    imagewebp($image, null, $quality);
                    break;
            }
            $imageData = ob_get_clean();

            if (strlen($imageData) <= 1048576) { // 1MB
                file_put_contents($targetFilePath, $imageData);
                $compressed = true;
            } else {
                $quality -= 5;
            }
        } while (!$compressed && $quality > 10);

        imagedestroy($image);
    }

    if ($compressed) {
        if ($existingImage && file_exists($targetDir . $existingImage)) {
            unlink($targetDir . $existingImage);
        }
        return ["success" => $newFileName];
    } else {
        return ["error" => "Gagal mengompres gambar di bawah 1MB."];
    }
}



// 🔹 Ambil data lama dari database
$sql = "SELECT * FROM landingpage WHERE id_user = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();

if ($result->num_rows > 0) {
    $errors = [];

    // 🔹 Upload gambar jika ada file yang diunggah
    $gambar_utama = isset($_FILES["gambar_utama"]) && $_FILES["gambar_utama"]["error"] === 0
                    ? uploadImage("gambar_utama", $row['gambar_utama'])
                    : ["success" => $row['gambar_utama']];

    $gambar_tentang = isset($_FILES["gambar_tentang"]) && $_FILES["gambar_tentang"]["error"] === 0
                    ? uploadImage("gambar_tentang", $row['gambar_tentang'])
                    : ["success" => $row['gambar_tentang']];

    $gambar_keunggulan = isset($_FILES["gambar_keunggulan"]) && $_FILES["gambar_keunggulan"]["error"] === 0
                    ? uploadImage("gambar_keunggulan", $row['gambar_keunggulan'])
                    : ["success" => $row['gambar_keunggulan']];

    // 🔹 Cek jika ada error pada upload gambar
    foreach ([$gambar_utama, $gambar_tentang, $gambar_keunggulan] as $key => $gambar) {
        if (isset($gambar["error"])) {
            $errors[] = $gambar["error"];
        }
    }

    // 🔹 Jika ada error, hentikan eksekusi dan tampilkan pesan
    if (!empty($errors)) {
        $_SESSION['error'] = implode("<br>", $errors);
        header("Location: ../landingpage");
        exit();
    }

    // 🔹 Update database hanya jika tidak ada error pada upload gambar
    $updateSql = "UPDATE landingpage SET 
                    no_template = ?, 
                    judul_utama = ?, 
                    deskripsi_utama = ?, 
                    tentang_usaha = ?, 
                    keterangan_cta_bawah = ?, 
                    gambar_utama = ?, 
                    gambar_tentang = ?, 
                    gambar_keunggulan = ? 
                  WHERE id_user = ?";

    $stmtUpdate = $conn->prepare($updateSql);
    $stmtUpdate->bind_param(
        "isssssssi",
        $no_template,
        $judul_utama,
        $deskripsi_utama,
        $tentang_usaha,
        $keterangan_cta_bawah,
        $gambar_utama["success"],
        $gambar_tentang["success"],
        $gambar_keunggulan["success"],
        $user_id
    );

    if ($stmtUpdate->execute()) {
        $_SESSION['success'] = "Data landingpage berhasil diperbarui";
    } else {
        $_SESSION['error'] = "Terjadi kesalahan saat menyimpan data.";
    }

    header("Location: ../landingpage");
    exit();
}

$stmt->close();
$conn->close();
?>
