<?php
if (empty($_SESSION['user'])) {
    header('Location: /login.php');
    exit;
}

// Fetch active credit bundles
$stmt = $db->prepare('SELECT * FROM credit_bundles WHERE user_id = ? AND credits_remaining > 0 AND expires_at > NOW() ORDER BY expires_at ASC');
$stmt->execute([$_SESSION['user']['id']]);
$creditBundles = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate total available credits
$totalCredits = 0;
foreach ($creditBundles as $bundle) {
    $totalCredits += (int)$bundle['credits_remaining'];
}

// Fetch user's bookings
$stmt = $db->prepare('SELECT * FROM bookings WHERE user_id = ? ORDER BY class_time DESC');
$stmt->execute([$_SESSION['user']['id']]);
$bookings = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Credit bundle options
$bundles = [
    ['credits' => 1, 'price_cents' => 500],
    ['credits' => 3, 'price_cents' => 1400],
    ['credits' => 5, 'price_cents' => 2200],
    ['credits' => 10, 'price_cents' => 4000],
    ['credits' => 15, 'price_cents' => 5600],
    ['credits' => 20, 'price_cents' => 7200],
];
?>

<div class="dashboard-content">
    <header class="dashboard-header">
        <h1>My Bookings & Credits</h1>
        <div class="credits-summary">
            Available Credits: <strong><?= $totalCredits ?></strong>
        </div>
    </header>

    <!-- Credit Bundles Status -->
    <?php if (!empty($creditBundles)): ?>
    <section class="credit-bundles card">
        <h2>Active Credit Bundles</h2>
        <div class="bundles-grid">
            <?php foreach ($creditBundles as $bundle): ?>
            <div class="bundle-card">
                <div class="bundle-credits"><?= (int)$bundle['credits_remaining'] ?></div>
                <div class="bundle-expiry">Expires: <?= date('M j, Y', strtotime($bundle['expires_at'])) ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </section>
    <?php endif; ?>

    <!-- Bookings List -->
    <section class="bookings-list card">
        <h2>My Bookings</h2>
        <?php if (empty($bookings)): ?>
            <p class="no-bookings">No active bookings found.</p>
        <?php else: ?>
            <div class="table-responsive">
                <table>
                    <thead>
                        <tr>
                            <th>Class</th>
                            <th>Date & Time</th>
                            <th>Credits Used</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($bookings as $booking): ?>
                        <tr data-booking-id="<?= (int)$booking['id'] ?>">
                            <td><?= htmlspecialchars($booking['class_id']) ?></td>
                            <td><?= date('M j, Y g:ia', strtotime($booking['class_time'])) ?></td>
                            <td><?= (int)$booking['consumed_credits'] ?></td>
                            <td>
                                <span class="status-badge <?= $booking['status'] ?>">
                                    <?= ucfirst($booking['status']) ?>
                                </span>
                            </td>
                            <td>
                                <?php if ($booking['status'] === 'booked'): ?>
                                <button class="btn btn-cancel" onclick="cancelBooking(<?= (int)$booking['id'] ?>)">
                                    Cancel
                                </button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </section>

    <!-- Purchase Credits -->
    <section class="purchase-credits card">
        <h2>Purchase Credits</h2>
        <p class="info">Credits expire 1 month from purchase date.</p>
        
        <div class="bundles-grid">
            <?php foreach ($bundles as $bundle): ?>
            <div class="bundle-purchase-card">
                <div class="bundle-amount"><?= $bundle['credits'] ?> Credits</div>
                <div class="bundle-price">$<?= number_format($bundle['price_cents']/100, 2) ?></div>
                <button class="btn btn-purchase" onclick="purchaseCredits(<?= $bundle['credits'] ?>)">
                    Purchase
                </button>
            </div>
            <?php endforeach; ?>
        </div>
    </section>
</div>

<style>
.dashboard-content { padding: 24px; }
.dashboard-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; }
.credits-summary { font-size: 1.2rem; }
.credits-summary strong { color: var(--accent); }

.card { background: #fff; border-radius: 12px; padding: 24px; margin-bottom: 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }
.card h2 { margin: 0 0 16px; font-size: 1.4rem; }

.bundles-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 16px; }
.bundle-card { background: var(--card); padding: 16px; border-radius: 8px; text-align: center; border: 1px solid var(--border); }
.bundle-credits { font-size: 1.8rem; font-weight: 700; color: var(--accent); }
.bundle-expiry { font-size: 0.9rem; color: var(--muted); margin-top: 8px; }

.table-responsive { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; }
th, td { padding: 12px; text-align: left; border-bottom: 1px solid var(--border); }
th { font-weight: 600; color: var(--muted); }

.status-badge { padding: 4px 8px; border-radius: 4px; font-size: 0.9rem; }
.status-badge.booked { background: #e3f2fd; color: #1976d2; }
.status-badge.cancelled { background: #ffebee; color: #d32f2f; }

.bundle-purchase-card { background: var(--card); padding: 20px; border-radius: 8px; text-align: center; border: 1px solid var(--border); }
.bundle-amount { font-size: 1.4rem; font-weight: 600; margin-bottom: 8px; }
.bundle-price { color: var(--accent); font-weight: 600; margin-bottom: 12px; }
.btn-purchase { width: 100%; }

.no-bookings { color: var(--muted); text-align: center; padding: 24px; }

@media (max-width: 768px) {
    .dashboard-header { flex-direction: column; align-items: flex-start; gap: 12px; }
    .bundles-grid { grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); }
}
</style>

<script>
function cancelBooking(bookingId) {
    if (!confirm('Cancel this booking? Credits will be refunded.')) return;
    
    fetch('<?= \Tshen\url("/dashboard/cancel_booking.php") ?>', {
        method: 'POST',
        headers: { 
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({ booking_id: bookingId })
    })
    .then(r => r.json())
    .then(res => {
        alert(res.message || 'Booking cancelled');
        if (res.success) location.reload();
    })
    .catch(() => alert('Failed to cancel booking'));
}

function purchaseCredits(amount) {
    if (!confirm(`Purchase ${amount} credits?`)) return;
    
    fetch('<?= \Tshen\url("/dashboard/purchase_credits.php") ?>', {
        method: 'POST',
        headers: { 
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({ credits: amount })
    })
    .then(r => r.json())
    .then(res => {
        alert(res.message || 'Credits purchased');
        if (res.success) location.reload();
    })
    .catch(() => alert('Purchase failed'));
}
</script>