<?php
// ============================================
// APPOINTMENT BOOKING WITH SMS
// Path: /public_html/Appointment/opd/book.php
// ============================================

session_start();

// Check if patient is logged in
if (!isset($_SESSION['opd_patient'])) {
    $_SESSION['redirect_after_login'] = 'opd/book.php';
    header('Location: login.php');
    exit;
}

require_once '../config.php';
require_once 'sms_helper.php'; // Include SMS helper

// --- Define $brand ---
$brand = array(
    'name' => 'ওয়ান হোমিওপ্যাথি',
    'slogan' => 'প্রাকৃতিক চিকিৎসায় সুস্থ জীবন',
    'phone' => '017XXXXXXXX',
    'whatsapp' => '017XXXXXXXX',
    'email' => 'info@example.com',
    'address' => 'ঢাকা, বাংলাদেশ',
    'logo' => '',
    'facebook' => '',
    'youtube' => '',
    'hero_image' => 'assets/images/hero-bg.jpg'
);

try {
    $brand_result = mysqli_query($conn, "SELECT * FROM brand LIMIT 1");
    if ($brand_result && mysqli_num_rows($brand_result) > 0) {
        $brand_data = mysqli_fetch_assoc($brand_result);
        foreach ($brand_data as $key => $value) {
            if (!empty($value)) {
                $brand[$key] = $value;
            }
        }
    }
} catch (Exception $e) {
    // Use defaults
}

$patient_id = $_SESSION['opd_patient'];
$patient_name = $_SESSION['opd_patient_name'] ?? 'রোগী';

// Get patient info
$patient_query = mysqli_query($conn, "SELECT * FROM opd_patients WHERE id = '$patient_id'");
$patient = mysqli_fetch_assoc($patient_query);
$patient_phone = $patient['mobile'] ?? '';

// --- Get Chambers ---
$chambers = array();
$chambers_result = mysqli_query($conn, "SELECT * FROM chambers WHERE status = 'active' ORDER BY id");
if ($chambers_result) {
    while ($row = mysqli_fetch_assoc($chambers_result)) {
        $chambers[] = $row;
    }
}

// --- Patient Categories ---
$categories = array(
    'regular' => array('label' => 'নিয়মিত', 'fee' => 200),
    'special' => array('label' => 'বিশেষ রোগী', 'fee' => 500),
    'free_medicine' => array('label' => 'ফ্রি মেডিসিন', 'fee' => 100)
);

