<?php
// File: input_testimoni.php
// Halaman input testimoni oleh customer via link token.

ini_set('display_errors', 0);
error_reporting(E_ALL);

require_once 'includes/db_connect.php';
require_once 'includes/security.php';

// Rate limiting — maks 5 submit per 10 menit per IP (AUDIT FIX)
if (!checkRateLimit('input_testimoni', 5, 600)) {
    http_response_code(429);
    die('<div style="font-family:sans-serif;padding:40px;text-align:center"><h2>Terlalu Banyak Percobaan</h2><p>Silakan coba lagi dalam beberapa menit.</p></div>');
}

$token = preg_replace('/[^a-zA-Z0-9\-_]/', '', $_GET['token'] ?? '');
$msg   = '';
$error = '';

if (empty($token)) {
    die('<div style="font-family:sans-serif;padding:40px;text-align:center"><h2>Link Tidak Valid</h2><p>Token tidak ditemukan atau sudah kadaluarsa.</p></div>');
}

$stmt = $pdo->prepare("SELECT * FROM testimoni WHERE token = ? LIMIT 1");
$stmt->execute([$token]);
$data = $stmt->fetch();

if (!$data) {
    die('<div style="font-family:sans-serif;padding:40px;text-align:center"><h2>Link Tidak Ditemukan</h2><p>Data serah terima tidak ditemukan atau link sudah kadaluarsa.</p></div>');
}

