<?php
/**
 * Katalog Kelas — Member Page (Photo Card Style)
 * Browse & filter classes, add to cart via AJAX
 */
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/auth.php';
requireMember();

// Fetch all active classes
$stmt = $pdo->query("SELECT k.*, 
    (SELECT ROUND(AVG(r.nilai),1) FROM rating r WHERE r.kelas_id = k.id) as avg_rating,
    (SELECT COUNT(*) FROM rating r2 WHERE r2.kelas_id = k.id) as total_reviews
    FROM kelas k WHERE k.status = 'aktif' ORDER BY k.hari, k.jam_mulai");
$kelasList = $stmt->fetchAll();

// Get unique jenis for filter
$jenisStmt = $pdo->query("SELECT DISTINCT jenis_olahraga FROM kelas WHERE status='aktif' ORDER BY jenis_olahraga");
$jenisList = $jenisStmt->fetchAll(PDO::FETCH_COLUMN);

// Cart count & total
$cartCount = getCartCount($pdo);
$cartStmt = $pdo->prepare("SELECT SUM(k.harga) as total FROM keranjang kr JOIN kelas k ON kr.kelas_id = k.id WHERE kr.user_id = ?");
$cartStmt->execute([$_SESSION['user_id']]);
$cartTotal = (int)($cartStmt->fetchColumn() ?: 0);

// Image mapping based on jenis_olahraga
$imageMap = [
    'yoga'      => url('/assets/images/yoga.png'),
    'zumba'     => url('/assets/images/zumba.png'),
    'muay thai' => url('/assets/images/muay_thai.png'),
    'gym'       => url('/assets/images/gym.png'),
    'pilates'   => url('/assets/images/pilates.png'),
    'spinning'  => url('/assets/images/spinning.png'),
    'crossfit'  => url('/assets/images/gym.png'),
];

function getClassImage($jenis) {
    global $imageMap;
    return $imageMap[strtolower($jenis)] ?? url('/assets/images/gym.png');
}

require_once __DIR__ . '/../includes/header.php';
?>

<div class="max-w-7xl mx-auto px-4 py-8">
    <!-- Page Header -->
    <div class="mb-8" style="opacity:0;animation:fadeUp 0.5s ease forwards;">
        <h1 class="text-3xl sm:text-4xl font-black mb-2">Katalog <span class="text-volt">Kelas</span></h1>
        <p class="text-muted text-sm">Pilih kelas yang sesuai dengan gaya hidup dan level fitnesmu</p>
    </div>

    <!-- Filters -->
    <div class="flex flex-wrap items-center gap-4 mb-8" style="opacity:0;animation:fadeUp 0.5s ease 0.1s forwards;">
        <!-- Jenis dropdown -->
        <select id="filter-jenis" onchange="filterKelas()" class="form-input w-auto min-w-[160px] bg-surface border-border text-white">
            <option value="all">Semua Jenis</option>
            <?php foreach ($jenisList as $j): ?>
                <option value="<?= htmlspecialchars(strtolower($j)) ?>"><?= htmlspecialchars($j) ?></option>
            <?php endforeach; ?>
        </select>

        <!-- Intensitas toggles -->
        <div class="flex gap-2">
            <button class="filter-intensitas active px-4 py-2 text-xs font-bold rounded-full border border-border bg-surface text-muted hover:text-white hover:border-volt transition-all" data-value="all">Semua</button>
            <button class="filter-intensitas px-4 py-2 text-xs font-bold rounded-full border border-border bg-surface text-muted hover:text-white hover:border-volt transition-all" data-value="low">🟢 Low</button>
            <button class="filter-intensitas px-4 py-2 text-xs font-bold rounded-full border border-border bg-surface text-muted hover:text-white hover:border-volt transition-all" data-value="medium">🟡 Medium</button>
            <button class="filter-intensitas px-4 py-2 text-xs font-bold rounded-full border border-border bg-surface text-muted hover:text-white hover:border-volt transition-all" data-value="high">🔴 High</button>
        </div>
    </div>

    <!-- Kelas Grid -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6" id="kelas-grid">
        <?php foreach ($kelasList as $i => $kelas):
            $pct = $kelas['kuota'] > 0 ? round(($kelas['sisa_slot'] / $kelas['kuota']) * 100) : 0;
            $fillColor = $pct >= 60 ? 'fill-green' : ($pct >= 30 ? 'fill-yellow' : 'fill-red');
            $delay = 'd' . min($i + 1, 12);
            $imgSrc = getClassImage($kelas['jenis_olahraga']);
            $avgRating = $kelas['avg_rating'] ? number_format($kelas['avg_rating'], 1) : null;
        ?>
        <div class="kelas-card <?= $delay ?>"
             data-jenis="<?= htmlspecialchars(strtolower($kelas['jenis_olahraga'])) ?>"
             data-intensitas="<?= $kelas['intensitas'] ?>">
            
            <!-- Card Image -->
            <div class="card-img">
                <img src="<?= $imgSrc ?>" alt="<?= htmlspecialchars($kelas['nama_kelas']) ?>" loading="lazy">
                <div class="img-overlay">
                    <div class="overlay-top">
                        <span class="sport-tag"><?= htmlspecialchars($kelas['jenis_olahraga']) ?></span>
                        <?php if ($avgRating): ?>
                            <span class="img-rating">★ <?= $avgRating ?></span>
                        <?php endif; ?>
                    </div>
                    <div class="overlay-bottom">
                        <span class="badge-<?= $kelas['intensitas'] ?>"><?= ucfirst($kelas['intensitas']) ?></span>
                        <span class="sport-tag"><?= $kelas['sisa_slot'] ?>/<?= $kelas['kuota'] ?> slot</span>
                    </div>
                </div>
            </div>

            <!-- Card Body -->
            <div class="card-body">
                <h3 class="card-title"><?= htmlspecialchars($kelas['nama_kelas']) ?></h3>
                <div class="card-subtitle">
                    <span>👤 <?= htmlspecialchars($kelas['instruktur']) ?></span>
                    <span>·</span>
                    <span>📅 <?= htmlspecialchars($kelas['hari']) ?>, <?= date('H:i', strtotime($kelas['jam_mulai'])) ?>–<?= date('H:i', strtotime($kelas['jam_selesai'])) ?></span>
                </div>

                <!-- Slot Bar -->
                <div class="slot-bar">
                    <div class="slot-fill <?= $fillColor ?>" data-width="<?= $pct ?>%" style="animation-delay:<?= 0.3 + ($i * 0.05) ?>s;"></div>
                </div>

                <!-- Price + Add Button -->
                <div class="card-footer-row">
                    <div>
                        <span class="text-xl font-black text-volt">Rp <?= number_format($kelas['harga'], 0, ',', '.') ?></span>
                        <span class="text-xs text-muted"> /sesi</span>
                    </div>
                    <?php if ($kelas['sisa_slot'] > 0): ?>
                        <button onclick="addToCart(<?= $kelas['id'] ?>, '<?= htmlspecialchars(addslashes($kelas['nama_kelas'])) ?>')"
                                class="flex items-center gap-2 px-4 py-2.5 bg-volt text-dark rounded-full font-black text-xs hover:shadow-lg hover:shadow-volt/30 transition-all duration-200 active:scale-95"
                                title="Tambah ke keranjang"
                                id="add-btn-<?= $kelas['id'] ?>">
                            Book Now ↗
                        </button>
                    <?php else: ?>
                        <span class="text-xs text-red-400 font-bold px-4 py-2 bg-red-500/10 rounded-full">PENUH</span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <?php if (empty($kelasList)): ?>
        <div class="empty-state mt-12">
            <div class="emoji">🏋️</div>
            <p class="text-lg font-bold mb-2">Belum Ada Kelas</p>
            <p class="text-sm text-muted">Kelas akan segera tersedia. Stay tuned!</p>
        </div>
    <?php endif; ?>
</div>

<!-- Floating Cart Pill -->
<?php if ($cartCount > 0): ?>
<a href="<?= BASE_URL ?>/member/keranjang.php" class="cart-float" id="cart-pill">
    🛒 <?= $cartCount ?> kelas · Rp <?= number_format($cartTotal, 0, ',', '.') ?> →
</a>
<?php endif; ?>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