// --- Handle Form Submission ---
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['book_appointment'])) {
    $chamber_id = intval($_POST['chamber_id']);
    $appointment_date = mysqli_real_escape_string($conn, $_POST['appointment_date']);
    $time_slot = mysqli_real_escape_string($conn, $_POST['time_slot']);
    $category = mysqli_real_escape_string($conn, $_POST['patient_category']);
    $symptoms = mysqli_real_escape_string($conn, $_POST['symptoms'] ?? '');
    $fee = floatval($_POST['fee'] ?? 0);

    // Validate
    if (empty($chamber_id) || empty($appointment_date) || empty($time_slot)) {
        $message = 'দয়া করে সকল প্রয়োজনীয় তথ্য পূরণ করুন।';
        $message_type = 'danger';
    } else {
        // Check if slot is available
        $check_query = "SELECT id FROM time_slots 
                        WHERE chamber_id = $chamber_id 
                        AND slot_date = '$appointment_date' 
                        AND start_time = '$time_slot' 
                        AND is_booked = 0";
        $check_result = mysqli_query($conn, $check_query);
        
        if (mysqli_num_rows($check_result) > 0) {
            $slot = mysqli_fetch_assoc($check_result);
            $slot_id = $slot['id'];
            
            // Get chamber details for SMS
            $chamber_query = mysqli_query($conn, "SELECT name, address, phone FROM chambers WHERE id = $chamber_id");
            $chamber = mysqli_fetch_assoc($chamber_query);
            
            // Insert appointment
            $insert_query = "INSERT INTO appointments 
                            (patient_id, chamber_id, time_slot_id, appointment_date, appointment_time, 
                             patient_category, fee, symptoms, status, created_at) 
                            VALUES 
                            ('$patient_id', '$chamber_id', '$slot_id', '$appointment_date', '$time_slot', 
                             '$category', '$fee', '$symptoms', 'confirmed', NOW())";
            
            if (mysqli_query($conn, $insert_query)) {
                $appointment_id = mysqli_insert_id($conn);
                
                // Mark slot as booked
                mysqli_query($conn, "UPDATE time_slots SET is_booked = 1, booked_by = '$patient_id' WHERE id = '$slot_id'");
                
                // --- SEND SMS NOTIFICATIONS ---
                $sms_success = true;
                $sms_messages = array();
                
                // 1. Send confirmation to patient
                $category_label = $categories[$category]['label'] ?? $category;
                $patient_sms = sendPatientConfirmation(
                    $patient_name,
                    $patient_phone,
                    $appointment_date,
                    date('h:i A', strtotime($time_slot)),
                    $chamber['name'],
                    $chamber['address'],
                    $fee
                );
                
                if (!$patient_sms['success']) {
                    $sms_success = false;
                    $sms_messages[] = "রোগীকে SMS পাঠাতে ব্যর্থ হয়েছে: " . ($patient_sms['message'] ?? 'অজানা ত্রুটি');
                }
                
                // 2. Send admin notification
                $admin_sms = sendAdminNotification(
                    $patient_name,
                    $patient_phone,
                    $appointment_date,
                    date('h:i A', strtotime($time_slot)),
                    $chamber['name'],
                    $category_label,
                    $fee
                );
                
                if (!$admin_sms['success']) {
                    $sms_success = false;
                    $sms_messages[] = "অ্যাডমিনকে SMS পাঠাতে ব্যর্থ হয়েছে: " . ($admin_sms['message'] ?? 'অজানা ত্রুটি');
                }
                
                // Update appointment with SMS status
                $sms_status = $sms_success ? 1 : 0;
                mysqli_query($conn, "UPDATE appointments SET sms_sent = $sms_status WHERE id = $appointment_id");
                
                // Show success message
                $message = 'অ্যাপয়েন্টমেন্ট সফলভাবে বুক হয়েছে!';
                if ($sms_success) {
                    $message .= ' এসএমএস নিশ্চিতকরণ পাঠানো হয়েছে।';
                } else {
                    $message .= ' কিন্তু এসএমএস পাঠাতে সমস্যা হয়েছে। আমাদের সাথে যোগাযোগ করুন।';
                }
                $message_type = 'success';
                
            } else {
                $message = 'অ্যাপয়েন্টমেন্ট বুক করতে ব্যর্থ হয়েছে। আবার চেষ্টা করুন।';
                $message_type = 'danger';
            }
        } else {
            $message = 'এই সময় স্লটটি আর উপলব্ধ নেই। অন্য সময় নির্বাচন করুন।';
            $message_type = 'danger';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>অ্যাপয়েন্টমেন্ট বুকিং | <?php echo htmlspecialchars($brand['name']); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
    
    <style>
        :root {
            --primary: #2d6a4f;
            --primary-dark: #1b4332;
            --primary-light: #52b788;
            --secondary: #25D366;
            --accent: #f39c12;
            --sidebar-width: 260px;
            --bg-light: #f8f9fa;
            --text-dark: #1a1a2e;
            --text-light: #6c757d;
            --shadow: 0 10px 40px rgba(0,0,0,0.08);
            --radius: 16px;
            --navbar-height: 60px;
            --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Hind Siliguri', 'SolaimanLipi', Arial, sans-serif;
            background: #f0f4f8;
            color: var(--text-dark);
            min-height: 100vh;
        }

        /* ============================================
           SIDEBAR
           ============================================ */
        .sidebar {
            position: fixed;
            top: 0;
            left: 0;
            height: 100vh;
            width: var(--sidebar-width);
            background: white;
            box-shadow: 2px 0 20px rgba(0,0,0,0.06);
            z-index: 1050;
            transition: var(--transition);
            overflow-y: auto;
            padding: 0;
        }
        .sidebar .sidebar-header {
            padding: 20px 20px 15px;
            border-bottom: 1px solid #e9ecef;
            text-align: center;
        }
        .sidebar .sidebar-header img {
            height: 45px;
            width: auto;
            object-fit: contain;
            margin-bottom: 5px;
        }
        .sidebar .sidebar-header h5 {
            font-weight: 700;
            color: var(--primary);
            margin: 0;
            font-size: 1.1rem;
        }
        .sidebar .sidebar-header small {
            color: var(--text-light);
            font-size: 0.75rem;
        }

        .sidebar .nav {
            padding: 15px 12px;
        }
        .sidebar .nav-item {
            margin-bottom: 3px;
        }
        .sidebar .nav-link {
            padding: 12px 16px;
            border-radius: 12px;
            color: #2c3e50;
            font-weight: 500;
            transition: var(--transition);
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 0.95rem;
        }
        .sidebar .nav-link i {
            width: 22px;
            text-align: center;
            font-size: 1.1rem;
        }
        .sidebar .nav-link:hover {
            background: rgba(45, 106, 79, 0.08);
            color: var(--primary);
        }
        .sidebar .nav-link.active {
            background: var(--primary);
            color: white;
        }
        .sidebar .nav-link.active i {
            color: white;
        }
        .sidebar .nav-link .badge {
            margin-left: auto;
            background: #e74c3c;
            color: white;
            font-size: 0.7rem;
            padding: 2px 8px;
            border-radius: 50px;
        }

        .sidebar-footer {
            padding: 15px 20px;
            border-top: 1px solid #e9ecef;
            position: sticky;
            bottom: 0;
            background: white;
        }
        .sidebar-footer .btn-logout {
            width: 100%;
            padding: 10px;
            border-radius: 12px;
            background: #e74c3c;
            color: white;
            border: none;
            font-weight: 600;
            transition: var(--transition);
        }
        .sidebar-footer .btn-logout:hover {
            background: #c0392b;
        }

        /* ============================================
           MAIN CONTENT
           ============================================ */
        .main-content {
            margin-left: var(--sidebar-width);
            min-height: 100vh;
            padding: 0;
        }

        /* TOP NAVBAR */
        .top-navbar {
            background: white;
            padding: 12px 25px;
            box-shadow: 0 2px 15px rgba(0,0,0,0.06);
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 1000;
            min-height: var(--navbar-height);
        }
        .top-navbar .toggle-sidebar {
            background: none;
            border: none;
            font-size: 1.3rem;
            color: var(--text-dark);
            cursor: pointer;
            padding: 5px 10px;
            border-radius: 8px;
            transition: var(--transition);
        }
        .top-navbar .toggle-sidebar:hover {
            background: rgba(0,0,0,0.05);
        }
        .top-navbar .page-title {
            font-weight: 600;
            font-size: 1.1rem;
            margin: 0;
        }
        .top-navbar .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .top-navbar .user-info .avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background: var(--primary);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
        }
        .top-navbar .user-info .name {
            font-weight: 500;
            font-size: 0.95rem;
        }

        /* PAGE CONTENT */
        .page-content {
            padding: 25px 30px;
        }

        /* BOOKING FORM */
        .booking-card {
            background: white;
            border-radius: var(--radius);
            padding: 35px;
            box-shadow: var(--shadow);
            max-width: 800px;
            margin: 0 auto;
        }
        .booking-card h2 {
            font-size: 1.8rem;
            font-weight: 700;
            color: var(--primary);
            margin-bottom: 5px;
        }
        .booking-card .subtitle {
            color: var(--text-light);
            margin-bottom: 25px;
        }

        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            font-weight: 600;
            margin-bottom: 6px;
            display: block;
            font-size: 0.95rem;
        }
        .form-group label .required {
            color: #e74c3c;
        }

        .form-control {
            border-radius: 12px;
            padding: 12px 18px;
            border: 2px solid #e9ecef;
            font-size: 1rem;
            transition: var(--transition);
            width: 100%;
        }
        .form-control:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 4px rgba(45, 106, 79, 0.1);
        }
        .form-control:disabled {
            background: #f8f9fa;
            cursor: not-allowed;
        }

        select.form-control {
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%232c3e50' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 15px center;
        }

        .fee-display {
            background: linear-gradient(135deg, var(--primary), var(--primary-light));
            color: white;
            padding: 20px 25px;
            border-radius: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin: 25px 0;
        }
        .fee-display .fee-label {
            font-size: 1.1rem;
            opacity: 0.9;
        }
        .fee-display .fee-amount {
            font-size: 2rem;
            font-weight: 700;
        }
        .fee-display .fee-amount span {
            font-size: 1rem;
            font-weight: 400;
            opacity: 0.8;
        }

        .btn-book {
            width: 100%;
            padding: 14px;
            background: linear-gradient(135deg, var(--primary), var(--primary-light));
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
        }
        .btn-book:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 30px rgba(45, 106, 79, 0.3);
        }
        .btn-book:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255,255,255,0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 0.8s linear infinite;
        }
        @keyframes spin { to { transform: rotate(360deg); } }

        /* ALERT */
        .alert-custom {
            border-radius: 12px;
            padding: 15px 20px;
            margin-bottom: 20px;
        }
        .alert-custom.success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        .alert-custom.danger {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }

        /* ============================================
           RESPONSIVE
           ============================================ */
        @media (max-width: 991px) {
            .sidebar {
                transform: translateX(-100%);
                width: 280px;
            }
            .sidebar.open {
                transform: translateX(0);
            }
            .main-content {
                margin-left: 0;
            }
            .page-content {
                padding: 20px;
            }
        }

        @media (max-width: 767px) {
            .booking-card { padding: 20px; }
            .fee-display { flex-direction: column; text-align: center; gap: 10px; }
            .fee-display .fee-amount { font-size: 1.6rem; }
            .top-navbar .user-info .name { display: none; }
        }

        @media (max-width: 480px) {
            .booking-card { padding: 15px; }
            .top-navbar { padding: 10px 15px; }
            .page-content { padding: 15px; }
        }

        /* Overlay for mobile */
        .sidebar-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.4);
            z-index: 1040;
        }
        .sidebar-overlay.active {
            display: block;
        }

        /* SIDEBAR SCROLL */
        .sidebar::-webkit-scrollbar {
            width: 4px;
        }
        .sidebar::-webkit-scrollbar-track {
            background: #f1f1f1;
        }
        .sidebar::-webkit-scrollbar-thumb {
            background: var(--primary-light);
            border-radius: 10px;
        }
    </style>
