<?php
// File: admin/crud_testimoni.php

// 1. Error Reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 2. Session Check
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require '../includes/db_connect.php';
require '../includes/functions.php';
require '../includes/upload_helper.php'; // WAJIB ADA

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

$view = $_GET['view'] ?? 'list';
$error = ''; 
$success = '';

// --- LOGIC DELETE ---
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    try {
        // Ambil info foto dulu sebelum dihapus
        $stmt = $pdo->prepare("SELECT foto_serah_terima_url FROM testimoni WHERE id = ?");
        $stmt->execute([$_GET['id']]);
        $row = $stmt->fetch();
        
        // Hapus file fisik
        if ($row) deleteFile($row['foto_serah_terima_url']);

        // Hapus data di DB
        $pdo->prepare("DELETE FROM testimoni WHERE id = ?")->execute([$_GET['id']]);
        echo "<script>window.location='crud_testimoni.php?msg=deleted';</script>"; exit;
    } catch (Exception $e) { $error = "Gagal hapus: " . $e->getMessage(); }
}

// --- LOGIC TOGGLE VISIBILITY ---
if (isset($_GET['action']) && $_GET['action'] == 'toggle' && isset($_GET['id'])) {
    $id = $_GET['id'];
    $current = $_GET['val'];
    $newVal = ($current == 1) ? 0 : 1;
    $pdo->prepare("UPDATE testimoni SET is_visible = ? WHERE id = ?")->execute([$newVal, $id]);
    echo "<script>window.location='crud_testimoni.php?msg=updated';</script>"; exit;
}

// --- LOGIC SAVE ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        $id = $_POST['id'] ?? null;
        $judul = $_POST['judul'];
        $tgl = $_POST['tanggal'];
        
        // Handle Upload Foto (Auto WebP + Cleanup)
        $img = $_POST['existing_image'] ?? '';
        if (!empty($_FILES['gambar_upload']['name'])) {
            // Hapus foto lama jika ada
            deleteFile($img);
            
            // Upload baru
            $up = uploadImage($_FILES['gambar_upload'], "../uploads/testimoni/", "testi");
            if ($up) $img = $up;
        } elseif (!empty($_POST['gambar_url_external'])) { 
            $img = $_POST['gambar_url_external']; 
        }

        if ($id) {
            // Edit Data
            $pdo->prepare("UPDATE testimoni SET judul_serah_terima=?, tanggal_serah_terima=?, foto_serah_terima_url=? WHERE id=?")->execute([$judul, $tgl, $img, $id]);
        } else {
            // INSERT BARU -> Generate Token Unik
            $token = bin2hex(random_bytes(16)); // 32 karakter random
            $pdo->prepare("INSERT INTO testimoni (token, judul_serah_terima, tanggal_serah_terima, foto_serah_terima_url) VALUES (?, ?, ?, ?)")->execute([$token, $judul, $tgl, $img]);
        }
        echo "<script>window.location='crud_testimoni.php?msg=saved';</script>"; exit;
    } catch (Exception $e) { $error = "Error: " . $e->getMessage(); }
}

// Fetch Data
$stmt = $pdo->query("SELECT * FROM testimoni ORDER BY created_at DESC");
$dataList = $stmt->fetchAll();

$editData = null;
if ($view == 'edit' && isset($_GET['id'])) {
    $stmt = $pdo->prepare("SELECT * FROM testimoni WHERE id = ?");
    $stmt->execute([$_GET['id']]);
    $editData = $stmt->fetch();
}

$page_title = 'Kelola Testimoni';
require 'includes/header.php';
?>

