<?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']]);
        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') {
    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]);
        }
        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-4">Foto</th>
                        <th class="py-3 px-4">Judul / Unit</th>
                        <th class="py-3 px-4">Isi Ulasan</th>
                        <th class="py-3 px-4">Status</th>
                        <th class="py-3 px-4">Rating</th>
                        <th class="py-3 px-4 text-center">Tampil?</th>
                        <th class="py-3 px-4 text-center">Link</th>
                        <th class="py-3 px-4 text-center">Aksi</th>
                    </tr>
                </thead>
                <tbody class="text-gray-600 text-sm">
                    <?php if(empty($dataList)): ?>
                        <tr><td colspan="8" 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-4">
                                <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-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">
                                    <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-xs font-bold border border-green-200">Sudah Diisi</span>
                                <?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-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 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-4 text-center">
                                <?php if (empty($d['source']) || $d['source'] === 'manual'): ?>
                                <button onclick="copyLink('<?= $link ?>')" class="bg-white text-gray-700 px-2 py-1 rounded-lg hover:bg-gray-50 border border-gray-300 text-xs flex items-center gap-1 mx-auto transition">
                                    <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 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">
        <?= csrfInput() ?>
                <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'; ?>