</head>
<body>

<!-- ============================================
     SIDEBAR OVERLAY (Mobile)
     ============================================ -->
<div class="sidebar-overlay" id="sidebarOverlay" onclick="toggleSidebar()"></div>

<!-- ============================================
     SIDEBAR
     ============================================ -->
<div class="sidebar" id="sidebar">
    <div class="sidebar-header">
        <?php if (!empty($brand['logo'])): ?>
            <img src="<?php echo htmlspecialchars($brand['logo']); ?>" alt="Logo">
        <?php else: ?>
            <i class="fas fa-clinic-medical" style="font-size:2rem;color:var(--primary);"></i>
        <?php endif; ?>
        <h5><?php echo htmlspecialchars($brand['name']); ?></h5>
        <small>রোগী ড্যাশবোর্ড</small>
    </div>

    <ul class="nav flex-column">
        <li class="nav-item">
            <a class="nav-link" href="dashboard.php">
                <i class="fas fa-tachometer-alt"></i> ড্যাশবোর্ড
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link active" href="book.php">
                <i class="fas fa-calendar-plus"></i> অ্যাপয়েন্টমেন্ট বুক
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="my_appointments.php">
                <i class="fas fa-calendar-check"></i> আমার অ্যাপয়েন্টমেন্ট
                <span class="badge" id="appointmentCount">0</span>
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="my_orders.php">
                <i class="fas fa-shopping-bag"></i> আমার অর্ডার
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="profile.php">
                <i class="fas fa-user"></i> প্রোফাইল
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="../index.php#chambers">
                <i class="fas fa-hospital"></i> চেম্বারসমূহ
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="../index.php#contact">
                <i class="fas fa-headset"></i> সাহায্য
            </a>
        </li>
    </ul>

    <div class="sidebar-footer">
        <button class="btn-logout" onclick="window.location.href='logout.php'">
            <i class="fas fa-sign-out-alt"></i> লগআউট
        </button>
    </div>