// Proses Simpan Testimoni
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // AUDIT FIX: Sanitasi dan validasi semua input
    $nama   = trim(strip_tags(substr($_POST['nama_customer'] ?? '', 0, 100)));
    $ulasan = trim(strip_tags(substr($_POST['isi_testimoni'] ?? '', 0, 1000)));
    $rating = intval($_POST['rating'] ?? 0);

    if (empty($nama) || mb_strlen($nama) < 2) {
        $error = 'Nama tidak valid.';
    } elseif ($rating < 1 || $rating > 5) {
        $error = 'Rating harus antara 1–5 bintang.';
    } else {
        try {
            $updateSql = "UPDATE testimoni SET
                          nama_customer = ?,
                          rating        = ?,
                          isi_testimoni = ?,
                          status_isi    = 'sudah_diisi'
                          WHERE token = ?";
            $stmtUp = $pdo->prepare($updateSql);
            $stmtUp->execute([$nama, $rating, $ulasan, $token]);

            $msg = 'Terima kasih! Testimoni Anda berhasil disimpan.';
            // Refresh data
            $stmt->execute([$token]);
            $data = $stmt->fetch();
        } catch (Exception $e) {
            // AUDIT FIX: Jangan expose detail error DB ke publik
            error_log('[Testimoni] Gagal simpan: ' . $e->getMessage());
            $error = 'Gagal menyimpan. Silakan coba lagi atau hubungi kami.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="robots" content="noindex, nofollow">
    <title>Berikan Testimoni</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .star-rating input { display: none; }
        .star-rating label { cursor: pointer; color: #ddd; font-size: 2rem; transition: color 0.2s; }
        .star-rating input:checked ~ label,
        .star-rating label:hover,
        .star-rating label:hover ~ label { color: #facc15; }
        .star-rating { direction: rtl; display: inline-flex; }
    </style>
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center p-4">

    <div class="bg-white rounded-2xl shadow-xl max-w-md w-full overflow-hidden">
        <!-- Header Foto -->
        <div class="relative h-48 bg-gray-200">
            <?php if (!empty($data['foto_serah_terima_url'])): ?>
            <img src="<?= htmlspecialchars($data['foto_serah_terima_url']) ?>"
                 class="w-full h-full object-cover"
                 alt="Foto serah terima <?= htmlspecialchars($data['judul_serah_terima']) ?>"
                 loading="eager">
            <?php endif; ?>
            <div class="absolute inset-0 bg-black/40 flex items-end p-6">
                <div>
                    <span class="bg-red-600 text-white text-xs font-bold px-2 py-1 rounded">Serah Terima Unit</span>
                    <h1 class="text-white text-xl font-bold mt-1 shadow-sm"><?= htmlspecialchars($data['judul_serah_terima']) ?></h1>
                    <p class="text-white/80 text-sm">
                        <?= !empty($data['tanggal_serah_terima'])
                            ? htmlspecialchars(date('d M Y', strtotime($data['tanggal_serah_terima'])))
                            : '' ?>
                    </p>
                </div>
            </div>
        </div>

        <div class="p-8">
            <?php if ($msg): ?>
                <div class="text-center py-8" role="alert">
                    <div class="w-20 h-20 rounded-full bg-green-100 flex items-center justify-center mx-auto mb-4">
                        <i class="fa-solid fa-check-circle text-4xl text-green-500" aria-hidden="true"></i>
                    </div>
                    <h2 class="text-2xl font-bold text-gray-800 mb-2">Terima Kasih!</h2>
                    <p class="text-gray-500"><?= htmlspecialchars($msg) ?></p>
                </div>
            <?php else: ?>
                <h2 class="text-xl font-bold text-gray-800 mb-6 text-center">Bagikan Pengalaman Anda</h2>

                <?php if (!empty($error)): ?>
                <div class="bg-red-50 border border-red-100 text-red-600 p-3 rounded-xl mb-5 text-sm flex items-center gap-2" role="alert">
                    <i class="fa-solid fa-circle-exclamation" aria-hidden="true"></i>
                    <?= htmlspecialchars($error) ?>
                </div>
                <?php endif; ?>

                <form method="POST" action="" novalidate>
                    <!-- Nama -->
                    <div class="mb-5">
                        <label for="nama_customer" class="block text-sm font-bold text-gray-700 mb-2">
                            Nama Anda <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="nama_customer" name="nama_customer"
                            class="w-full p-3 border rounded-xl bg-gray-50 focus:ring-2 focus:ring-red-500 outline-none transition"
                            value="<?= htmlspecialchars($data['nama_customer'] ?? '') ?>"
                            maxlength="100" required aria-required="true"
                            placeholder="Contoh: Pak Budi">
                    </div>

                    <!-- Rating Bintang -->
                    <div class="mb-5">
                        <label class="block text-sm font-bold text-gray-700 mb-3">
                            Rating <span class="text-red-500">*</span>
                        </label>
                        <div class="star-rating" role="radiogroup" aria-label="Pilih rating bintang">
                            <?php for ($i = 5; $i >= 1; $i--): ?>
                            <input type="radio" id="star<?= $i ?>" name="rating" value="<?= $i ?>"
                                <?= ((int)($data['rating'] ?? 0) === $i) ? 'checked' : '' ?>
                                aria-label="<?= $i ?> bintang">
                            <label for="star<?= $i ?>" title="<?= $i ?> bintang">
                                <i class="fa-solid fa-star" aria-hidden="true"></i>
                            </label>
                            <?php endfor; ?>
                        </div>
                    </div>

                    <!-- Ulasan -->
                    <div class="mb-6">
                        <label for="isi_testimoni" class="block text-sm font-bold text-gray-700 mb-2">
                            Ulasan / Kesan
                        </label>
                        <textarea id="isi_testimoni" name="isi_testimoni" rows="4"
                            class="w-full p-3 border rounded-xl bg-gray-50 focus:ring-2 focus:ring-red-500 outline-none resize-none transition"
                            maxlength="1000"
                            placeholder="Ceritakan pengalaman Anda bersama kami..."><?= htmlspecialchars($data['isi_testimoni'] ?? '') ?></textarea>
                    </div>

                    <button type="submit"
                        class="w-full bg-red-600 hover:bg-red-700 text-white font-bold py-3 rounded-xl transition active:scale-95 shadow">
                        <i class="fa-solid fa-paper-plane mr-2" aria-hidden="true"></i>
                        Kirim Testimoni
                    </button>
                </form>
            <?php endif; ?>
        </div>
    </div>

</body>
</html>
