<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/auth.php';
requireMember();
$userId = $_SESSION['user_id'];

// Handle rating POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validateCsrf()) { setFlash('error', 'CSRF error.'); header('Location: ' . url('/member/rating.php')); exit; }
    $kelasId = (int)$_POST['kelas_id'];
    $nilai = (int)$_POST['nilai'];
    $komentar = trim($_POST['komentar'] ?? '');
    $instruktur = trim($_POST['instruktur'] ?? '');
    if ($nilai < 1 || $nilai > 5) { setFlash('error', 'Rating 1-5.'); header('Location: ' . url('/member/rating.php')); exit; }

    // Check duplicate
    $chk = $pdo->prepare("SELECT id FROM rating WHERE user_id = ? AND kelas_id = ?");
    $chk->execute([$userId, $kelasId]);
    if ($chk->fetch()) {
        $pdo->prepare("UPDATE rating SET nilai=?, komentar=? WHERE user_id=? AND kelas_id=?")->execute([$nilai, $komentar, $userId, $kelasId]);
        setFlash('success', 'Rating diperbarui!');
    } else {
        $pdo->prepare("INSERT INTO rating (user_id, kelas_id, instruktur, nilai, komentar) VALUES (?,?,?,?,?)")->execute([$userId, $kelasId, $instruktur, $nilai, $komentar]);
        setFlash('success', 'Rating berhasil disimpan!');
    }
    header('Location: ' . url('/member/rating.php')); exit;
}

// Fetch classes user has attended
$stmt = $pdo->prepare("
    SELECT DISTINCT k.id, k.nama_kelas, k.instruktur, k.jenis_olahraga,
           r.nilai as my_rating, r.komentar as my_komentar,
           (SELECT ROUND(AVG(r2.nilai),1) FROM rating r2 WHERE r2.kelas_id = k.id) as avg_rating,
           (SELECT COUNT(*) FROM rating r3 WHERE r3.kelas_id = k.id) as total_ratings
    FROM absensi a
    JOIN kelas k ON a.kelas_id = k.id
    LEFT JOIN rating r ON r.user_id = ? AND r.kelas_id = k.id
    WHERE a.user_id = ? AND a.status = 'hadir'
    ORDER BY k.nama_kelas
");
$stmt->execute([$userId, $userId]);
$kelasList = $stmt->fetchAll();

require_once __DIR__ . '/../includes/header.php';
?>
<div class="max-w-4xl mx-auto px-4 py-8">
    <div class="mb-8 animate-fadeUp"><h1 class="text-3xl font-black mb-2">Rating <span class="text-volt">& Review</span></h1><p class="text-muted text-sm">Berikan rating untuk kelas yang sudah Anda ikuti</p></div>

    <?php if (empty($kelasList)): ?>
        <div class="empty-state"><div class="emoji">⭐</div><p class="text-lg font-bold mb-2">Belum Ada Kelas</p><p class="text-sm text-muted">Anda belum mengikuti kelas manapun</p></div>
    <?php else: ?>
        <div class="space-y-6">
        <?php foreach ($kelasList as $i => $kls):
            $delay = 'd' . min($i+1, 12);
        ?>
        <div class="card animate-fadeUp <?= $delay ?>">
            <div class="flex items-start justify-between mb-4">
                <div>
                    <h3 class="font-bold text-lg"><?= htmlspecialchars($kls['nama_kelas']) ?></h3>
                    <p class="text-xs text-muted">👤 <?= htmlspecialchars($kls['instruktur']) ?></p>
                    <?php if ($kls['avg_rating']): ?>
                    <p class="text-xs text-muted mt-1">⭐ <?= $kls['avg_rating'] ?>/5 (<?= $kls['total_ratings'] ?> review)</p>
                    <?php endif; ?>
                </div>
                <?php if ($kls['my_rating']): ?>
                    <span class="text-sm font-bold text-volt">Rating Anda: <?= $kls['my_rating'] ?>/5</span>
                <?php endif; ?>
            </div>

            <form method="POST" class="space-y-4">
                <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
                <input type="hidden" name="kelas_id" value="<?= $kls['id'] ?>">
                <input type="hidden" name="instruktur" value="<?= htmlspecialchars($kls['instruktur']) ?>">
                <input type="hidden" name="nilai" id="rating-value-<?= $kls['id'] ?>" value="<?= $kls['my_rating'] ?? 0 ?>">

                <div>
                    <label class="form-label">Rating</label>
                    <div class="star-rating" id="stars-<?= $kls['id'] ?>">
                        <?php for ($s = 1; $s <= 5; $s++): ?>
                        <span class="star <?= ($kls['my_rating'] && $s <= $kls['my_rating']) ? 'active' : '' ?>"
                              onclick="document.getElementById('rating-value-<?= $kls['id'] ?>').value=<?= $s ?>;this.parentElement.querySelectorAll('.star').forEach((st,i)=>st.classList.toggle('active',i<<?= $s ?>))">★</span>
                        <?php endfor; ?>
                    </div>
                </div>

                <div>
                    <label class="form-label">Komentar</label>
                    <textarea name="komentar" rows="2" class="form-input" placeholder="Tulis review..."><?= htmlspecialchars($kls['my_komentar'] ?? '') ?></textarea>
                </div>

                <button type="submit" class="btn-volt text-xs px-6 py-2"><?= $kls['my_rating'] ? 'Update Rating' : 'Kirim Rating' ?></button>
            </form>
        </div>
        <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
