<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check permissions
$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'RECEPTIONIST', 'ENT_DOCTOR', 'ENT_CONSULTANT'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$errors = [];
$success_message = '';

// Fetch active ENT doctors
$doctors_sql = "SELECT d.doctor_id, u.full_name, d.specialization, d.consultation_fee, d.appointment_duration 
                FROM doctors d 
                JOIN users u ON d.user_id = u.user_id 
                WHERE d.is_active = 1 AND u.status = 'ACTIVE' 
                ORDER BY u.full_name";
$doctors_result = $conn->query($doctors_sql);

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $patient_search = trim($_POST['patient_search'] ?? '');
    $patient_id = $_POST['patient_id'] ?? '';
    $doctor_id = $_POST['doctor_id'] ?? '';
    $appointment_date = $_POST['appointment_date'] ?? '';
    $appointment_time = $_POST['appointment_time'] ?? '';
    $appointment_type = $_POST['appointment_type'] ?? 'CONSULTATION';
    $chief_complaint = trim($_POST['chief_complaint'] ?? '');
    $special_requirements = trim($_POST['special_requirements'] ?? '');
    $booking_source = 'STAFF'; // Since it's booked by staff
    
    // Validation
    if (empty($patient_id)) {
        $errors[] = "Please select a patient";
    }
    
    if (empty($doctor_id)) {
        $errors[] = "Please select a doctor";
    }
    
    if (empty($appointment_date)) {
        $errors[] = "Appointment date is required";
    } else {
        $selected_date = new DateTime($appointment_date);
        $today = new DateTime();
        
        if ($selected_date < $today->setTime(0, 0, 0)) {
            $errors[] = "Appointment date cannot be in the past";
        }
        
        // Check if date is more than 30 days in advance
        $max_advance_date = $today->add(new DateInterval('P30D'));
        if ($selected_date > $max_advance_date) {
            $errors[] = "Appointments can only be booked up to 30 days in advance";
        }
    }
    
    if (empty($appointment_time)) {
        $errors[] = "Appointment time is required";
    }
    
    if (empty($chief_complaint)) {
        $errors[] = "Chief complaint is required";
    }
    
    // Check for conflicts if no errors so far
    if (empty($errors)) {
        // Check if doctor is available at this time
        $conflict_sql = "SELECT appointment_id FROM appointments 
                        WHERE doctor_id = ? AND appointment_date = ? AND appointment_time = ? 
                        AND status NOT IN ('CANCELLED', 'NO_SHOW')";
        $stmt = $conn->prepare($conflict_sql);
        $stmt->bind_param("iss", $doctor_id, $appointment_date, $appointment_time);
        $stmt->execute();
        
        if ($stmt->get_result()->num_rows > 0) {
            $errors[] = "Doctor is not available at this time. Please select a different time.";
        }
        
        // Check if patient already has appointment on the same day
        $patient_conflict_sql = "SELECT appointment_id FROM appointments 
                                WHERE patient_id = ? AND appointment_date = ? 
                                AND status NOT IN ('CANCELLED', 'NO_SHOW')";
        $stmt = $conn->prepare($patient_conflict_sql);
        $stmt->bind_param("is", $patient_id, $appointment_date);
        $stmt->execute();
        
        if ($stmt->get_result()->num_rows > 0) {
            $errors[] = "Patient already has an appointment on this date.";
        }
    }
    
    // If no errors, create the appointment
    if (empty($errors)) {
        try {
            $conn->begin_transaction();
            
            // Generate appointment number
            $appointment_number = 'APT' . date('Ymd') . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
            
            // Get doctor details for duration
            $doctor_details_sql = "SELECT appointment_duration FROM doctors WHERE doctor_id = ?";
            $stmt = $conn->prepare($doctor_details_sql);
            $stmt->bind_param("i", $doctor_id);
            $stmt->execute();
            $doctor_details = $stmt->get_result()->fetch_assoc();
            $estimated_duration = $doctor_details['appointment_duration'] ?? 30;
            
            // Insert appointment
            $appointment_sql = "INSERT INTO appointments (appointment_number, patient_id, doctor_id, 
                               appointment_date, appointment_time, appointment_type, booking_source, 
                               chief_complaint, special_requirements, estimated_duration, status, created_at) 
                               VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'SCHEDULED', NOW())";
            
            $stmt = $conn->prepare($appointment_sql);
            $stmt->bind_param("siisssssi", 
                $appointment_number, $patient_id, $doctor_id, $appointment_date, 
                $appointment_time, $appointment_type, $booking_source, 
                $chief_complaint, $special_requirements, $estimated_duration
            );
            
            if (!$stmt->execute()) {
                throw new Exception("Failed to create appointment");
            }
            
            $appointment_id = $conn->insert_id;
            
            // Log the activity
            $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, 
                           new_values, ip_address, logged_at) 
                           VALUES (?, 'CREATE', 'APPOINTMENT', ?, 'APPOINTMENT', ?, ?, NOW())";
            
            $new_values = json_encode([
                'appointment_number' => $appointment_number,
                'patient_id' => $patient_id,
                'doctor_id' => $doctor_id,
                'appointment_date' => $appointment_date,
                'appointment_time' => $appointment_time,
                'appointment_type' => $appointment_type
            ]);
            
            $ip_address = $_SERVER['REMOTE_ADDR'];
            
            $stmt = $conn->prepare($activity_sql);
            $stmt->bind_param("iiss", $user_id, $appointment_id, $new_values, $ip_address);
            $stmt->execute();
            
            $conn->commit();
            
            $success_message = "Appointment booked successfully! Appointment Number: " . $appointment_number;
            
            // Clear form data after successful submission
            $_POST = array();
            
        } catch (Exception $e) {
            $conn->rollback();
            $errors[] = "Booking failed: " . $e->getMessage();
        }
    }
}