</div>

<!-- ============================================
     MAIN CONTENT
     ============================================ -->
<div class="main-content">
    <!-- TOP NAVBAR -->
    <div class="top-navbar">
        <div>
            <button class="toggle-sidebar" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <span class="page-title">📅 অ্যাপয়েন্টমেন্ট বুকিং</span>
        </div>
        <div class="user-info">
            <span class="name"><?php echo htmlspecialchars($patient_name); ?></span>
            <div class="avatar"><?php echo substr($patient_name, 0, 1); ?></div>
        </div>
    </div>

    <!-- PAGE CONTENT -->
    <div class="page-content">
        <div class="booking-card" data-aos="fade-up">
            <h2><i class="fas fa-calendar-plus" style="color: var(--primary);"></i> অ্যাপয়েন্টমেন্ট বুক করুন</h2>
            <p class="subtitle">আপনার পছন্দের চেম্বার ও সময়ে অ্যাপয়েন্টমেন্ট নিন</p>

            <?php if ($message): ?>
                <div class="alert-custom <?php echo $message_type; ?>">
                    <i class="fas <?php echo $message_type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'; ?>"></i>
                    <?php echo htmlspecialchars($message); ?>
                </div>
            <?php endif; ?>

            <form id="bookingForm" method="POST" action="">
                <!-- Chamber -->
                <div class="form-group">
                    <label for="chamber_id">চেম্বার নির্বাচন করুন <span class="required">*</span></label>
                    <select name="chamber_id" id="chamber_id" class="form-control" required>
                        <option value="">-- চেম্বার নির্বাচন করুন --</option>
                        <?php foreach ($chambers as $chamber): ?>
                            <option value="<?php echo $chamber['id']; ?>">
                                <?php echo htmlspecialchars($chamber['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Date -->
                <div class="form-group">
                    <label for="appointment_date">তারিখ <span class="required">*</span></label>
                    <input type="date" name="appointment_date" id="appointment_date" class="form-control" 
                           min="<?php echo date('Y-m-d'); ?>" required>
                </div>

                <!-- Time Slot -->
                <div class="form-group">
                    <label for="time_slot">সময় স্লট <span class="required">*</span></label>
                    <select name="time_slot" id="time_slot" class="form-control" required disabled>
                        <option value="">প্রথমে চেম্বার ও তারিখ নির্বাচন করুন</option>
                    </select>
                </div>

                <!-- Patient Category -->
                <div class="form-group">
                    <label for="patient_category">রোগীর ক্যাটাগরি <span class="required">*</span></label>
                    <select name="patient_category" id="patient_category" class="form-control" required>
                        <?php foreach ($categories as $key => $cat): ?>
                            <option value="<?php echo $key; ?>" data-fee="<?php echo $cat['fee']; ?>">
                                <?php echo htmlspecialchars($cat['label']); ?> (<?php echo $cat['fee']; ?> টাকা)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Symptoms -->
                <div class="form-group">
                    <label for="symptoms">রোগের লক্ষণ (ঐচ্ছিক)</label>
                    <textarea name="symptoms" id="symptoms" class="form-control" rows="3" 
                              placeholder="আপনার শারীরিক সমস্যা সম্পর্কে সংক্ষেপে লিখুন..."></textarea>
                </div>

                <!-- Fee Display -->
                <div class="fee-display">
                    <span class="fee-label"><i class="fas fa-money-bill-wave"></i> মোট ফি</span>
                    <span class="fee-amount" id="feeAmount">২০০ <span>টাকা</span></span>
                </div>

                <!-- Hidden fee field -->
                <input type="hidden" name="fee" id="fee" value="200">

                <button type="submit" name="book_appointment" class="btn-book" id="bookBtn">
                    <i class="fas fa-check-circle"></i> অ্যাপয়েন্টমেন্ট বুক করুন
                </button>
            </form>
        </div>
    </div>
</div>

<!-- ============================================
     SCRIPTS
     ============================================ -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>

<script>
AOS.init({
    duration: 800,
    once: true,
    offset: 50,
    easing: 'ease-out-cubic'
});

// ============================================
// SIDEBAR TOGGLE
// ============================================
function toggleSidebar() {
    document.getElementById('sidebar').classList.toggle('open');
    document.getElementById('sidebarOverlay').classList.toggle('active');
}

// Close sidebar on escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        document.getElementById('sidebar').classList.remove('open');
        document.getElementById('sidebarOverlay').classList.remove('active');
    }
});

