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

// This page is accessible without login for public booking
$is_logged_in = isset($_SESSION['user_id']);
$is_patient = $is_logged_in && $_SESSION['role_code'] === 'PATIENT';

// Get available doctors
$doctors_sql = "SELECT d.doctor_id, d.specialization, d.sub_specialization, d.consultation_fee, 
                       d.is_consultant, d.is_surgeon, d.experience_years,
                       u.full_name, u.profile_picture
                FROM doctors d
                INNER JOIN users u ON d.user_id = u.user_id
                WHERE d.is_active = 1
                ORDER BY u.full_name";
$doctors_result = $conn->query($doctors_sql);

// Get selected doctor if any
$selected_doctor_id = isset($_GET['doctor_id']) ? (int)$_GET['doctor_id'] : 0;
$selected_doctor = null;

if ($selected_doctor_id) {
    $doctor_sql = "SELECT d.*, u.full_name, u.profile_picture, u.email, u.phone_primary
                   FROM doctors d
                   INNER JOIN users u ON d.user_id = u.user_id
                   WHERE d.doctor_id = ? AND d.is_active = 1";
    $stmt = $conn->prepare($doctor_sql);
    $stmt->bind_param('i', $selected_doctor_id);
    $stmt->execute();
    $selected_doctor = $stmt->get_result()->fetch_assoc();
}

