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

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

// 2. Session Check
require_once '../includes/db_connect.php';
require_once '../includes/cache.php';
require_once '../includes/functions.php';
require_once '../includes/security.php';
secureSessionStart();
require_once '../includes/upload_helper.php'; // WAJIB ADA

// Cek Login
if (!isset($_SESSION['admin_id']) || !validateAdminSession()) { 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']]);
        
        // FIX 1: Gunakan Header Location (Server-side redirect) agar tidak blinking
        header("Location: crud_testimoni.php?msg=deleted"); 
        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]);
    
    // FIX 1: Gunakan Header Location agar tidak blinking
    header("Location: crud_testimoni.php?msg=updated"); 
    exit;
}

// --- LOGIC SAVE ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    verifyCsrf();
    cacheFlush(); // Hapus cache setelah perubahan data
    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]);
        }
        
        // FIX 1: Gunakan Header Location agar tidak blinking
        header("Location: crud_testimoni.php?msg=saved"); 
        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 shadow-sm animate-fade-in">
            <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-plus"></i> Buat Link Baru
            </a>
        </div>

        <div class="bg-white rounded-xl shadow overflow-x-auto border border-gray-100">
            <table class="w-full text-left border-collapse">
                <thead>
                    <tr class="bg-gray-800 text-white text-sm uppercase">
                        <th class="py-4 px-4 font-semibold">Foto</th>
                        <th class="py-4 px-4 font-semibold">Judul / Unit</th>
                        <th class="py-4 px-4 font-semibold">Isi Ulasan</th>
                        <th class="py-4 px-4 font-semibold">Status</th>
                        <th class="py-4 px-4 font-semibold">Rating</th>
                        <th class="py-4 px-4 text-center font-semibold">Tampil?</th>
                        <th class="py-4 px-4 text-center font-semibold">Link</th>
                        <th class="py-4 px-4 text-center font-semibold">Aksi</th>
                    </tr>
                </thead>
                <tbody class="text-gray-600 text-sm">
                    <?php if(empty($dataList)): ?>
                        <tr><td colspan="8" class="p-8 text-center text-gray-500 italic">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-4">
                                <!-- FIX 2: Tambahkan this.onerror=null agar tidak looping jika fallback image gagal diload -->
                                <img src="<?= $imgSrc ?>" class="h-12 w-20 object-cover rounded-lg border shadow-sm" onerror="this.onerror=null; this.src='../assets/images/no-image.jpg';">
                            </td>
                            <td class="py-3 px-4">
                                <span class="font-bold block text-gray-800 text-sm"><?= 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>
                                <?php if (!empty($d['source']) && $d['source'] === 'google'): ?>
                                <span class="inline-flex items-center gap-1 mt-1 text-[10px] font-bold text-blue-600 bg-blue-50 px-1.5 py-0.5 rounded border border-blue-100">
                                    <i class="fa-brands fa-google"></i> Google
                                </span>
                                <?php endif; ?>
                            </td>
                            <td class="py-3 px-4 max-w-xs">
                                <?php if ($d['status_isi'] === 'sudah_diisi' && !empty($d['isi_testimoni'])): ?>
                                    <p class="text-xs text-gray-600 italic line-clamp-3 leading-relaxed">
                                        "<?= htmlspecialchars(mb_substr($d['isi_testimoni'], 0, 180)) ?><?= mb_strlen($d['isi_testimoni']) > 180 ? '...' : '' ?>"
                                    </p>
                                    <?php if (!empty($d['nama_customer'])): ?>
                                    <span class="text-xs font-semibold text-gray-500 mt-1 block">— <?= htmlspecialchars($d['nama_customer']) ?></span>
                                    <?php endif; ?>
                                <?php elseif ($d['status_isi'] === 'menunggu'): ?>
                                    <span class="text-xs text-gray-300 italic">Belum diisi customer</span>
                                <?php else: ?>
                                    <span class="text-xs text-gray-300 italic">Kosong</span>
                                <?php endif; ?>
                            </td>
                            <td class="py-3 px-4">
                                <?php if($d['status_isi'] == 'sudah_diisi'): ?>
                                    <span class="bg-green-100 text-green-700 px-2 py-1 rounded-full text-[10px] font-bold border border-green-200 uppercase tracking-wide">Sudah Diisi</span>
                                <?php else: ?>
                                    <span class="bg-yellow-100 text-yellow-700 px-2 py-1 rounded-full text-[10px] font-bold border border-yellow-200 uppercase tracking-wide">Menunggu</span>
                                <?php endif; ?>
                            </td>
                            <td class="py-3 px-4 text-yellow-400 text-sm">
                                <?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-4 text-center">
                                <a href="crud_testimoni.php?action=toggle&id=<?= $d['id'] ?>&val=<?= $d['is_visible'] ?>" 
                                   class="px-3 py-1.5 rounded-lg text-xs font-bold transition shadow-sm border <?= $d['is_visible'] ? 'bg-blue-50 text-blue-600 border-blue-200 hover:bg-blue-100' : 'bg-gray-100 text-gray-500 border-gray-200 hover:bg-gray-200' ?>">
                                    <?= $d['is_visible'] ? 'AKTIF' : 'SEMBUNYI' ?>
                                </a>
                            </td>
                            <td class="py-3 px-4 text-center">
                                <?php if (empty($d['source']) || $d['source'] === 'manual'): ?>
                                <button onclick="copyLink('<?= $link ?>')" class="bg-white text-gray-600 px-3 py-1.5 rounded-lg hover:bg-gray-50 border border-gray-300 text-xs font-medium flex items-center gap-1 mx-auto transition shadow-sm">
                                    <i class="fa-regular fa-copy"></i> Copy
                                </button>
                                <?php else: ?>
                                <span class="text-xs text-gray-300">—</span>
                                <?php endif; ?>
                            </td>
                            <td class="py-3 px-4 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 w-8 h-8 flex items-center justify-center rounded-lg hover:bg-blue-600 hover:text-white transition shadow-sm border border-blue-100" title="Edit"><i class="fa-solid fa-pen text-xs"></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 w-8 h-8 flex items-center justify-center rounded-lg hover:bg-red-600 hover:text-white transition shadow-sm border border-red-100" title="Hapus"><i class="fa-solid fa-trash text-xs"></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 pb-10">
            <div class="flex justify-between items-center mb-6">
                <h1 class="text-2xl font-bold text-gray-800"><?= $view=='add'?'Buat Link':'Edit' ?> Serah Terima</h1>
                <a href="crud_testimoni.php" class="text-gray-500 font-bold text-sm flex items-center gap-2 hover:text-gray-800 bg-white px-4 py-2 rounded-lg border shadow-sm"><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-sm border border-gray-100">
                <?= csrfInput() ?>
                <input type="hidden" name="id" value="<?= $editData['id'] ?? '' ?>">
                <input type="hidden" name="existing_image" value="<?= $editData['foto_serah_terima_url'] ?? '' ?>">

                <div class="mb-5">
                    <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 border-gray-200 rounded-lg focus:ring-2 focus:ring-green-500 outline-none transition" required placeholder="Contoh: Delivery Unit Innova Zenix Pak Budi">
                </div>
                
                <div class="mb-5">
                    <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 border-gray-200 rounded-lg focus:ring-2 focus:ring-green-500 outline-none transition">
                </div>
                
                <div class="mb-8 p-5 bg-gray-50 border border-gray-200 rounded-lg border-dashed">
                    <label class="block text-sm font-bold mb-2 text-gray-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-gray-200 file:text-gray-700 hover:file:bg-gray-300 cursor-pointer mb-3">
                    <input type="text" name="gambar_url_external" value="<?= htmlspecialchars($editData['foto_serah_terima_url'] ?? '') ?>" class="w-full p-3 border border-gray-200 rounded-lg text-sm bg-white focus:ring-2 focus:ring-green-500 outline-none" placeholder="Atau paste URL gambar dari luar...">
                    <?php if(!empty($editData['foto_serah_terima_url'])): ?>
                        <div class="mt-4">
                            <p class="text-xs text-gray-500 mb-2 font-bold uppercase tracking-wider">Preview Gambar Saat Ini:</p>
                            <!-- FIX 2: Tambahkan this.onerror=null untuk preview gambar juga -->
                            <img src="<?= strpos($editData['foto_serah_terima_url'], 'http') === 0 ? $editData['foto_serah_terima_url'] : '../'.$editData['foto_serah_terima_url'] ?>" class="h-32 rounded-lg border shadow-sm object-cover" onerror="this.onerror=null; this.style.display='none';">
                        </div>
                    <?php endif; ?>
                </div>

                <div class="flex justify-end gap-3 pt-6 border-t border-gray-100">
                    <a href="crud_testimoni.php" class="px-6 py-2.5 rounded-lg text-gray-600 hover:bg-gray-100 font-bold transition border border-gray-200">Batal</a>
                    <button type="submit" class="px-8 py-2.5 bg-green-600 text-white rounded-lg font-bold hover:bg-green-700 shadow-md transition transform hover:-translate-y-0.5 flex items-center gap-2"><i class="fa-solid fa-save"></i> 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 {
        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'; ?>