// AJAX endpoint for patient search
if (isset($_GET['action']) && $_GET['action'] === 'search_patients') {
    $search_term = $_GET['term'] ?? '';
    
    if (strlen($search_term) >= 2) {
        $search_sql = "SELECT p.patient_id, p.patient_number, u.full_name, u.phone_primary 
                      FROM patients p 
                      JOIN users u ON p.user_id = u.user_id 
                      WHERE p.is_active = 1 
                      AND (u.full_name LIKE ? OR p.patient_number LIKE ? OR u.phone_primary LIKE ?) 
                      ORDER BY u.full_name LIMIT 10";
        
        $search_term_like = '%' . $search_term . '%';
        $stmt = $conn->prepare($search_sql);
        $stmt->bind_param("sss", $search_term_like, $search_term_like, $search_term_like);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $patients = [];
        while ($row = $result->fetch_assoc()) {
            $patients[] = [
                'id' => $row['patient_id'],
                'text' => $row['full_name'] . ' (' . $row['patient_number'] . ') - ' . $row['phone_primary']
            ];
        }
        
        header('Content-Type: application/json');
        echo json_encode($patients);
        exit();
    }
    
    header('Content-Type: application/json');
    echo json_encode([]);
    exit();
}

// AJAX endpoint for doctor availability
if (isset($_GET['action']) && $_GET['action'] === 'check_availability') {
    $doctor_id = $_GET['doctor_id'] ?? '';
    $date = $_GET['date'] ?? '';
    
    if ($doctor_id && $date) {
        // Get existing appointments for this doctor on this date
        $appointments_sql = "SELECT appointment_time, estimated_duration 
                           FROM appointments 
                           WHERE doctor_id = ? AND appointment_date = ? 
                           AND status NOT IN ('CANCELLED', 'NO_SHOW') 
                           ORDER BY appointment_time";
        
        $stmt = $conn->prepare($appointments_sql);
        $stmt->bind_param("is", $doctor_id, $date);
        $stmt->execute();
        $existing_appointments = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        
        // Generate available time slots (8 AM to 5 PM, 30-minute intervals)
        $available_slots = [];
        $start_time = new DateTime($date . ' 08:00:00');
        $end_time = new DateTime($date . ' 17:00:00');
        
        while ($start_time <= $end_time) {
            $slot_time = $start_time->format('H:i:s');
            $is_available = true;
            
            // Check if this slot conflicts with existing appointments
            foreach ($existing_appointments as $appointment) {
                $appointment_start = new DateTime($date . ' ' . $appointment['appointment_time']);
                $appointment_end = clone $appointment_start;
                $appointment_end->add(new DateInterval('PT' . ($appointment['estimated_duration'] ?? 30) . 'M'));
                
                $slot_end = clone $start_time;
                $slot_end->add(new DateInterval('PT30M'));
                
                if (($start_time >= $appointment_start && $start_time < $appointment_end) ||
                    ($slot_end > $appointment_start && $slot_end <= $appointment_end)) {
                    $is_available = false;
                    break;
                }
            }
            
            if ($is_available) {
                $available_slots[] = [
                    'time' => $slot_time,
                    'display' => $start_time->format('g:i A')
                ];
            }
            
            $start_time->add(new DateInterval('PT30M'));
        }
        
        header('Content-Type: application/json');
        echo json_encode($available_slots);
        exit();
    }
    
    header('Content-Type: application/json');
    echo json_encode([]);
    exit();
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Book Appointment')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    
    <style>
        .form-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .form-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
            border-radius: 12px 12px 0 0;
        }
        
        .form-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .form-body {
            padding: 1.5rem;
        }
        
        .appointment-type-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .appointment-card {
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .appointment-card:hover {
            border-color: #3b82f6;
            background: #f8faff;
        }
        
        .appointment-card.active {
            border-color: #3b82f6;
            background: #eff6ff;
        }
        
        .appointment-icon {
            font-size: 1.5rem;
            margin-bottom: 0.5rem;
            color: #3b82f6;
        }
        
        .doctor-card {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .doctor-card:hover {
            border-color: #3b82f6;
            background: #f8faff;
        }
        
        .doctor-card.selected {
            border-color: #3b82f6;
            background: #eff6ff;
        }
        
        .time-slots {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 0.5rem;
            margin-top: 1rem;
        }
        
        .time-slot {
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            padding: 0.5rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s;
            font-size: 0.875rem;
        }
        
        .time-slot:hover {
            border-color: #3b82f6;
            background: #f8faff;
        }
        
        .time-slot.selected {
            border-color: #3b82f6;
            background: #3b82f6;
            color: white;
        }
        
        .time-slot.unavailable {
            background: #f1f5f9;
            color: #64748b;
            cursor: not-allowed;
        }
        
        .select2-container {
            width: 100% !important;
        }
        
        .select2-selection {
            border: 1px solid #d1d5db !important;
            border-radius: 8px !important;
            height: 42px !important;
        }
        
        .select2-selection__rendered {
            line-height: 40px !important;
            padding-left: 12px !important;
        }
        
        .select2-selection__arrow {
            height: 40px !important;
        }
        
        .required {
            color: #ef4444;
        }
        
        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
            border-radius: 8px;
        }
        
        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #3b82f6;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Book Appointment</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_appointments.php">Appointments</a></li>
                                        <li class="breadcrumb-item active">Book Appointment</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Alerts -->
                    <?php if (!empty($errors)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <strong>Booking Failed!</strong>
                        <ul class="mb-0 mt-2">
                            <?php foreach ($errors as $error): ?>
                                <li><?php echo htmlspecialchars($error); ?></li>
                            <?php endforeach; ?>
                        </ul>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <?php if ($success_message): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <strong>Success!</strong> <?php echo htmlspecialchars($success_message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <!-- Appointment Booking Form -->
                    <form id="appointmentForm" method="POST" action="">
                        <!-- Patient Selection -->
                        <div class="form-card">
                            <div class="form-header">
                                <h5 class="form-title">Select Patient</h5>
                            </div>
                            <div class="form-body">
                                <div class="row">
                                    <div class="col-md-8 mb-3">
                                        <label class="form-label">Search Patient <span class="required">*</span></label>
                                        <select class="form-control" id="patientSelect" name="patient_id" required>
                                            <option value="">Search by name, patient number, or phone...</option>
                                        </select>
                                        <small class="text-muted">Type at least 2 characters to search</small>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">&nbsp;</label>
                                        <div>
                                            <a href="register_patient.php" class="btn btn-outline-primary w-100">
                                                <i class="ri-user-add-line me-1"></i> Register New Patient
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Appointment Type -->
                        <div class="form-card">
                            <div class="form-header">
                                <h5 class="form-title">Appointment Type</h5>
                            </div>
                            <div class="form-body">
                                <div class="appointment-type-cards">
                                    <div class="appointment-card" data-type="CONSULTATION">
                                        <div class="appointment-icon">👨‍⚕️</div>
                                        <h6>Consultation</h6>
                                        <p class="text-muted small mb-0">General ENT consultation</p>
                                        <input type="radio" name="appointment_type" value="CONSULTATION" style="display: none;">
                                    </div>
                                    <div class="appointment-card" data-type="FOLLOW_UP">
                                        <div class="appointment-icon">🔄</div>
                                        <h6>Follow-up</h6>
                                        <p class="text-muted small mb-0">Follow-up visit</p>
                                        <input type="radio" name="appointment_type" value="FOLLOW_UP" style="display: none;">
                                    </div>
                                    <div class="appointment-card" data-type="PROCEDURE">
                                        <div class="appointment-icon">⚕️</div>
                                        <h6>Procedure</h6>
                                        <p class="text-muted small mb-0">ENT procedure</p>
                                        <input type="radio" name="appointment_type" value="PROCEDURE" style="display: none;">
                                    </div>
                                    <div class="appointment-card" data-type="EMERGENCY">
                                        <div class="appointment-icon">🚨</div>
                                        <h6>Emergency</h6>
                                        <p class="text-muted small mb-0">Urgent consultation</p>
                                        <input type="radio" name="appointment_type" value="EMERGENCY" style="display: none;">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Doctor Selection -->
                        <div class="form-card">
                            <div class="form-header">
                                <h5 class="form-title">Select Doctor</h5>
                            </div>
                            <div class="form-body">
                                <div class="row">
                                    <?php while ($doctor = $doctors_result->fetch_assoc()): ?>
                                    <div class="col-md-6 col-lg-4 mb-3">
                                        <div class="doctor-card" data-doctor-id="<?php echo $doctor['doctor_id']; ?>">
                                            <div class="d-flex align-items-start">
                                                <div class="flex-grow-1">
                                                    <h6 class="mb-1"><?php echo htmlspecialchars($doctor['full_name']); ?></h6>
                                                    <p class="text-muted small mb-1"><?php echo htmlspecialchars($doctor['specialization']); ?></p>
                                                    <p class="text-primary small mb-0">
                                                        Fee: KES <?php echo number_format($doctor['consultation_fee']); ?>
                                                    </p>
                                                    <p class="text-muted small mb-0">
                                                        Duration: <?php echo $doctor['appointment_duration']; ?> mins
                                                    </p>
                                                </div>
                                                <input type="radio" name="doctor_id" value="<?php echo $doctor['doctor_id']; ?>" style="display: none;">
                                            </div>
                                        </div>
                                    </div>
                                    <?php endwhile; ?>
                                </div>
                            </div>
                        </div>

                        <!-- Date and Time Selection -->
                        <div class="form-card">
                            <div class="form-header">
                                <h5 class="form-title">Select Date & Time</h5>
                            </div>
                            <div class="form-body">
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Appointment Date <span class="required">*</span></label>
                                        <input type="date" class="form-control" name="appointment_date" id="appointmentDate"
                                               min="<?php echo date('Y-m-d'); ?>" 
                                               max="<?php echo date('Y-m-d', strtotime('+30 days')); ?>" required>
                                    </div>
                                    <div class="col-md-8">
                                        <label class="form-label">Available Time Slots <span class="required">*</span></label>
                                        <div id="timeSlotsContainer" style="position: relative;">
                                            <div class="time-slots" id="timeSlots">
                                                <p class="text-muted">Please select a doctor and date first</p>
                                            </div>
                                        </div>
                                        <input type="hidden" name="appointment_time" id="selectedTime" required>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Appointment Details -->
                        <div class="form-card">
                            <div class="form-header">
                                <h5 class="form-title">Appointment Details</h5>
                            </div>
                            <div class="form-body">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Chief Complaint <span class="required">*</span></label>
                                        <textarea class="form-control" name="chief_complaint" rows="3" 
                                                  placeholder="Describe the main reason for this appointment" required><?php echo htmlspecialchars($_POST['chief_complaint'] ?? ''); ?></textarea>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Special Requirements</label>
                                        <textarea class="form-control" name="special_requirements" rows="3" 
                                                  placeholder="Any special requirements or notes"><?php echo htmlspecialchars($_POST['special_requirements'] ?? ''); ?></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Form Actions -->
                        <div class="form-card">
                            <div class="form-body">
                                <div class="d-flex justify-content-between">
                                    <a href="list_appointments.php" class="btn btn-secondary">
                                        <i class="ri-arrow-left-line me-1"></i> Back to Appointments
                                    </a>
                                    <div>
                                        <button type="button" class="btn btn-secondary me-2" onclick="clearForm()">
                                            <i class="ri-refresh-line me-1"></i> Clear Form
                                        </button>
                                        <button type="submit" class="btn btn-primary">
                                            <i class="ri-calendar-check-line me-1"></i> Book Appointment
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Initialize Select2 for patient search
        $('#patientSelect').select2({
            ajax: {
                url: 'book_appointment.php?action=search_patients',
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    return {
                        term: params.term
                    };
                },
                processResults: function (data) {
                    return {
                        results: data
                    };
                },
                cache: true
            },
            minimumInputLength: 2,
            placeholder: 'Search by name, patient number, or phone...'
        });
        
        // Appointment type selection
        const appointmentCards = document.querySelectorAll('.appointment-card');
        appointmentCards.forEach(card => {
            card.addEventListener('click', function() {
                appointmentCards.forEach(c => c.classList.remove('active'));
                this.classList.add('active');
                const radioInput = this.querySelector('input[type="radio"]');
                radioInput.checked = true;
            });
        });
        
        // Set default appointment type to CONSULTATION
        document.querySelector('[data-type="CONSULTATION"]').click();
        
        // Doctor selection
        const doctorCards = document.querySelectorAll('.doctor-card');
        doctorCards.forEach(card => {
            card.addEventListener('click', function() {
                doctorCards.forEach(c => c.classList.remove('selected'));
                this.classList.add('selected');
                const radioInput = this.querySelector('input[type="radio"]');
                radioInput.checked = true;
                
                // Load available time slots when doctor and date are selected
                loadAvailableSlots();
            });
        });
        
        // Date selection
        document.getElementById('appointmentDate').addEventListener('change', function() {
            loadAvailableSlots();
        });
        
        // Load available time slots
        function loadAvailableSlots() {
            const doctorId = document.querySelector('input[name="doctor_id"]:checked')?.value;
            const date = document.getElementById('appointmentDate').value;
            
            if (!doctorId || !date) {
                return;
            }
            
            const container = document.getElementById('timeSlotsContainer');
            const slotsDiv = document.getElementById('timeSlots');
            
            // Show loading
            container.style.position = 'relative';
            const loadingOverlay = document.createElement('div');
            loadingOverlay.className = 'loading-overlay';
            loadingOverlay.innerHTML = '<div class="spinner"></div>';
            container.appendChild(loadingOverlay);
            
            fetch(`book_appointment.php?action=check_availability&doctor_id=${doctorId}&date=${date}`)
                .then(response => response.json())
                .then(slots => {
                    container.removeChild(loadingOverlay);
                    
                    if (slots.length === 0) {
                        slotsDiv.innerHTML = '<p class="text-muted">No available slots for this date</p>';
                        return;
                    }
                    
                    let slotsHtml = '';
                    slots.forEach(slot => {
                        slotsHtml += `
                            <div class="time-slot" data-time="${slot.time}">
                                ${slot.display}
                            </div>
                        `;
                    });
                    
                    slotsDiv.innerHTML = slotsHtml;
                    
                    // Add click handlers to time slots
                    document.querySelectorAll('.time-slot').forEach(slot => {
                        slot.addEventListener('click', function() {
                            if (this.classList.contains('unavailable')) return;
                            
                            document.querySelectorAll('.time-slot').forEach(s => s.classList.remove('selected'));
                            this.classList.add('selected');
                            document.getElementById('selectedTime').value = this.dataset.time;
                        });
                    });
                })
                .catch(error => {
                    container.removeChild(loadingOverlay);
                    slotsDiv.innerHTML = '<p class="text-danger">Error loading available slots</p>';
                    console.error('Error:', error);
                });
        }
        
        // Form validation
        const form = document.getElementById('appointmentForm');
        form.addEventListener('submit', function(e) {
            // Check if patient is selected
            if (!document.querySelector('select[name="patient_id"]').value) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Patient Required',
                    text: 'Please select a patient for the appointment.'
                });
                return;
            }
            
            // Check if appointment type is selected
            if (!document.querySelector('input[name="appointment_type"]:checked')) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Appointment Type Required',
                    text: 'Please select an appointment type.'
                });
                return;
            }
            
            // Check if doctor is selected
            if (!document.querySelector('input[name="doctor_id"]:checked')) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Doctor Required',
                    text: 'Please select a doctor for the appointment.'
                });
                return;
            }
            
            // Check if time is selected
            if (!document.getElementById('selectedTime').value) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Time Required',
                    text: 'Please select an appointment time.'
                });
                return;
            }
            
            // Show loading state
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="ri-loader-2-line me-1 spin"></i> Booking...';
            submitBtn.disabled = true;
            
            // Re-enable button after a delay in case of errors
            setTimeout(() => {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            }, 5000);
        });
        
        // Set initial values if form was submitted with errors
        <?php if (!empty($_POST['appointment_type'])): ?>
        document.querySelector('[data-type="<?php echo $_POST['appointment_type']; ?>"]')?.click();
        <?php endif; ?>
        
        <?php if (!empty($_POST['doctor_id'])): ?>
        document.querySelector('[data-doctor-id="<?php echo $_POST['doctor_id']; ?>"]')?.click();
        <?php endif; ?>
    });
    
    // Clear form function
    function clearForm() {
        Swal.fire({
            title: 'Clear Form?',
            text: 'This will clear all entered data. Are you sure?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, clear it!'
        }).then((result) => {
            if (result.isConfirmed) {
                document.getElementById('appointmentForm').reset();
                $('#patientSelect').val(null).trigger('change');
                document.querySelectorAll('.appointment-card').forEach(card => {
                    card.classList.remove('active');
                });
                document.querySelectorAll('.doctor-card').forEach(card => {
                    card.classList.remove('selected');
                });
                document.querySelectorAll('.time-slot').forEach(slot => {
                    slot.classList.remove('selected');
                });
                document.getElementById('timeSlots').innerHTML = '<p class="text-muted">Please select a doctor and date first</p>';
                document.getElementById('selectedTime').value = '';
                
                // Reset to default appointment type
                document.querySelector('[data-type="CONSULTATION"]').click();
                
                Swal.fire({
                    icon: 'success',
                    title: 'Form Cleared',
                    text: 'All fields have been cleared.',
                    timer: 1500,
                    showConfirmButton: false
                });
            }
        });
    }
    
    // Add CSS for loading animation
    const style = document.createElement('style');
    style.textContent = `
        .spin {
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
    `;
    document.head.appendChild(style);
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>