<?php
require_once __DIR__ . '/../api/lib.php';
hw_require_auth(['superadmin']);

$db = hw_db();
$message = '';
$error = '';

// Handle actions
if ($_POST) {
    $action = $_POST['action'] ?? '';
    $appointment_id = intval($_POST['appointment_id'] ?? 0);
    
    if ($action === 'update_status' && $appointment_id) {
        $status = $_POST['status'] ?? '';
        try {
            $stmt = $db->prepare("UPDATE appointments SET status = ? WHERE id = ?");
            $stmt->execute([$status, $appointment_id]);
            $message = "Appointment status updated successfully!";
        } catch (Exception $e) {
            $error = "Error updating appointment: " . $e->getMessage();
        }
    }
}

// Get appointments
$status_filter = $_GET['status'] ?? '';
$where_clause = $status_filter ? "WHERE a.status = ?" : "";
$params = $status_filter ? [$status_filter] : [];

$stmt = $db->prepare("
    SELECT a.*, 
           u.first_name as client_first_name, u.last_name as client_last_name, u.email as client_email,
           c.display_name as coach_name
    FROM appointments a
    JOIN users u ON a.user_id = u.id
    JOIN coaches c ON a.coach_id = c.id
    $where_clause
    ORDER BY a.starts_at DESC
");
$stmt->execute($params);
$appointments = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Appointments | Superadmin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body class="bg-gray-100">
    <div class="min-h-screen flex">
        <!-- Sidebar -->
        <div class="bg-emerald-800 text-white w-64 flex-shrink-0">
            <div class="p-6">
                <h1 class="text-xl font-bold">Superadmin Panel</h1>
            </div>
            <nav class="mt-6">
                <a href="/files/atasteofafricanmarketplace/superadmin/dashboard.php" class="flex items-center px-6 py-3 hover:bg-emerald-700 text-emerald-100">
                    <i class="fas fa-tachometer-alt mr-3"></i>Dashboard
                </a>
                <a href="/files/atasteofafricanmarketplace/superadmin/coaches.php" class="flex items-center px-6 py-3 hover:bg-emerald-700 text-emerald-100">
                    <i class="fas fa-users mr-3"></i>Manage Coaches
                </a>
                <a href="/files/atasteofafricanmarketplace/superadmin/coach-applications.php" class="flex items-center px-6 py-3 hover:bg-emerald-700 text-emerald-100">
                    <i class="fas fa-user-plus mr-3"></i>Coach Applications
                </a>
                <a href="/files/atasteofafricanmarketplace/superadmin/appointments.php" class="flex items-center px-6 py-3 bg-emerald-700 text-white">
                    <i class="fas fa-calendar mr-3"></i>Appointments
                </a>
                <a href="/files/atasteofafricanmarketplace/dashboard/admin/toa-wheel-management.php" class="flex items-center px-6 py-3 hover:bg-emerald-700 text-emerald-100">
                    <i class="fas fa-cog mr-3"></i>TOA Wheel
                </a>
            </nav>
        </div>
        
        <!-- Main Content -->
        <div class="flex-1 p-8">
            <div class="mb-8">
                <h2 class="text-3xl font-bold text-gray-900">Appointments Management</h2>
                <p class="text-gray-600 mt-2">View and manage all appointments</p>
            </div>
            
            <?php if ($message): ?>
                <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-6">
                    <?= htmlspecialchars($message) ?>
                </div>
            <?php endif; ?>
            
            <?php if ($error): ?>
                <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6">
                    <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>
            
            <!-- Filters -->
            <div class="mb-6 flex gap-4">
                <a href="/files/atasteofafricanmarketplace/superadmin/appointments.php" 
                   class="px-4 py-2 rounded <?= !$status_filter ? 'bg-emerald-600 text-white' : 'bg-gray-200 text-gray-700' ?>">
                    All
                </a>
                <a href="/files/atasteofafricanmarketplace/superadmin/appointments.php?status=scheduled" 
                   class="px-4 py-2 rounded <?= $status_filter === 'scheduled' ? 'bg-emerald-600 text-white' : 'bg-gray-200 text-gray-700' ?>">
                    Scheduled
                </a>
                <a href="/files/atasteofafricanmarketplace/superadmin/appointments.php?status=completed" 
                   class="px-4 py-2 rounded <?= $status_filter === 'completed' ? 'bg-emerald-600 text-white' : 'bg-gray-200 text-gray-700' ?>">
                    Completed
                </a>
                <a href="/files/atasteofafricanmarketplace/superadmin/appointments.php?status=cancelled" 
                   class="px-4 py-2 rounded <?= $status_filter === 'cancelled' ? 'bg-emerald-600 text-white' : 'bg-gray-200 text-gray-700' ?>">
                    Cancelled
                </a>
            </div>
            
            <!-- Appointments Table -->
            <div class="bg-white rounded-lg shadow overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="min-w-full">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Date & Time</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Client</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Coach</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Notes</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            <?php foreach ($appointments as $appointment): ?>
                                <tr>
                                    <td class="px-6 py-4">
                                        <div class="text-sm font-medium text-gray-900">
                                            <?= date('M j, Y', strtotime($appointment['starts_at'])) ?>
                                        </div>
                                        <div class="text-sm text-gray-500">
                                            <?= date('g:i A', strtotime($appointment['starts_at'])) ?>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="text-sm font-medium text-gray-900">
                                            <?= htmlspecialchars($appointment['client_first_name'] . ' ' . $appointment['client_last_name']) ?>
                                        </div>
                                        <div class="text-sm text-gray-500">
                                            <?= htmlspecialchars($appointment['client_email']) ?>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-900">
                                        <?= htmlspecialchars($appointment['coach_name']) ?>
                                    </td>
                                    <td class="px-6 py-4">
                                        <span class="px-2 py-1 text-xs font-semibold rounded-full
                                            <?= $appointment['status'] === 'scheduled' ? 'bg-blue-100 text-blue-800' : 
                                                ($appointment['status'] === 'completed' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800') ?>">
                                            <?= ucfirst($appointment['status']) ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-500 max-w-xs truncate">
                                        <?= htmlspecialchars($appointment['notes'] ?: 'No notes') ?>
                                    </td>
                                    <td class="px-6 py-4 text-sm font-medium">
                                        <form method="POST" class="inline-block">
                                            <input type="hidden" name="action" value="update_status">
                                            <input type="hidden" name="appointment_id" value="<?= $appointment['id'] ?>">
                                            <select name="status" onchange="this.form.submit()" class="text-sm border rounded px-2 py-1">
                                                <option value="scheduled" <?= $appointment['status'] === 'scheduled' ? 'selected' : '' ?>>Scheduled</option>
                                                <option value="completed" <?= $appointment['status'] === 'completed' ? 'selected' : '' ?>>Completed</option>
                                                <option value="cancelled" <?= $appointment['status'] === 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
                                            </select>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <?php if (empty($appointments)): ?>
                <div class="text-center py-12">
                    <i class="fas fa-calendar-times text-gray-400 text-6xl mb-4"></i>
                    <h3 class="text-lg font-medium text-gray-900 mb-2">No Appointments Found</h3>
                    <p class="text-gray-500">No appointments match the current filter.</p>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</body>
</html>