// ============================================
// DYNAMIC TIME SLOTS
// ============================================
$('#chamber_id, #appointment_date').change(function() {
    const chamber_id = $('#chamber_id').val();
    const date = $('#appointment_date').val();

    if (chamber_id && date) {
        $('#time_slot').prop('disabled', true).html('<option value="">লোড হচ্ছে...</option>');
        
        $.ajax({
            url: 'ajax_get_slots.php',
            method: 'POST',
            data: { chamber_id, date },
            success: function(response) {
                $('#time_slot').html(response).prop('disabled', false);
            },
            error: function() {
                $('#time_slot').html('<option value="">স্লট লোড করতে ব্যর্থ হয়েছে</option>').prop('disabled', true);
            }
        });
    } else {
        $('#time_slot').html('<option value="">প্রথমে চেম্বার ও তারিখ নির্বাচন করুন</option>').prop('disabled', true);
    }
});

// ============================================
// DYNAMIC FEE CALCULATION
// ============================================
function updateFee() {
    const category = $('#patient_category').val();
    const fee = $('#patient_category option:selected').data('fee') || 200;
    $('#feeAmount').html(fee + ' <span>টাকা</span>');
    $('#fee').val(fee);
}

$('#patient_category').change(updateFee);
updateFee();

// ============================================
// FORM SUBMISSION
// ============================================
$('#bookingForm').on('submit', function(e) {
    const chamber = $('#chamber_id').val();
    const date = $('#appointment_date').val();
    const slot = $('#time_slot').val();

    if (!chamber || !date || !slot) {
        e.preventDefault();
        alert('দয়া করে সকল প্রয়োজনীয় তথ্য পূরণ করুন।');
        return false;
    }

    const btn = $('#bookBtn');
    btn.prop('disabled', true).html('<span class="spinner"></span> প্রক্রিয়াকরণ...');
});

// ============================================
// GET APPOINTMENT COUNT
// ============================================
function getAppointmentCount() {
    $.ajax({
        url: 'get_appointment_count.php',
        method: 'GET',
        dataType: 'json',
        success: function(response) {
            if (response.count > 0) {
                $('#appointmentCount').text(response.count).show();
            } else {
                $('#appointmentCount').hide();
            }
        },
        error: function() {
            $('#appointmentCount').hide();
        }
    });
}

// Call on load
$(document).ready(function() {
    getAppointmentCount();
    // Refresh every 60 seconds
    setInterval(getAppointmentCount, 60000);
});
</script>

</body>
</html>