<?php
declare(strict_types=1);
require_once __DIR__ . '/../../api/lib.php';

hw_require_auth(['admin']);

// Get search/filter parameters
$search = hw_sanitize_string($_GET['search'] ?? '');
$status = hw_sanitize_string($_GET['status'] ?? '');
$dateFrom = hw_sanitize_string($_GET['date_from'] ?? '');
$dateTo = hw_sanitize_string($_GET['date_to'] ?? '');
$coachFilter = hw_sanitize_string($_GET['coach'] ?? '');
$limit = 50;
$offset = (int)($_GET['page'] ?? 0) * $limit;

try {
    $pdo = hw_db();
    
    // Get all coaches for filter dropdown
    $coachesStmt = $pdo->query('SELECT id, display_name FROM coaches ORDER BY display_name');
    $allCoaches = $coachesStmt->fetchAll();

    // Get bookings with customer, coach info
    $query = 'SELECT a.id, a.starts_at, a.ends_at, a.status, a.notes, a.created_at,
                     u.first_name, u.last_name, u.email, u.phone,
                     c.display_name, c.hourly_rate,
                     TIMESTAMPDIFF(MINUTE, a.starts_at, a.ends_at) as duration_minutes
              FROM appointments a 
              JOIN users u ON a.user_id = u.id 
              JOIN coaches c ON a.coach_id = c.id 
              WHERE 1=1';
    
    if ($search) {
        $query .= ' AND (CONCAT(u.first_name, " ", u.last_name) LIKE ? OR c.display_name LIKE ? OR u.email LIKE ?)';
    }
    
    if ($status) {
        $query .= ' AND a.status = ?';
    }
    
    if ($dateFrom) {
        $query .= ' AND DATE(a.starts_at) >= ?';
    }
    
    if ($dateTo) {
        $query .= ' AND DATE(a.starts_at) <= ?';
    }
    
    if ($coachFilter) {
        $query .= ' AND a.coach_id = ?';
    }
    
    $query .= ' ORDER BY a.starts_at DESC LIMIT ? OFFSET ?';
    
    $stmt = $pdo->prepare($query);
    $params = [];
    if ($search) {
        $searchTerm = "%$search%";
        $params[] = $searchTerm;
        $params[] = $searchTerm;
        $params[] = $searchTerm;
    }
    if ($status) {
        $params[] = $status;
    }
    if ($dateFrom) {
        $params[] = $dateFrom;
    }
    if ($dateTo) {
        $params[] = $dateTo;
    }
    if ($coachFilter) {
        $params[] = $coachFilter;
    }
    $params[] = $limit;
    $params[] = $offset;
    $stmt->execute($params);
    $bookings = $stmt->fetchAll();
    
    // Calculate charges for each booking
    foreach ($bookings as &$booking) {
        $durationHours = ($booking['duration_minutes'] ?? 60) / 60;
        $hourlyRate = (float)($booking['hourly_rate'] ?? 0);
        $booking['charge_amount'] = $durationHours * $hourlyRate;
    }

    // Count total
    $countQuery = 'SELECT COUNT(*) as count FROM appointments a JOIN users u ON a.user_id = u.id JOIN coaches c ON a.coach_id = c.id WHERE 1=1';
    if ($search) {
        $countQuery .= ' AND (CONCAT(u.first_name, " ", u.last_name) LIKE ? OR c.display_name LIKE ? OR u.email LIKE ?)';
    }
    if ($status) {
        $countQuery .= ' AND a.status = ?';
    }
    if ($dateFrom) {
        $countQuery .= ' AND DATE(a.starts_at) >= ?';
    }
    if ($dateTo) {
        $countQuery .= ' AND DATE(a.starts_at) <= ?';
    }
    if ($coachFilter) {
        $countQuery .= ' AND a.coach_id = ?';
    }
    
    $countStmt = $pdo->prepare($countQuery);
    $countParams = [];
    if ($search) {
        $searchTerm = "%$search%";
        $countParams[] = $searchTerm;
        $countParams[] = $searchTerm;
        $countParams[] = $searchTerm;
    }
    if ($status) {
        $countParams[] = $status;
    }
    if ($dateFrom) {
        $countParams[] = $dateFrom;
    }
    if ($dateTo) {
        $countParams[] = $dateTo;
    }
    if ($coachFilter) {
        $countParams[] = $coachFilter;
    }
    $countStmt->execute($countParams);
    $totalCount = (int)($countStmt->fetch()['count'] ?? 0);
    $totalPages = ceil($totalCount / $limit);
    
    // Get summary statistics
    $statsQuery = 'SELECT 
                    COUNT(*) as total_bookings,
                    COUNT(CASE WHEN status = "scheduled" THEN 1 END) as scheduled,
                    COUNT(CASE WHEN status = "completed" THEN 1 END) as completed,
                    COUNT(CASE WHEN status = "cancelled" THEN 1 END) as cancelled,
                    SUM(TIMESTAMPDIFF(MINUTE, starts_at, ends_at) / 60 * c.hourly_rate) as total_revenue
                   FROM appointments a 
                   JOIN coaches c ON a.coach_id = c.id';
    $statsStmt = $pdo->query($statsQuery);
    $summaryStats = $statsStmt->fetch();
} catch (Exception $e) {
    $bookings = [];
    $totalPages = 0;
    $summaryStats = [
        'total_bookings' => 0,
        'scheduled' => 0,
        'completed' => 0,
        'cancelled' => 0,
        'total_revenue' => 0
    ];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bookings - Herbal Wellness Admin</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">
    <link href='https://cdn.jsdelivr.net/npm/fullcalendar@6.1.10/index.global.min.css' rel='stylesheet' />
    <script src='https://cdn.jsdelivr.net/npm/fullcalendar@6.1.10/index.global.min.js'></script>
    <style>
        .fc {
            font-family: inherit;
        }
        .fc-toolbar-title {
            font-size: 1.5rem !important;
            font-weight: bold !important;
        }
        .fc-button {
            background: #059669 !important;
            border-color: #059669 !important;
        }
        .fc-button:hover {
            background: #047857 !important;
        }
        .fc-button-active {
            background: #047857 !important;
        }
        .fc-event {
            cursor: pointer;
        }
        .fc-event-scheduled {
            background: #3b82f6 !important;
            border-color: #3b82f6 !important;
        }
        .fc-event-completed {
            background: #10b981 !important;
            border-color: #10b981 !important;
        }
        .fc-event-cancelled {
            background: #ef4444 !important;
            border-color: #ef4444 !important;
        }
    </style>
</head>
<body class="bg-gray-50">
    <div class="flex h-screen bg-gray-100">
        <!-- Sidebar Navigation -->
        <aside class="w-64 bg-gradient-to-b from-emerald-900 to-emerald-800 text-white shadow-lg overflow-y-auto">
            <!-- Logo/Brand -->
            <div class="p-6 border-b border-emerald-700">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 bg-emerald-300 rounded-lg flex items-center justify-center">
                        <i class="fas fa-leaf text-emerald-900 text-lg"></i>
                    </div>
                    <div>
                        <h1 class="font-bold text-lg">Herbal Admin</h1>
                        <p class="text-emerald-200 text-xs">Management Portal</p>
                    </div>
                </div>
            </div>

            <!-- Navigation Menu -->
            <nav class="p-4 space-y-2">
                <!-- Dashboard Home -->
                <a href="/files/atasteofafricanmarketplace/dashboard/admin/" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-home w-5"></i>
                    <span class="font-medium">Dashboard</span>
                </a>

                <!-- CATEGORY: BUSINESS OPERATIONS -->
                <div class="pt-4 pb-2">
                    <p class="px-4 text-xs font-bold text-emerald-300 uppercase tracking-wider">Business</p>
                </div>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/sales.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-shopping-cart w-5"></i>
                    <span>Sales & Orders</span>
                </a>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/bookings.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors bg-emerald-700 text-white">
                    <i class="fas fa-calendar-check w-5"></i>
                    <span>Booking Calendar</span>
                </a>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/coaches.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-user-md w-5"></i>
                    <span>Coaches</span>
                </a>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/products.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-boxes w-5"></i>
                    <span>Products</span>
                </a>

                <!-- CATEGORY: CUSTOMERS -->
                <div class="pt-4 pb-2">
                    <p class="px-4 text-xs font-bold text-emerald-300 uppercase tracking-wider">Customers</p>
                </div>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/customers.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-users w-5"></i>
                    <span>All Customers</span>
                </a>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/contacts.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-address-book w-5"></i>
                    <span>Contacts & Leads</span>
                </a>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/loyalty.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-gift w-5"></i>
                    <span>Loyalty Program</span>
                </a>

                <!-- CATEGORY: INSIGHTS -->
                <div class="pt-4 pb-2">
                    <p class="px-4 text-xs font-bold text-emerald-300 uppercase tracking-wider">Insights</p>
                </div>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/analytics.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-chart-line w-5"></i>
                    <span>Analytics</span>
                </a>

                <!-- CATEGORY: AUTOMATION & TOOLS -->
                <div class="pt-4 pb-2">
                    <p class="px-4 text-xs font-bold text-emerald-300 uppercase tracking-wider">Tools</p>
                </div>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/automations.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-robot w-5"></i>
                    <span>Automations</span>
                </a>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/cms.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-file-alt w-5"></i>
                    <span>Content Manager</span>
                </a>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/developers.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-code w-5"></i>
                    <span>Developer Tools</span>
                </a>

                <!-- CATEGORY: SETTINGS -->
                <div class="pt-4 pb-2">
                    <p class="px-4 text-xs font-bold text-emerald-300 uppercase tracking-wider">System</p>
                </div>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/settings.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-cog w-5"></i>
                    <span>Settings</span>
                </a>
            </nav>
        </aside>

        <!-- Main Content -->
        <div class="flex-1 flex flex-col overflow-hidden">
            <header class="bg-white border-b border-gray-200 px-8 py-4 shadow-sm">
                <h1 class="text-2xl font-bold text-gray-900">Booking Calendar</h1>
            </header>

            <main class="flex-1 overflow-auto p-8">
                <!-- View Toggle & Quick Actions -->
                <div class="flex items-center justify-between mb-6">
                    <div class="flex gap-2">
                        <button onclick="switchView('list')" id="btn-list" class="px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors">
                            <i class="fas fa-list mr-2"></i>List View
                        </button>
                        <button onclick="switchView('calendar')" id="btn-calendar" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors">
                            <i class="fas fa-calendar mr-2"></i>Calendar View
                        </button>
                    </div>
                    <div class="flex gap-2">
                        <button onclick="openNewBookingModal()" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                            <i class="fas fa-plus mr-2"></i>New Booking
                        </button>
                        <button onclick="exportBookings()" class="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors">
                            <i class="fas fa-file-excel mr-2"></i>Export
                        </button>
                    </div>
                </div>

                <!-- Summary Stats -->
                <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
                    <div class="bg-white rounded-lg shadow p-6">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm text-gray-600 font-medium">Total Bookings</p>
                                <p class="text-3xl font-bold text-gray-900 mt-2"><?php echo number_format($summaryStats['total_bookings'] ?? 0); ?></p>
                            </div>
                            <div class="w-12 h-12 bg-emerald-100 rounded-lg flex items-center justify-center">
                                <i class="fas fa-calendar-check text-emerald-600 text-xl"></i>
                            </div>
                        </div>
                    </div>
                    <div class="bg-white rounded-lg shadow p-6">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm text-gray-600 font-medium">Scheduled</p>
                                <p class="text-3xl font-bold text-blue-900 mt-2"><?php echo number_format($summaryStats['scheduled'] ?? 0); ?></p>
                            </div>
                            <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                                <i class="fas fa-clock text-blue-600 text-xl"></i>
                            </div>
                        </div>
                    </div>
                    <div class="bg-white rounded-lg shadow p-6">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm text-gray-600 font-medium">Completed</p>
                                <p class="text-3xl font-bold text-emerald-900 mt-2"><?php echo number_format($summaryStats['completed'] ?? 0); ?></p>
                            </div>
                            <div class="w-12 h-12 bg-emerald-100 rounded-lg flex items-center justify-center">
                                <i class="fas fa-check-circle text-emerald-600 text-xl"></i>
                            </div>
                        </div>
                    </div>
                    <div class="bg-white rounded-lg shadow p-6">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm text-gray-600 font-medium">Revenue</p>
                                <p class="text-3xl font-bold text-purple-900 mt-2">$<?php echo number_format($summaryStats['total_revenue'] ?? 0, 2); ?></p>
                            </div>
                            <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                                <i class="fas fa-dollar-sign text-purple-600 text-xl"></i>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Calendar View (Hidden by default) -->
                <div id="calendar-view" class="hidden bg-white rounded-lg shadow p-6 mb-6">
                    <div id="calendar"></div>
                </div>

                <!-- List View -->
                <div id="list-view">
                    <!-- Filters -->
                    <div class="bg-white rounded-lg shadow p-6 mb-6">
                        <h3 class="font-semibold text-gray-900 mb-4">Filters</h3>
                        <form method="GET" action="bookings.php" class="grid grid-cols-1 md:grid-cols-6 gap-4">
                            <div class="md:col-span-2">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Search</label>
                                <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" 
                                       placeholder="Client name or email..." 
                                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-500">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Coach</label>
                                <select name="coach" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-500">
                                    <option value="">All Coaches</option>
                                    <?php foreach ($allCoaches as $coach): ?>
                                    <option value="<?php echo $coach['id']; ?>" <?php echo $coachFilter == $coach['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($coach['display_name']); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Status</label>
                                <select name="status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-500">
                                    <option value="">All Status</option>
                                    <option value="scheduled" <?php echo $status === 'scheduled' ? 'selected' : ''; ?>>Scheduled</option>
                                    <option value="completed" <?php echo $status === 'completed' ? 'selected' : ''; ?>>Completed</option>
                                    <option value="cancelled" <?php echo $status === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">From Date</label>
                                <input type="date" name="date_from" value="<?php echo htmlspecialchars($dateFrom); ?>" 
                                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-500">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">To Date</label>
                                <input type="date" name="date_to" value="<?php echo htmlspecialchars($dateTo); ?>" 
                                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-500">
                            </div>
                            <div class="md:col-span-6 flex gap-2">
                                <button type="submit" class="px-6 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors">
                                    <i class="fas fa-filter mr-2"></i>Apply Filters
                                </button>
                                <a href="bookings.php" class="px-6 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors">
                                    <i class="fas fa-times mr-2"></i>Clear
                                </a>
                                <div class="ml-auto flex gap-2">
                                    <button type="button" onclick="setQuickFilter('today')" class="px-4 py-2 bg-blue-100 text-blue-700 rounded-lg hover:bg-blue-200 transition-colors text-sm">
                                        Today
                                    </button>
                                    <button type="button" onclick="setQuickFilter('week')" class="px-4 py-2 bg-blue-100 text-blue-700 rounded-lg hover:bg-blue-200 transition-colors text-sm">
                                        This Week
                                    </button>
                                    <button type="button" onclick="setQuickFilter('month')" class="px-4 py-2 bg-blue-100 text-blue-700 rounded-lg hover:bg-blue-200 transition-colors text-sm">
                                        This Month
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Bookings Table -->
                    <div class="bg-white rounded-lg shadow overflow-hidden">
                        <table class="w-full">
                            <thead class="bg-gray-50 border-b border-gray-200">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase">Client</th>
                                    <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase">Coach</th>
                                    <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase">Date & Time</th>
                                    <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase">Duration</th>
                                    <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase">Amount</th>
                                    <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase">Status</th>
                                    <th class="px-6 py-3 text-right text-xs font-semibold text-gray-700 uppercase">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-200">
                                <?php if (!empty($bookings)): ?>
                                    <?php foreach ($bookings as $booking): ?>
                                    <tr class="hover:bg-gray-50 transition-colors">
                                        <td class="px-6 py-4 text-sm">
                                            <div>
                                                <p class="font-medium text-gray-900"><?php echo htmlspecialchars($booking['first_name'] . ' ' . $booking['last_name']); ?></p>
                                                <p class="text-gray-500 text-xs"><?php echo htmlspecialchars($booking['email']); ?></p>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 text-sm">
                                            <div>
                                                <p class="font-medium text-gray-900"><?php echo htmlspecialchars($booking['display_name']); ?></p>
                                                <p class="text-gray-600 text-xs">$<?php echo number_format($booking['hourly_rate'], 2); ?>/hr</p>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 text-sm">
                                            <div>
                                                <p class="font-medium text-gray-900"><?php echo (new DateTime($booking['starts_at']))->format('M d, Y'); ?></p>
                                                <p class="text-gray-600 text-xs"><?php echo (new DateTime($booking['starts_at']))->format('h:i A'); ?> - <?php echo (new DateTime($booking['ends_at']))->format('h:i A'); ?></p>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 text-sm text-gray-900">
                                            <span class="inline-flex items-center">
                                                <i class="fas fa-clock text-gray-400 mr-1"></i>
                                                <?php echo ($booking['duration_minutes'] ?? 60); ?> min
                                            </span>
                                        </td>
                                        <td class="px-6 py-4 text-sm font-semibold text-gray-900">
                                            $<?php echo number_format($booking['charge_amount'], 2); ?>
                                        </td>
                                        <td class="px-6 py-4 text-sm">
                                            <select onchange="updateStatus(<?php echo $booking['id']; ?>, this.value)" class="inline-block px-3 py-1 bg-<?php 
                                                $statusColor = match($booking['status']) {
                                                    'scheduled' => 'blue',
                                                    'completed' => 'emerald',
                                                    'cancelled' => 'red',
                                                    default => 'gray'
                                                };
                                                echo $statusColor;
                                            ?>-100 text-<?php echo $statusColor; ?>-700 text-xs font-semibold rounded-full border-0 cursor-pointer">
                                                <option value="scheduled" <?php echo $booking['status'] === 'scheduled' ? 'selected' : ''; ?>>Scheduled</option>
                                                <option value="completed" <?php echo $booking['status'] === 'completed' ? 'selected' : ''; ?>>Completed</option>
                                                <option value="cancelled" <?php echo $booking['status'] === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                                            </select>
                                        </td>
                                        <td class="px-6 py-4 text-right text-sm">
                                            <button onclick="viewBooking(<?php echo $booking['id']; ?>)" class="text-emerald-600 hover:text-emerald-700 font-medium">View</button>
                                            <span class="text-gray-300 mx-2">•</span>
                                            <button onclick="editBooking(<?php echo $booking['id']; ?>)" class="text-blue-600 hover:text-blue-700 font-medium">Edit</button>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                <tr>
                                    <td colspan="7" class="px-6 py-8 text-center text-gray-600">
                                        <i class="fas fa-calendar text-4xl text-gray-300 mb-4 block"></i>
                                        No bookings found
                                    </td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <?php if ($totalPages > 1): ?>
                    <div class="mt-6 flex items-center justify-between">
                        <p class="text-sm text-gray-600">Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $limit, $totalCount); ?> of <?php echo $totalCount; ?> bookings</p>
                    </div>
                    <?php endif; ?>
                </div>
            </main>
        </div>
    </div>

    <!-- New Booking Modal -->
    <div id="new-booking-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
        <div class="bg-white rounded-lg shadow-xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto">
            <div class="p-6 border-b border-gray-200">
                <div class="flex items-center justify-between">
                    <h2 class="text-xl font-bold text-gray-900">New Booking</h2>
                    <button onclick="closeNewBookingModal()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
            </div>
            <form id="new-booking-form" class="p-6 space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Client</label>
                        <select id="client-select" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-500">
                            <option value="">Select a client...</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Coach</label>
                        <select id="coach-select" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-500">
                            <option value="">Select a coach...</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Date</label>
                        <input type="date" id="booking-date" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Start Time</label>
                        <input type="time" id="booking-time" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Duration (minutes)</label>
                        <select id="booking-duration" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-500">
                            <option value="30">30 minutes</option>
                            <option value="60" selected>1 hour</option>
                            <option value="90">1.5 hours</option>
                            <option value="120">2 hours</option>
                        </select>
                    </div>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Notes (optional)</label>
                    <textarea id="booking-notes" rows="3" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-500" placeholder="Add any special notes or requirements..."></textarea>
                </div>
                <div class="flex gap-2 justify-end pt-4">
                    <button type="button" onclick="closeNewBookingModal()" class="px-6 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors">
                        Cancel
                    </button>
                    <button type="submit" class="px-6 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors">
                        <i class="fas fa-check mr-2"></i>Create Booking
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
    let calendar;
    let currentView = 'list';

    // View switching
    function switchView(view) {
        currentView = view;
        if (view === 'calendar') {
            document.getElementById('list-view').classList.add('hidden');
            document.getElementById('calendar-view').classList.remove('hidden');
            document.getElementById('btn-list').classList.remove('bg-emerald-600', 'text-white');
            document.getElementById('btn-list').classList.add('bg-gray-200', 'text-gray-700');
            document.getElementById('btn-calendar').classList.add('bg-emerald-600', 'text-white');
            document.getElementById('btn-calendar').classList.remove('bg-gray-200', 'text-gray-700');
            
            if (!calendar) {
                initCalendar();
            }
        } else {
            document.getElementById('list-view').classList.remove('hidden');
            document.getElementById('calendar-view').classList.add('hidden');
            document.getElementById('btn-list').classList.add('bg-emerald-600', 'text-white');
            document.getElementById('btn-list').classList.remove('bg-gray-200', 'text-gray-700');
            document.getElementById('btn-calendar').classList.remove('bg-emerald-600', 'text-white');
            document.getElementById('btn-calendar').classList.add('bg-gray-200', 'text-gray-700');
        }
    }

    // Initialize FullCalendar
    function initCalendar() {
        const calendarEl = document.getElementById('calendar');
        calendar = new FullCalendar.Calendar(calendarEl, {
            initialView: 'dayGridMonth',
            headerToolbar: {
                left: 'prev,next today',
                center: 'title',
                right: 'dayGridMonth,timeGridWeek,timeGridDay'
            },
            events: function(info, successCallback, failureCallback) {
                fetch('api_bookings.php?action=list')
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            successCallback(data.events);
                        } else {
                            failureCallback(data.message);
                        }
                    })
                    .catch(error => failureCallback(error));
            },
            eventClick: function(info) {
                viewBooking(info.event.id);
            },
            selectable: true,
            select: function(info) {
                openNewBookingModal(info.startStr);
            }
        });
        calendar.render();
    }

    // Quick filter dates
    function setQuickFilter(period) {
        const today = new Date();
        let fromDate, toDate;
        
        switch(period) {
            case 'today':
                fromDate = toDate = today.toISOString().split('T')[0];
                break;
            case 'week':
                const weekStart = new Date(today);
                weekStart.setDate(today.getDate() - today.getDay());
                const weekEnd = new Date(weekStart);
                weekEnd.setDate(weekStart.getDate() + 6);
                fromDate = weekStart.toISOString().split('T')[0];
                toDate = weekEnd.toISOString().split('T')[0];
                break;
            case 'month':
                fromDate = new Date(today.getFullYear(), today.getMonth(), 1).toISOString().split('T')[0];
                toDate = new Date(today.getFullYear(), today.getMonth() + 1, 0).toISOString().split('T')[0];
                break;
        }
        
        const form = document.querySelector('form[action="bookings.php"]');
        form.querySelector('[name="date_from"]').value = fromDate;
        form.querySelector('[name="date_to"]').value = toDate;
        form.submit();
    }

    // Modal functions
    function openNewBookingModal(date) {
        const modal = document.getElementById('new-booking-modal');
        modal.classList.remove('hidden');
        
        // Load clients and coaches
        loadClients();
        loadCoaches();
        
        // Set date if provided
        if (date) {
            document.getElementById('booking-date').value = date.split('T')[0];
        }
    }

    function closeNewBookingModal() {
        document.getElementById('new-booking-modal').classList.add('hidden');
        document.getElementById('new-booking-form').reset();
    }

    // Load data for dropdowns
    async function loadClients() {
        const response = await fetch('api_bookings.php?action=get_clients');
        const data = await response.json();
        if (data.success) {
            const select = document.getElementById('client-select');
            select.innerHTML = '<option value="">Select a client...</option>';
            data.clients.forEach(client => {
                const option = document.createElement('option');
                option.value = client.id;
                option.textContent = `${client.name} (${client.email})`;
                select.appendChild(option);
            });
        }
    }

    async function loadCoaches() {
        const response = await fetch('api_bookings.php?action=get_coaches');
        const data = await response.json();
        if (data.success) {
            const select = document.getElementById('coach-select');
            select.innerHTML = '<option value="">Select a coach...</option>';
            data.coaches.forEach(coach => {
                const option = document.createElement('option');
                option.value = coach.id;
                option.textContent = `${coach.display_name} ($${coach.hourly_rate}/hr)`;
                select.appendChild(option);
            });
        }
    }

    // Handle new booking form submission
    document.getElementById('new-booking-form').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const date = document.getElementById('booking-date').value;
        const time = document.getElementById('booking-time').value;
        const duration = parseInt(document.getElementById('booking-duration').value);
        
        const startsAt = `${date} ${time}:00`;
        const endsAt = new Date(new Date(startsAt).getTime() + duration * 60000).toISOString().slice(0, 19).replace('T', ' ');
        
        const bookingData = {
            user_id: document.getElementById('client-select').value,
            coach_id: document.getElementById('coach-select').value,
            starts_at: startsAt,
            ends_at: endsAt
        };
        
        try {
            const response = await fetch('api_bookings.php?action=create', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(bookingData)
            });
            
            const data = await response.json();
            
            if (data.success) {
                alert('Booking created successfully!');
                closeNewBookingModal();
                location.reload();
            } else {
                alert('Error: ' + data.message);
            }
        } catch (error) {
            alert('Error creating booking: ' + error.message);
        }
    });

    // Update booking status
    async function updateStatus(bookingId, newStatus) {
        try {
            const response = await fetch('api_bookings.php?action=update_status', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ id: bookingId, status: newStatus })
            });
            
            const data = await response.json();
            
            if (data.success) {
                // Show success message
                const toast = document.createElement('div');
                toast.className = 'fixed top-4 right-4 bg-emerald-600 text-white px-6 py-3 rounded-lg shadow-lg z-50';
                toast.textContent = 'Status updated successfully!';
                document.body.appendChild(toast);
                setTimeout(() => toast.remove(), 3000);
                
                // Refresh calendar if visible
                if (calendar && currentView === 'calendar') {
                    calendar.refetchEvents();
                }
            } else {
                alert('Error: ' + data.message);
            }
        } catch (error) {
            alert('Error updating status: ' + error.message);
        }
    }

    // View/Edit functions (placeholder)
    function viewBooking(id) {
        alert('View booking #' + id + ' (feature coming soon)');
    }

    function editBooking(id) {
        alert('Edit booking #' + id + ' (feature coming soon)');
    }

    // Export bookings
    function exportBookings() {
        alert('Export feature coming soon!');
    }

    // Sidebar toggle
    function toggleCatalog(event) {
        event.preventDefault();
        const submenu = document.getElementById('catalog-submenu');
        const chevron = document.getElementById('catalog-chevron');
        
        if (submenu.classList.contains('hidden')) {
            submenu.classList.remove('hidden');
            chevron.classList.remove('fa-chevron-down');
            chevron.classList.add('fa-chevron-up');
        } else {
            submenu.classList.add('hidden');
            chevron.classList.remove('fa-chevron-up');
            chevron.classList.add('fa-chevron-down');
        }
    }
    </script>
</body>
</html>
