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

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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $id_user = $_SESSION['user_id'];

    // 🔹 Ambil ID dari tabel berdasarkan id_user
    function getData($conn, $query, $id_user) {
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $id_user);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result->fetch_assoc();
    }

    // Ambil data usaha
    $data_usaha = getData($conn, "SELECT id_usaha, nama_usaha FROM datausaha WHERE id_user = ?", $id_user);
    $id_usaha = $data_usaha['id_usaha'] ?? null;
    $nama_usaha = $data_usaha['nama_usaha'] ?? '';
    
    // Buat slug awal
    $slug_url = $nama_usaha ? strtolower(str_replace(" ", "-", trim($nama_usaha))) : null;
    
    if ($slug_url) {
        // Cek apakah slug sudah ada di landingpage
        $query = "SELECT COUNT(*) as count FROM landingpage WHERE slug_url = ?";
        
        // Pastikan slug unik hanya jika sudah ada di database
        $stmt = $conn->prepare($query);
        $stmt->bind_param("s", $slug_url);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
    
        if ($row['count'] > 0) {
            // Slug sudah dipakai, tambahkan angka agar unik
            $counter = 1;
            $slug_base = $slug_url;
    
            do {
                $slug_url = $slug_base . "-" . $counter;
                
                $stmt->bind_param("s", $slug_url);
                $stmt->execute();
                $result = $stmt->get_result();
                $row = $result->fetch_assoc();
    
                $counter++;
            } while ($row['count'] > 0);
        }
    }
    
    $data_seo = getData($conn, "SELECT id_seo, judul_seo FROM seo WHERE id_user = ?", $id_user);
    $id_seo = $data_seo['id_seo'] ?? null;
    
    $id_testimoni = getData($conn, "SELECT id_testimoni FROM testimoni WHERE id_user = ?", $id_user)['id_testimoni'] ?? null;
    $id_produk = getData($conn, "SELECT id_produk FROM produk WHERE id_user = ?", $id_user)['id_produk'] ?? null;
    $id_keunggulan = getData($conn, "SELECT id_keunggulan FROM keunggulan WHERE id_user = ?", $id_user)['id_keunggulan'] ?? null;

    if (!$id_usaha || !$id_seo || !$id_testimoni || !$id_produk || !$id_keunggulan) {
        $_SESSION['error'] = "Beberapa data tidak ditemukan.";
        header("Location: ../landingpage");
        exit();
    }

    $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
function uploadImage($inputName)
{
    $targetDir = "../../uploads/assets/";
    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0777, true);
    }

    if (!isset($_FILES[$inputName]) || $_FILES[$inputName]['error'] == UPLOAD_ERR_NO_FILE) {
        return null;
    }

    if ($_FILES[$inputName]['error'] !== UPLOAD_ERR_OK) {
        $_SESSION['error'] = "Gagal upload file. Ukuran terlalu besar atau bermasalah.";
        header("Location: ../landingpage");
        exit();
    }

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

    if (!in_array($fileType, $allowedTypes)) {
        $_SESSION['old_input'] = $_POST;
        $_SESSION['error'] = "Format gambar tidak valid! Gunakan JPG, JPEG, PNG, atau WEBP.";
        header("Location: ../landingpage");
        exit();
    }

    // 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)) {
        $_SESSION['error'] = "File bukan gambar yang valid.";
        header("Location: ../landingpage");
        exit();
    }

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

    $fileSize = $_FILES[$inputName]['size'];

    // Jika file GIF atau ukurannya sudah < 1MB, langsung simpan tanpa kompres
    if ($fileType === 'gif' || $fileSize <= 1048576) {
        move_uploaded_file($tmpFile, $targetFilePath);
        return $newFileName;
    }

    // Kompres gambar lainnya
    $image = null;
    if ($fileType === 'jpg' || $fileType === 'jpeg') {
        $image = imagecreatefromjpeg($tmpFile);
    } elseif ($fileType === 'png') {
        $image = imagecreatefrompng($tmpFile);
    } elseif ($fileType === 'webp') {
        $image = imagecreatefromwebp($tmpFile);
    }

    $compressed = false;
    $quality = 85;

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

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

        imagedestroy($image);
    }

    if ($compressed) {
        return $newFileName;
    } else {
        $_SESSION['error'] = "Gagal mengompres gambar di bawah 1MB.";
        header("Location: ../landingpage");
        exit();
    }
}


// 🔹 Upload gambar utama, tentang usaha, dan keunggulan
$gambar_utama = uploadImage("gambar_utama");
$gambar_tentang = uploadImage("gambar_tentang");
$gambar_keunggulan = uploadImage("gambar_keunggulan");

// 🔹 Pastikan semua input tidak kosong
if ($no_template && $judul_utama && $deskripsi_utama && $tentang_usaha && $keterangan_cta_bawah && $gambar_utama && $gambar_tentang && $gambar_keunggulan) {
    // 🔹 Simpan ke database
    $query = "INSERT INTO landingpage 
        (id_user, id_usaha, id_seo, id_keunggulan, id_testimoni, id_produk, no_template, judul_utama, deskripsi_utama, gambar_utama, tentang_usaha, gambar_tentang, gambar_keunggulan, keterangan_cta_bawah, slug_url) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $conn->prepare($query);
    $stmt->bind_param("iiiiiiissssssss", $id_user, $id_usaha, $id_seo, $id_keunggulan, $id_testimoni, $id_produk, $no_template, $judul_utama, $deskripsi_utama, $gambar_utama, $tentang_usaha, $gambar_tentang, $gambar_keunggulan, $keterangan_cta_bawah, $slug_url);

    if ($stmt->execute()) {
        $source_file = 'original.php';
        $target_dir = '../../page/' . $slug_url;
        $target_file = $target_dir . '/index.php';

        if (!is_dir($target_dir)) {
            mkdir($target_dir, 0777, true);
        }

        if (copy($source_file, $target_file)) {
            $file_content = file_get_contents($target_file);
            $file_content = preg_replace('/\$user_id\s*=\s*[^;]+;/', '$user_id = ' . $id_user . ';', $file_content);
            file_put_contents($target_file, $file_content);

            unset($_SESSION['old_input']);
            
            $_SESSION['success'] = "Data landingpage berhasil disimpan";
            header("Location: ../landingpage");
            exit();
        }
    } else {
        $_SESSION['old'] = $_POST; 
        $_SESSION['error'] = "Terjadi kesalahan saat menyimpan data.";
        header("Location: ../landingpage");
        exit();
    }
} else {
    $_SESSION['old'] = $_POST; 
    $_SESSION['error'] = "Harap lengkapi semua bidang!";
    header("Location: ../landingpage");
    exit();
}
} else {
header("Location: ../landingpage");
exit();
}