// Get available dates (next 30 days)
$available_dates = [];
for ($i = 0; $i < 30; $i++) {
    $date = date('Y-m-d', strtotime("+$i days"));
    $available_dates[] = [
        'date' => $date,
        'day_name' => date('l', strtotime($date)),
        'formatted' => date('d M Y', strtotime($date))
    ];
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Book Appointment - ENT Hospital</title>
    <link href="assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    
    <style>
        :root {
            --primary: #667eea;
            --primary-dark: #5a67d8;
            --secondary: #764ba2;
            --success: #10b981;
            --danger: #ef4444;
            --warning: #f59e0b;
            --info: #3b82f6;
        }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 2rem 0;
        }
        
        .booking-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 1rem;
        }
        
        .booking-header {
            text-align: center;
            color: white;
            margin-bottom: 2rem;
        }
        
        .booking-header h1 {
            font-size: 2.5rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .booking-card {
            background: white;
            border-radius: 16px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .booking-steps {
            display: flex;
            background: #f8fafc;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .step {
            flex: 1;
            padding: 1.5rem;
            text-align: center;
            position: relative;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .step.active {
            background: white;
            color: var(--primary);
        }
        
        .step.completed {
            background: #d1fae5;
            color: var(--success);
        }
        
        .step-number {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #e2e8f0;
            color: #64748b;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .step.active .step-number {
            background: var(--primary);
            color: white;
        }
        
        .step.completed .step-number {
            background: var(--success);
            color: white;
        }
        
        .step-title {
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        .booking-content {
            padding: 2rem;
        }
        
        .step-content {
            display: none;
        }
        
        .step-content.active {
            display: block;
            animation: fadeIn 0.3s;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .doctor-card {
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .doctor-card:hover {
            border-color: var(--primary);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
            transform: translateY(-2px);
        }
        
        .doctor-card.selected {
            border-color: var(--primary);
            background: #f5f7ff;
        }
        
        .doctor-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 2rem;
            font-weight: 700;
        }
        
        .doctor-avatar img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            object-fit: cover;
        }
        
        .date-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 1rem;
            margin-top: 1rem;
        }
        
        .date-card {
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .date-card:hover {
            border-color: var(--primary);
            transform: translateY(-2px);
        }
        
        .date-card.selected {
            border-color: var(--primary);
            background: #f5f7ff;
        }
        
        .date-card.disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .date-day {
            font-size: 0.75rem;
            color: #64748b;
            text-transform: uppercase;
            margin-bottom: 0.25rem;
        }
        
        .date-number {
            font-size: 1.5rem;
            font-weight: 700;
            color: #1e293b;
        }
        
        .time-slots-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
            gap: 0.75rem;
            margin-top: 1rem;
        }
        
        .time-slot {
            border: 2px solid #e2e8f0;
            border-radius: 6px;
            padding: 0.75rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: 500;
        }
        
        .time-slot:hover:not(.disabled) {
            border-color: var(--primary);
            transform: translateY(-2px);
        }
        
        .time-slot.selected {
            border-color: var(--primary);
            background: #f5f7ff;
            color: var(--primary);
        }
        
        .time-slot.disabled {
            opacity: 0.4;
            cursor: not-allowed;
        }
        
        .btn-primary-custom {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            border: none;
            color: white;
            padding: 0.75rem 2rem;
            border-radius: 8px;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .btn-primary-custom:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }
        
        .summary-card {
            background: #f8fafc;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
        
        .summary-row {
            display: flex;
            justify-content: space-between;
            padding: 0.75rem 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .summary-row:last-child {
            border-bottom: none;
            font-weight: 700;
            font-size: 1.125rem;
            color: var(--primary);
        }
        
        .payment-method {
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 1.25rem;
            margin-bottom: 1rem;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .payment-method:hover {
            border-color: var(--primary);
        }
        
        .payment-method.selected {
            border-color: var(--primary);
            background: #f5f7ff;
        }
        
        .payment-icon {
            width: 50px;
            height: 50px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
        }
        
        .mpesa-icon {
            background: #d1fae5;
            color: var(--success);
        }
        
        .card-icon {
            background: #dbeafe;
            color: var(--info);
        }
        
        .insurance-icon {
            background: #fef3c7;
            color: var(--warning);
        }
        
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.7);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 9999;
        }
        
        .loading-overlay.active {
            display: flex;
        }
        
        .spinner {
            width: 50px;
            height: 50px;
            border: 5px solid rgba(255,255,255,0.3);
            border-top-color: white;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
</head>

<body>
    <div class="booking-container">
        <div class="booking-header">
            <h1><i class="ri-hospital-line"></i> ENT Hospital</h1>
            <p>Book your appointment online - Quick & Easy</p>
            <?php if ($is_logged_in): ?>
            <p class="mb-0"><small>Welcome, <?php echo htmlspecialchars($_SESSION['full_name']); ?> | 
                <a href="index.php" style="color: white; text-decoration: underline;">Go to Dashboard</a></small></p>
            <?php else: ?>
            <p class="mb-0"><small>Already have an account? <a href="login.php" style="color: white; text-decoration: underline;">Login here</a></small></p>
            <?php endif; ?>
        </div>

        <div class="booking-card">
            <!-- Steps -->
            <div class="booking-steps">
                <div class="step active" data-step="1">
                    <div class="step-number">1</div>
                    <div class="step-title">Select Doctor</div>
                </div>
                <div class="step" data-step="2">
                    <div class="step-number">2</div>
                    <div class="step-title">Choose Date & Time</div>
                </div>
                <div class="step" data-step="3">
                    <div class="step-number">3</div>
                    <div class="step-title">Patient Details</div>
                </div>
                <div class="step" data-step="4">
                    <div class="step-number">4</div>
                    <div class="step-title">Payment & Confirm</div>
                </div>
            </div>

            <!-- Content -->
            <div class="booking-content">
                <form id="bookingForm">
                    <!-- Step 1: Select Doctor -->
                    <div class="step-content active" id="step1">
                        <h4 class="mb-4">Select a Doctor</h4>
                        
                        <div class="row">
                            <?php while($doctor = $doctors_result->fetch_assoc()): ?>
                            <div class="col-md-6">
                                <div class="doctor-card" onclick="selectDoctor(<?php echo $doctor['doctor_id']; ?>, this)">
                                    <div class="d-flex">
                                        <div class="doctor-avatar me-3">
                                            <?php if ($doctor['profile_picture']): ?>
                                                <img src="<?php echo htmlspecialchars($doctor['profile_picture']); ?>" alt="Doctor">
                                            <?php else: ?>
                                                <?php echo strtoupper(substr($doctor['full_name'], 0, 2)); ?>
                                            <?php endif; ?>
                                        </div>
                                        <div class="flex-grow-1">
                                            <h5 class="mb-1">Dr. <?php echo htmlspecialchars($doctor['full_name']); ?></h5>
                                            <p class="text-muted mb-2"><?php echo htmlspecialchars($doctor['specialization']); ?></p>
                                            <div class="d-flex gap-2 flex-wrap">
                                                <span class="badge bg-primary"><?php echo $doctor['experience_years']; ?> years exp</span>
                                                <?php if ($doctor['is_consultant']): ?>
                                                <span class="badge bg-info">Consultant</span>
                                                <?php endif; ?>
                                                <?php if ($doctor['is_surgeon']): ?>
                                                <span class="badge bg-success">Surgeon</span>
                                                <?php endif; ?>
                                            </div>
                                            <div class="mt-2">
                                                <strong class="text-primary">KES <?php echo number_format($doctor['consultation_fee'], 2); ?></strong>
                                                <small class="text-muted"> / consultation</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endwhile; ?>
                        </div>

                        <div class="text-end mt-4">
                            <button type="button" class="btn btn-primary-custom" onclick="nextStep(2)" disabled id="step1Next">
                                Continue <i class="ri-arrow-right-line"></i>
                            </button>
                        </div>
                    </div>

                    <!-- Step 2: Date & Time -->
                    <div class="step-content" id="step2">
                        <h4 class="mb-4">Choose Date & Time</h4>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <h6 class="mb-3">Select Date</h6>
                                <div class="date-grid" id="dateGrid">
                                    <!-- Dates will be loaded via AJAX -->
                                </div>
                            </div>
                            <div class="col-md-6">
                                <h6 class="mb-3">Available Time Slots</h6>
                                <div id="timeSlotsContainer">
                                    <p class="text-muted text-center py-5">Please select a date first</p>
                                </div>
                            </div>
                        </div>

                        <div class="d-flex justify-content-between mt-4">
                            <button type="button" class="btn btn-secondary" onclick="prevStep(1)">
                                <i class="ri-arrow-left-line"></i> Back
                            </button>
                            <button type="button" class="btn btn-primary-custom" onclick="nextStep(3)" disabled id="step2Next">
                                Continue <i class="ri-arrow-right-line"></i>
                            </button>
                        </div>
                    </div>

                    <!-- Step 3: Patient Details -->
                    <div class="step-content" id="step3">
                        <h4 class="mb-4">Patient Information</h4>
                        
                        <?php if ($is_patient): ?>
                            <div class="alert alert-info">
                                <i class="ri-information-line me-2"></i>
                                Your details will be automatically filled from your profile.
                            </div>
                            <input type="hidden" name="patient_id" value="<?php echo $_SESSION['patient_id']; ?>">
                        <?php else: ?>
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">Full Name *</label>
                                    <input type="text" class="form-control" name="full_name" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Email *</label>
                                    <input type="email" class="form-control" name="email" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Phone Number *</label>
                                    <input type="tel" class="form-control" name="phone" required placeholder="e.g., 0712345678">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Date of Birth *</label>
                                    <input type="date" class="form-control" name="dob" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Gender *</label>
                                    <select class="form-select" name="gender" required>
                                        <option value="">Select Gender</option>
                                        <option value="MALE">Male</option>
                                        <option value="FEMALE">Female</option>
                                        <option value="OTHER">Other</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">National ID</label>
                                    <input type="text" class="form-control" name="national_id">
                                </div>
                                <div class="col-12">
                                    <label class="form-label">Address</label>
                                    <textarea class="form-control" name="address" rows="2"></textarea>
                                </div>
                            </div>
                        <?php endif; ?>

                        <div class="mt-4">
                            <label class="form-label">Reason for Visit *</label>
                            <textarea class="form-control" name="reason" rows="3" required placeholder="Please describe your symptoms or reason for consultation"></textarea>
                        </div>

                        <div class="d-flex justify-content-between mt-4">
                            <button type="button" class="btn btn-secondary" onclick="prevStep(2)">
                                <i class="ri-arrow-left-line"></i> Back
                            </button>
                            <button type="button" class="btn btn-primary-custom" onclick="nextStep(4)">
                                Continue <i class="ri-arrow-right-line"></i>
                            </button>
                        </div>
                    </div>

                    <!-- Step 4: Payment & Confirmation -->
                    <div class="step-content" id="step4">
                        <h4 class="mb-4">Payment & Confirmation</h4>

                        <div class="row">
                            <div class="col-md-7">
                                <h6 class="mb-3">Select Payment Method</h6>
                                
                                <div class="payment-method" onclick="selectPayment('MPESA', this)">
                                    <div class="d-flex align-items-center">
                                        <div class="payment-icon mpesa-icon me-3">
                                            <i class="ri-smartphone-line"></i>
                                        </div>
                                        <div class="flex-grow-1">
                                            <h6 class="mb-1">M-Pesa</h6>
                                            <small class="text-muted">Pay using M-Pesa mobile money</small>
                                        </div>
                                        <i class="ri-checkbox-blank-circle-line text-muted"></i>
                                    </div>
                                </div>

                                <div class="payment-method" onclick="selectPayment('CARD', this)">
                                    <div class="d-flex align-items-center">
                                        <div class="payment-icon card-icon me-3">
                                            <i class="ri-bank-card-line"></i>
                                        </div>
                                        <div class="flex-grow-1">
                                            <h6 class="mb-1">Credit/Debit Card</h6>
                                            <small class="text-muted">Pay with Visa, Mastercard</small>
                                        </div>
                                        <i class="ri-checkbox-blank-circle-line text-muted"></i>
                                    </div>
                                </div>

                                <div class="payment-method" onclick="selectPayment('INSURANCE', this)">
                                    <div class="d-flex align-items-center">
                                        <div class="payment-icon insurance-icon me-3">
                                            <i class="ri-shield-check-line"></i>
                                        </div>
                                        <div class="flex-grow-1">
                                            <h6 class="mb-1">Insurance</h6>
                                            <small class="text-muted">Pay using health insurance</small>
                                        </div>
                                        <i class="ri-checkbox-blank-circle-line text-muted"></i>
                                    </div>
                                </div>

                                <div class="payment-method" onclick="selectPayment('CASH', this)">
                                    <div class="d-flex align-items-center">
                                        <div class="payment-icon" style="background: #fee2e2; color: var(--danger);">
                                            <i class="ri-money-dollar-circle-line"></i>
                                        </div>
                                        <div class="flex-grow-1">
                                            <h6 class="mb-1">Pay at Hospital</h6>
                                            <small class="text-muted">Pay cash at reception</small>
                                        </div>
                                        <i class="ri-checkbox-blank-circle-line text-muted"></i>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-5">
                                <h6 class="mb-3">Booking Summary</h6>
                                <div class="summary-card">
                                    <div class="summary-row">
                                        <span>Doctor:</span>
                                        <strong id="summaryDoctor">-</strong>
                                    </div>
                                    <div class="summary-row">
                                        <span>Date:</span>
                                        <strong id="summaryDate">-</strong>
                                    </div>
                                    <div class="summary-row">
                                        <span>Time:</span>
                                        <strong id="summaryTime">-</strong>
                                    </div>
                                    <div class="summary-row">
                                        <span>Consultation Fee:</span>
                                        <strong id="summaryFee">-</strong>
                                    </div>
                                </div>

                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="termsCheck" required>
                                    <label class="form-check-label small" for="termsCheck">
                                        I agree to the <a href="#" target="_blank">Terms & Conditions</a> and <a href="#" target="_blank">Privacy Policy</a>
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="d-flex justify-content-between mt-4">
                            <button type="button" class="btn btn-secondary" onclick="prevStep(3)">
                                <i class="ri-arrow-left-line"></i> Back
                            </button>
                            <button type="submit" class="btn btn-primary-custom" id="confirmBookingBtn" disabled>
                                <i class="ri-check-line me-1"></i> Confirm Booking
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="loading-overlay" id="loadingOverlay">
        <div class="text-center text-white">
            <div class="spinner"></div>
            <p class="mt-3">Processing your booking...</p>
        </div>
    </div>

    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/js/bootstrap.bundle.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>

    <script>
        let bookingData = {
            doctor_id: null,
            doctor_name: null,
            doctor_fee: null,
            date: null,
            formatted_date: null,
            time: null,
            payment_method: null
        };

        function selectDoctor(doctorId, cardElement) {
            // Remove previous selection
            document.querySelectorAll('.doctor-card').forEach(card => {
                card.classList.remove('selected');
            });
            
            // Mark as selected
            cardElement.classList.add('selected');
            
            // Get doctor details
            const doctorName = cardElement.querySelector('h5').textContent;
            const feeElement = cardElement.querySelector('strong');
            const doctorFee = feeElement ? feeElement.textContent : 'KES 0.00';
            
            bookingData.doctor_id = doctorId;
            bookingData.doctor_name = doctorName;
            bookingData.doctor_fee = doctorFee;
            
            // Enable next button
            document.getElementById('step1Next').disabled = false;
        }

        function nextStep(step) {
            // Validate current step
            const currentStepNum = parseInt(document.querySelector('.step.active').dataset.step);
            
            if (step === 2 && !bookingData.doctor_id) {
                Swal.fire('Error', 'Please select a doctor', 'error');
                return;
            }
            
            if (step === 3 && (!bookingData.date || !bookingData.time)) {
                Swal.fire('Error', 'Please select date and time', 'error');
                return;
            }
            
            if (step === 4) {
                // Validate step 3 form
                const reason = document.querySelector('textarea[name="reason"]').value.trim();
                if (!reason) {
                    Swal.fire('Error', 'Please provide a reason for your visit', 'error');
                    return;
                }
                if (!document.getElementById('termsCheck').checked) {
                    Swal.fire('Error', 'Please agree to the terms and conditions', 'error');
                    return;
                }
            }
            
            // Hide current content
            document.querySelector('.step-content.active').classList.remove('active');
            
            // Update steps
            document.querySelectorAll('.step').forEach(s => {
                const stepNum = parseInt(s.dataset.step);
                if (stepNum < step) {
                    s.classList.add('completed');
                    s.classList.remove('active');
                } else if (stepNum === step) {
                    s.classList.add('active');
                    s.classList.remove('completed');
                } else {
                    s.classList.remove('active', 'completed');
                }
            });
            
            // Show new content
            document.getElementById('step' + step).classList.add('active');
            
            // Load dates if moving to step 2
            if (step === 2) {
                loadAvailableDates();
            }
            
            // Update summary if moving to step 4
            if (step === 4) {
                updateSummary();
            }
            
            // Scroll to top
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }

        function prevStep(step) {
            nextStep(step);
        }

        function loadAvailableDates() {
            $.ajax({
                url: 'ajax/get_available_dates.php',
                type: 'GET',
                data: { doctor_id: bookingData.doctor_id },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        let html = '';
                        response.dates.forEach(date => {
                            const isDisabled = !date.has_slots;
                            html += `
                                <div class="date-card ${isDisabled ? 'disabled' : ''}" 
                                     onclick="${isDisabled ? '' : `selectDate('${date.date}', '${date.formatted}')`} style="cursor: ${isDisabled ? 'not-allowed' : 'pointer'};">
                                    <div class="date-day">${date.day_name.substr(0, 3)}</div>
                                    <div class="date-number">${date.day_number}</div>
                                    <div class="date-day small">${date.month}</div>
                                </div>
                            `;
                        });
                        document.getElementById('dateGrid').innerHTML = html;
                    } else {
                        Swal.fire('Error', response.message || 'Failed to load dates', 'error');
                    }
                },
                error: function() {
                    Swal.fire('Error', 'Failed to load available dates', 'error');
                }
            });
        }

        function selectDate(dateValue, formatted) {
            // Remove previous selection
            document.querySelectorAll('.date-card').forEach(card => {
                card.classList.remove('selected');
            });
            
            // Mark as selected
            event.currentTarget.classList.add('selected');
            
            bookingData.date = dateValue;
            bookingData.formatted_date = formatted;
            
            // Clear previous time slots
            document.getElementById('timeSlotsContainer').innerHTML = '<p class="text-muted text-center py-5">Loading time slots...</p>';
            
            // Load time slots
            loadTimeSlots();
            
            // Enable continue button after time selection, but for now just proceed
        }

        function loadTimeSlots() {
            $.ajax({
                url: 'ajax/get_available_times.php',
                type: 'GET',
                data: { 
                    doctor_id: bookingData.doctor_id,
                    date: bookingData.date 
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        let html = '';
                        if (response.times.length === 0) {
                            html = '<p class="text-muted text-center py-5">No available time slots for this date. Please select another date.</p>';
                        } else {
                            response.times.forEach(time => {
                                const isDisabled = !time.available;
                                html += `
                                    <div class="time-slot ${isDisabled ? 'disabled' : ''}" 
                                         onclick="${isDisabled ? '' : `selectTimeSlot('${time.time_slot}')`}" style="cursor: ${isDisabled ? 'not-allowed' : 'pointer'};">
                                        ${time.time_slot}
                                    </div>
                                `;
                            });
                        }
                        document.getElementById('timeSlotsContainer').innerHTML = `<div class="time-slots-grid">${html}</div>`;
                    } else {
                        document.getElementById('timeSlotsContainer').innerHTML = '<p class="text-muted text-center py-5">Failed to load time slots</p>';
                    }
                },
                error: function() {
                    document.getElementById('timeSlotsContainer').innerHTML = '<p class="text-muted text-center py-5">Failed to load time slots</p>';
                }
            });
        }

        function selectTimeSlot(timeValue) {
            // Remove previous selection
            document.querySelectorAll('.time-slot').forEach(slot => {
                slot.classList.remove('selected');
            });
            
            // Mark as selected
            event.currentTarget.classList.add('selected');
            
            bookingData.time = timeValue;
            
            // Enable next button
            document.getElementById('step2Next').disabled = false;
        }

        function selectPayment(method, element) {
            // Remove previous selection
            document.querySelectorAll('.payment-method').forEach(pm => {
                pm.classList.remove('selected');
            });
            
            // Mark as selected
            element.classList.add('selected');
            
            bookingData.payment_method = method;
            
            // Enable confirm button if terms checked
            checkConfirmReady();
        }

        function updateSummary() {
            document.getElementById('summaryDoctor').textContent = bookingData.doctor_name;
            document.getElementById('summaryDate').textContent = bookingData.formatted_date;
            document.getElementById('summaryTime').textContent = bookingData.time;
            document.getElementById('summaryFee').textContent = bookingData.doctor_fee;
        }

        function checkConfirmReady() {
            const termsChecked = document.getElementById('termsCheck').checked;
            const hasPayment = bookingData.payment_method;
            document.getElementById('confirmBookingBtn').disabled = !(termsChecked && hasPayment);
        }

        // Event listeners
        document.getElementById('termsCheck').addEventListener('change', checkConfirmReady);

        $('#bookingForm').on('submit', function(e) {
            e.preventDefault();
            
            if (!bookingData.payment_method || !document.getElementById('termsCheck').checked) {
                Swal.fire('Error', 'Please select payment method and agree to terms', 'error');
                return;
            }
            
            // Show loading
            document.getElementById('loadingOverlay').classList.add('active');
            
            // Collect form data
            const formData = new FormData(this);
            formData.append('doctor_id', bookingData.doctor_id);
            formData.append('appointment_date', bookingData.date);
            formData.append('appointment_time', bookingData.time);
            formData.append('payment_method', bookingData.payment_method);
            
            $.ajax({
                url: 'ajax/book_appointment.php',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: 'json',
                success: function(response) {
                    document.getElementById('loadingOverlay').classList.remove('active');
                    if (response.success) {
                        Swal.fire('Success!', 'Appointment booked successfully!', 'success').then(() => {
                            window.location.href = 'appointment_confirmation.php?booking_id=' + response.booking_id;
                        });
                    } else {
                        Swal.fire('Error', response.message || 'Failed to book appointment', 'error');
                    }
                },
                error: function() {
                    document.getElementById('loadingOverlay').classList.remove('active');
                    Swal.fire('Error', 'Failed to book appointment. Please try again.', 'error');
                }
            });
        });

        // Preselect doctor if coming from GET
        <?php if ($selected_doctor): ?>
        $(document).ready(function() {
            selectDoctor(<?php echo $selected_doctor['doctor_id']; ?>, document.querySelectorAll('.doctor-card')[0]); // Approximate, adjust if needed
            nextStep(2);
        });
        <?php endif; ?>
    </script>
</body>
</html>