<?php
if (empty($_SESSION['user']) || $_SESSION['user']['role'] !== 'studio') {
    \Tshen\redirect('/login');
}

// Fetch studio's classes
$stmt = $db->prepare('
    SELECT c.*, 
           COUNT(b.id) as booked_slots,
           c.capacity - COUNT(b.id) as available_slots
    FROM classes c
    LEFT JOIN bookings b ON c.id = b.class_id AND b.status = "booked"
    WHERE c.studio_id = ?
    GROUP BY c.id
    ORDER BY c.class_time DESC
');
$stmt->execute([$_SESSION['user']['studio_id']]);
$classes = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="studio-dashboard">
    <header class="dashboard-header">
        <h1>Studio Dashboard</h1>
        <a href="<?= \Tshen\url('/studio/class/new') ?>" class="btn-primary">Add New Class</a>
    </header>

    <div class="dashboard-grid">
        <!-- Quick Stats -->
        <div class="stats-card">
            <h3>Classes Overview</h3>
            <div class="stats-grid">
                <div class="stat">
                    <div class="stat-value"><?= count($classes) ?></div>
                    <div class="stat-label">Total Classes</div>
                </div>
                <div class="stat">
                    <div class="stat-value">
                        <?php
                        $totalBookings = 0;
                        foreach ($classes as $class) {
                            $totalBookings += (int)$class['booked_slots'];
                        }
                        echo $totalBookings;
                        ?>
                    </div>
                    <div class="stat-label">Total Bookings</div>
                </div>
            </div>
        </div>

        <!-- Class Listings Table -->
        <div class="content-card">
            <h2>Class Listings</h2>
            <div class="table-responsive">
                <table class="classes-table">
                    <thead>
                        <tr>
                            <th>Class Name</th>
                            <th>Date & Time</th>
                            <th>Capacity</th>
                            <th>Booked</th>
                            <th>Available</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($classes as $class): ?>
                        <tr data-class-id="<?= (int)$class['id'] ?>">
                            <td><?= htmlspecialchars($class['name']) ?></td>
                            <td><?= date('M j, Y g:ia', strtotime($class['class_time'])) ?></td>
                            <td><?= (int)$class['capacity'] ?></td>
                            <td><?= (int)$class['booked_slots'] ?></td>
                            <td><?= (int)$class['available_slots'] ?></td>
                            <td>
                                <select class="status-select" onchange="updateClassStatus(<?= (int)$class['id'] ?>, this.value)">
                                    <option value="active" <?= $class['status'] === 'active' ? 'selected' : '' ?>>Active</option>
                                    <option value="cancelled" <?= $class['status'] === 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
                                    <option value="full" <?= $class['status'] === 'full' ? 'selected' : '' ?>>Full</option>
                                </select>
                            </td>
                            <td class="actions">
                                <button onclick="viewBookings(<?= (int)$class['id'] ?>)" class="btn-view">View Bookings</button>
                                <button onclick="editClass(<?= (int)$class['id'] ?>)" class="btn-edit">Edit</button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<style>
.studio-dashboard {
    padding: 24px;
    max-width: 1400px;
    margin: 0 auto;
}

.dashboard-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
}

.btn-primary {
    background: var(--accent);
    color: white;
    padding: 10px 20px;
    border-radius: 6px;
    text-decoration: none;
}

.dashboard-grid {
    display: grid;
    gap: 24px;
}

.stats-card {
    background: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 20px;
    margin-top: 16px;
}

.stat {
    text-align: center;
}

.stat-value {
    font-size: 2rem;
    font-weight: 700;
    color: var(--accent);
}

.stat-label {
    color: var(--muted);
    margin-top: 4px;
}

.content-card {
    background: white;
    border-radius: 12px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.table-responsive {
    overflow-x: auto;
}

.classes-table {
    width: 100%;
    border-collapse: collapse;
}

.classes-table th,
.classes-table td {
    padding: 12px;
    text-align: left;
    border-bottom: 1px solid var(--border);
}

.status-select {
    padding: 6px;
    border-radius: 4px;
    border: 1px solid var(--border);
}

.actions {
    display: flex;
    gap: 8px;
}

.btn-view,
.btn-edit {
    padding: 6px 12px;
    border-radius: 4px;
    border: none;
    cursor: pointer;
}

.btn-view {
    background: #e3f2fd;
    color: #1976d2;
}

.btn-edit {
    background: #f5f5f5;
    color: #333;
}

@media (max-width: 768px) {
    .actions {
        flex-direction: column;
    }
}
</style>

<script>
function updateClassStatus(classId, status) {
    if (!confirm('Update class status?')) {
        // Reset select to previous value if cancelled
        location.reload();
        return;
    }

    fetch('<?= \Tshen\url('/studio/update-status.php') ?>', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({ class_id: classId, status: status })
    })
    .then(r => r.json())
    .then(res => {
        if (res.success) {
            location.reload();
        } else {
            alert(res.message || 'Update failed');
            location.reload();
        }
    })
    .catch(() => {
        alert('Update failed');
        location.reload();
    });
}

function viewBookings(classId) {
    window.location.href = '<?= \Tshen\url('/studio/bookings') ?>/' + classId;
}

function editClass(classId) {
    window.location.href = '<?= \Tshen\url('/studio/class/edit') ?>/' + classId;
}
</script>