<!-- KONTEN HALAMAN -->
<main class="flex-1 overflow-y-auto p-6 md:p-10 bg-gray-50 w-full">

    <?php if($error): ?><div class="bg-red-100 text-red-700 p-4 rounded mb-4"><?= $error ?></div><?php endif; ?>
    
    <?php if(isset($_GET['msg'])): ?>
        <?php 
            $msgType = $_GET['msg'];
            $msgText = '';
            if($msgType == 'saved') $msgText = 'Data berhasil disimpan!';
            elseif($msgType == 'deleted') $msgText = 'Data berhasil dihapus!';
            elseif($msgType == 'updated') $msgText = 'Status berhasil diubah!';
        ?>
        <div class="bg-green-100 text-green-700 p-4 rounded mb-4 font-bold flex items-center gap-2">
            <i class="fa-solid fa-check-circle"></i> <?= $msgText ?>
        </div>
    <?php endif; ?>

    <?php if ($view == 'list'): ?>
        <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
            <div>
                <h1 class="text-3xl font-bold text-gray-800">Testimoni & Serah Terima</h1>
                <p class="text-gray-500 text-sm">Buat link baru untuk customer mengisi ulasan.</p>
            </div>
            <a href="crud_testimoni.php?view=add" class="bg-green-600 text-white px-4 py-2 rounded-lg font-bold hover:bg-green-700 shadow flex items-center gap-2 transition transform hover:-translate-y-1">
                <i class="fa-solid fa-link"></i> Buat Link Baru
            </a>
        </div>

        <div class="bg-white rounded-lg shadow overflow-x-auto">
            <table class="w-full text-left border-collapse">
                <thead>
                    <tr class="bg-gray-800 text-white text-sm uppercase">
                        <th class="py-3 px-6">Foto</th>
                        <th class="py-3 px-6">Judul Serah Terima</th>
                        <th class="py-3 px-6">Status Isi</th>
                        <th class="py-3 px-6">Rating</th>
                        <th class="py-3 px-6">Tampil?</th>
                        <th class="py-3 px-6 text-center">Link Customer</th>
                        <th class="py-3 px-6 text-center">Aksi</th>
                    </tr>
                </thead>
                <tbody class="text-gray-600 text-sm">
                    <?php if(empty($dataList)): ?>
                        <tr><td colspan="7" class="p-6 text-center text-gray-500">Belum ada data serah terima.</td></tr>
                    <?php else: ?>
                        <?php foreach($dataList as $d): 
                            // Base URL logic buat copy link
                            $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
                            $host = $_SERVER['HTTP_HOST'];
                            // Naik satu folder dari admin/ ke root
                            $path = dirname(dirname($_SERVER['PHP_SELF'])); 
                            $base = rtrim("$protocol://$host$path", '/\\');
                            $link = "$base/input_testimoni.php?token=" . $d['token'];

                            // Fix Image Path for Admin Display
                            $imgSrc = (!empty($d['foto_serah_terima_url']) && strpos($d['foto_serah_terima_url'], 'http') === 0) 
                                ? $d['foto_serah_terima_url'] 
                                : '../'.($d['foto_serah_terima_url'] ?: 'assets/images/no-image.jpg');
                        ?>
                        <tr class="border-b hover:bg-gray-50 transition">
                            <td class="py-3 px-6">
                                <img src="<?= $imgSrc ?>" class="h-10 w-16 object-cover rounded border shadow-sm" onerror="this.src='https://via.placeholder.com/100x60?text=No+Img'">
                            </td>
                            <td class="py-3 px-6">
                                <span class="font-bold block text-gray-800"><?= htmlspecialchars($d['judul_serah_terima']) ?></span>
                                <span class="text-xs text-gray-400"><i class="fa-regular fa-calendar mr-1"></i> <?= date('d M Y', strtotime($d['tanggal_serah_terima'])) ?></span>
                            </td>
                            <td class="py-3 px-6">
                                <?php if($d['status_isi'] == 'sudah_diisi'): ?>
                                    <span class="bg-green-100 text-green-700 px-2 py-1 rounded-full text-xs font-bold border border-green-200">Sudah Diisi</span>
                                    <div class="text-xs mt-1 font-semibold text-gray-600"><?= htmlspecialchars($d['nama_customer']) ?></div>
                                <?php else: ?>
                                    <span class="bg-yellow-100 text-yellow-700 px-2 py-1 rounded-full text-xs font-bold border border-yellow-200">Menunggu</span>
                                <?php endif; ?>
                            </td>
                            <td class="py-3 px-6 text-yellow-400 text-base">
                                <?php if($d['rating'] > 0): ?>
                                    <?= str_repeat('<i class="fa-solid fa-star"></i>', $d['rating']) ?>
                                <?php else: ?> <span class="text-gray-300">-</span> <?php endif; ?>
                            </td>
                            <td class="py-3 px-6">
                                <!-- Toggle Visibility Button -->
                                <a href="crud_testimoni.php?action=toggle&id=<?= $d['id'] ?>&val=<?= $d['is_visible'] ?>" 
                                   class="px-3 py-1 rounded-full text-xs font-bold transition shadow-sm border <?= $d['is_visible'] ? 'bg-blue-100 text-blue-700 border-blue-200 hover:bg-blue-200' : 'bg-gray-200 text-gray-600 border-gray-300 hover:bg-gray-300' ?>">
                                    <?= $d['is_visible'] ? 'AKTIF' : 'SEMBUNYI' ?>
                                </a>
                            </td>
                            <td class="py-3 px-6 text-center">
                                <button onclick="copyLink('<?= $link ?>')" class="bg-white text-gray-700 px-3 py-1 rounded-lg hover:bg-gray-50 border border-gray-300 text-xs flex items-center gap-2 mx-auto transition">
                                    <i class="fa-regular fa-copy"></i> Copy Link
                                </button>
                            </td>
                            <td class="py-3 px-6 text-center">
                                <div class="flex justify-center gap-2">
                                    <a href="crud_testimoni.php?view=edit&id=<?= $d['id'] ?>" class="bg-blue-50 text-blue-600 p-2 rounded hover:bg-blue-100 transition" title="Edit"><i class="fa-solid fa-pen"></i></a>
                                    <a href="crud_testimoni.php?action=delete&id=<?= $d['id'] ?>" onclick="return confirm('Yakin hapus data & foto ini?')" class="bg-red-50 text-red-600 p-2 rounded hover:bg-red-100 transition" title="Hapus"><i class="fa-solid fa-trash"></i></a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

    <?php elseif ($view == 'add' || $view == 'edit'): ?>
        <div class="max-w-4xl mx-auto">
            <div class="flex justify-between items-center mb-6">
                <h1 class="text-3xl font-bold text-gray-800"><?= $view=='add'?'Buat Link':'Edit' ?> Serah Terima</h1>
                <a href="crud_testimoni.php" class="text-gray-500 font-bold flex items-center gap-2 hover:text-gray-800"><i class="fa-solid fa-arrow-left"></i> Kembali</a>
            </div>
            
            <form method="POST" enctype="multipart/form-data" class="bg-white p-8 rounded-xl shadow-lg border border-gray-100">
                <input type="hidden" name="id" value="<?= $editData['id'] ?? '' ?>">
                <input type="hidden" name="existing_image" value="<?= $editData['foto_serah_terima_url'] ?? '' ?>">

                <div class="mb-4">
                    <label class="block text-sm font-bold mb-2 text-gray-700">Judul Serah Terima</label>
                    <input type="text" name="judul" value="<?= htmlspecialchars($editData['judul_serah_terima'] ?? '') ?>" class="w-full p-3 border rounded-lg focus:ring-2 focus:ring-green-500 outline-none" required placeholder="Contoh: Delivery Unit Innova Zenix Pak Budi">
                </div>
                
                <div class="mb-4">
                    <label class="block text-sm font-bold mb-2 text-gray-700">Tanggal Serah Terima</label>
                    <input type="date" name="tanggal" value="<?= $editData['tanggal_serah_terima'] ?? date('Y-m-d') ?>" class="w-full p-3 border rounded-lg focus:ring-2 focus:ring-green-500 outline-none">
                </div>
                
                <div class="mb-6 p-4 bg-green-50 border border-green-100 rounded-lg border-dashed">
                    <label class="block text-sm font-bold mb-2 text-green-800">Foto Dokumentasi (Auto WebP)</label>
                    <input type="file" name="gambar_upload" class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-green-100 file:text-green-700 hover:file:bg-green-200 cursor-pointer mb-2">
                    <input type="text" name="gambar_url_external" value="<?= htmlspecialchars($editData['foto_serah_terima_url'] ?? '') ?>" class="w-full p-2 border rounded text-sm bg-white" placeholder="Atau paste URL gambar...">
                    <?php if(!empty($editData['foto_serah_terima_url'])): ?>
                        <div class="mt-4">
                            <p class="text-xs text-gray-500 mb-1">Preview:</p>
                            <img src="<?= strpos($editData['foto_serah_terima_url'], 'http') === 0 ? $editData['foto_serah_terima_url'] : '../'.$editData['foto_serah_terima_url'] ?>" class="h-32 rounded border shadow-sm">
                        </div>
                    <?php endif; ?>
                </div>

                <div class="flex justify-end gap-4 mt-8 pt-4 border-t">
                    <a href="crud_testimoni.php" class="px-6 py-3 rounded-lg text-gray-600 hover:bg-gray-100 font-bold transition">Batal</a>
                    <button type="submit" class="px-8 py-3 bg-green-600 text-white rounded-lg font-bold hover:bg-green-700 shadow-lg transition transform hover:-translate-y-0.5">Simpan & Generate Link</button>
                </div>
            </form>
        </div>
    <?php endif; ?>

</main>

<script>
function copyLink(text) {
    if(navigator.clipboard) {
        navigator.clipboard.writeText(text).then(() => {
            alert("Link berhasil disalin!\nSilahkan kirim link ini ke customer Anda.");
        });
    } else {
        // Fallback for older browsers
        const textArea = document.createElement("textarea");
        textArea.value = text;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand("copy");
        document.body.removeChild(textArea);
        alert("Link berhasil disalin!");
    }
}
</script>

<?php require 'includes/footer.php'; ?>