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

if (!isset($_SESSION['user_id']) || $_SESSION['role_code'] !== 'PATIENT') {
    header('Location: login.php');
    exit();
}

$reschedule_id = $_GET['reschedule_id'] ?? 0;
// Note: We'll reuse existing AJAX booking or a simplified version for patients.
// Assuming 'ajax/book_appointment.php' handles the backend logic (we just modified it).
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Book Appointment')); ?>
    <link href="assets/libs/select2/css/select2.min.css" rel="stylesheet" />
    <link href="assets/libs/flatpickr/flatpickr.min.css" rel="stylesheet" />
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <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">
                                    <?php echo $reschedule_id ? 'Reschedule Appointment' : 'Book New Appointment'; ?>
                                </h4>
                            </div>
                        </div>
                    </div>

                    <div class="row justify-content-center">
                        <div class="col-lg-8">
                            <div class="card">
                                <div class="card-body">
                                    <form id="bookingForm">
                                        <input type="hidden" name="patient_id"
                                            value="<?php echo $_SESSION['user_id']; // This likely needs mapping to patient_id in JS or Backend but let's pass session user_id to be mapped ?>">
                                        <!-- Real patient_id lookup should happen in backend or we fetch here -->

                                        <?php
                                        // Fetch actual patient ID
                                        $u_id = $_SESSION['user_id'];
                                        $pid_res = $conn->query("SELECT patient_id FROM patients WHERE user_id=$u_id")->fetch_assoc();
                                        $real_pid = $pid_res['patient_id'] ?? 0;
                                        ?>
                                        <input type="hidden" name="patient_id" value="<?php echo $real_pid; ?>">
                                        <input type="hidden" name="reschedule_id" value="<?php echo $reschedule_id; ?>">

                                        <div class="mb-3">
                                            <label class="form-label">Service Type</label>
                                            <select class="form-select" name="appointment_type" required>
                                                <option value="CONSULTATION">General Consultation</option>
                                                <option value="HEARING_TEST">Hearing Test / Audiometry</option>
                                                <option value="FOLLOW_UP">Follow-up Visit</option>
                                            </select>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Select Doctor (Optional)</label>
                                            <select class="form-select select2" name="doctor_id" id="doctor_select">
                                                <option value="">Any Available Doctor</option>
                                                <?php
                                                $docs = $conn->query("SELECT d.doctor_id, u.full_name, d.specialization FROM doctors d JOIN users u ON d.user_id = u.user_id WHERE d.is_active=1");
                                                while ($d = $docs->fetch_assoc()):
                                                    ?>
                                                    <option value="<?php echo $d['doctor_id']; ?>">Dr.
                                                        <?php echo htmlspecialchars($d['full_name']) . " (" . $d['specialization'] . ")"; ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Preferred Date</label>
                                                <input type="text" class="form-control" id="dateData"
                                                    name="appointment_date" placeholder="Select Date" required>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Time Slot</label>
                                                <select class="form-select" name="appointment_time" id="timeSlot"
                                                    required>
                                                    <option value="">Select Date First</option>
                                                </select>
                                                <!-- Hidden slot_id needed by backend -->
                                                <input type="hidden" name="slot_id" id="slot_id">
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Chief Complaint / Reason</label>
                                            <textarea class="form-control" name="chief_complaint" rows="3" required
                                                placeholder="Briefly describe your symptoms..."></textarea>
                                        </div>

                                        <button type="submit" class="btn btn-primary w-100">Confirm Booking</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/select2/js/select2.min.js"></script>
    <script src="assets/libs/flatpickr/flatpickr.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script>
        $('.select2').select2();

        flatpickr("#dateData", {
            minDate: "today",
            disable: [
                function (date) {
                    return (date.getDay() === 0); // Disable Sundays if needed
                }
            ],
            onChange: function (selectedDates, dateStr, instance) {
                fetchSlots(dateStr);
            }
        });

        function fetchSlots(date) {
            let docId = $('#doctor_select').val();
            // Using existing logic to get slots
            $.get('ajax/get_available_slots.php', { date: date, doctor_id: docId }, function (data) {
                let options = '<option value="">Select Time</option>';
                if (data.length > 0) {
                    data.forEach(slot => {
                        options += `<option value="${slot.start_time}" data-id="${slot.slot_id}">${slot.start_time} - ${slot.end_time}</option>`;
                    });
                } else {
                    options = '<option value="">No slots available</option>';
                }
                $('#timeSlot').html(options);
            }, 'json');
        }

        $('#timeSlot').change(function () {
            let slotId = $(this).find(':selected').data('id');
            $('#slot_id').val(slotId);
        });

        $('#bookingForm').submit(function (e) {
            e.preventDefault();
            let formData = $(this).serialize();
            formData += '&booking_source=ONLINE'; // Ensure source is set

            $.post('ajax/book_appointment.php', formData, function (res) {
                if (res.success) {
                    Swal.fire('Success', 'Appointment booked successfully!', 'success').then(() => {
                        window.location.href = 'patient_appointment_history.php';
                    });
                } else {
                    Swal.fire('Error', res.message, 'error');
                }
            }, 'json');
        });
    </script>
</body>

</html>