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

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

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

$appointment_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$appointment_id) {
    header('Location: list_appointments.php');
    exit();
}

// Get appointment details
$sql = "SELECT 
            a.*,
            p.patient_number,
            CONCAT(pu.first_name, ' ', pu.last_name) as patient_name,
            CONCAT(du.first_name, ' ', du.last_name) as doctor_name,
            d.specialization,
            d.max_daily_appointments
        FROM appointments a
        INNER JOIN patients p ON a.patient_id = p.patient_id
        INNER JOIN users pu ON p.user_id = pu.user_id
        INNER JOIN doctors d ON a.doctor_id = d.doctor_id
        INNER JOIN users du ON d.user_id = du.user_id
        WHERE a.appointment_id = ?
        LIMIT 1";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $appointment_id);
$stmt->execute();
$appointment = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$appointment) {
    header('Location: list_appointments.php?error=not_found');
    exit();
}

// Check if appointment can be rescheduled
if (!in_array($appointment['status'], ['SCHEDULED', 'CONFIRMED'])) {
    header('Location: view_appointment.php?id=' . $appointment_id . '&error=cannot_reschedule');
    exit();
}

// Get all active doctors
$doctors_sql = "SELECT 
                    d.doctor_id,
                    CONCAT(u.first_name, ' ', u.last_name) as full_name,
                    d.specialization
                FROM doctors d
                JOIN users u ON d.user_id = u.user_id
                WHERE d.is_active = 1
                ORDER BY u.first_name";
$doctors = $conn->query($doctors_sql);
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Reschedule Appointment')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    
    <style>
        .reschedule-header {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            color: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
        
        .info-box {
            background: #fef3c7;
            border: 2px solid #f59e0b;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .time-slot {
            background: white;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s;
            margin-bottom: 0.5rem;
        }
        
        .time-slot:hover:not(.unavailable) {
            border-color: #3b82f6;
            background: #eff6ff;
        }
        
        .time-slot.selected {
            border-color: #10b981;
            background: #d1fae5;
        }
        
        .time-slot.unavailable {
            background: #f1f5f9;
            cursor: not-allowed;
            opacity: 0.5;
        }
    </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">
                                <div>
                                    <h4 class="mb-sm-0">Reschedule Appointment</h4>
                                    <ol class="breadcrumb m-0 mt-2">
                                        <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">Reschedule</li>
                                    </ol>
                                </div>
                                <div>
                                    <a href="view_appointment.php?id=<?php echo $appointment_id; ?>" class="btn btn-outline-secondary">
                                        <i class="ri-arrow-left-line me-1"></i> Back
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Header -->
                    <div class="reschedule-header">
                        <h5 class="mb-1">Reschedule Appointment</h5>
                        <p class="mb-0" style="opacity: 0.9;">
                            <?php echo htmlspecialchars($appointment['appointment_number']); ?> • 
                            <?php echo htmlspecialchars($appointment['patient_name']); ?>
                        </p>
                    </div>

                    <!-- Current Appointment Info -->
                    <div class="info-box">
                        <h6 class="mb-2"><i class="ri-information-line me-1"></i> Current Appointment Details</h6>
                        <div class="row">
                            <div class="col-md-4">
                                <small class="text-muted">Date & Time</small><br>
                                <strong><?php echo date('M d, Y', strtotime($appointment['appointment_date'])); ?> at <?php echo date('h:i A', strtotime($appointment['appointment_time'])); ?></strong>
                            </div>
                            <div class="col-md-4">
                                <small class="text-muted">Doctor</small><br>
                                <strong>Dr. <?php echo htmlspecialchars($appointment['doctor_name']); ?></strong>
                            </div>
                            <div class="col-md-4">
                                <small class="text-muted">Type</small><br>
                                <strong><?php echo str_replace('_', ' ', ucwords($appointment['appointment_type'])); ?></strong>
                            </div>
                        </div>
                    </div>

                    <div class="row justify-content-center">
                        <div class="col-lg-8">
                            <div class="card">
                                <div class="card-body">
                                    <form id="rescheduleForm">
                                        <input type="hidden" name="appointment_id" value="<?php echo $appointment_id; ?>">
                                        
                                        <!-- Doctor Selection -->
                                        <div class="mb-4">
                                            <label class="form-label fw-bold">Select Doctor</label>
                                            <select class="form-select" name="doctor_id" id="doctorSelect" required onchange="loadAvailability()">
                                                <option value="">Choose doctor...</option>
                                                <?php while($doctor = $doctors->fetch_assoc()): ?>
                                                <option value="<?php echo $doctor['doctor_id']; ?>" 
                                                        <?php echo $doctor['doctor_id'] == $appointment['doctor_id'] ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($doctor['full_name']); ?> - <?php echo $doctor['specialization']; ?>
                                                </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>

                                        <!-- Date Selection -->
                                        <div class="mb-4">
                                            <label class="form-label fw-bold">New Date <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" id="appointmentDate" name="appointment_date" 
                                                   placeholder="Select date" required>
                                        </div>

                                        <!-- Time Slots -->
                                        <div id="timeSlotsSection" style="display: none;">
                                            <label class="form-label fw-bold">Available Time Slots <span class="text-danger">*</span></label>
                                            <div id="timeSlots" class="row g-2"></div>
                                        </div>

                                        <!-- Reason -->
                                        <div class="mb-4">
                                            <label class="form-label fw-bold">Reason for Rescheduling <span class="text-danger">*</span></label>
                                            <textarea class="form-control" name="reschedule_reason" rows="3" 
                                                      placeholder="Please provide reason for rescheduling..." required></textarea>
                                        </div>

                                        <!-- Submit Buttons -->
                                        <div class="d-grid gap-2">
                                            <button type="submit" class="btn btn-warning btn-lg" id="submitBtn" disabled>
                                                <i class="ri-calendar-line me-2"></i>Reschedule Appointment
                                            </button>
                                            <a href="view_appointment.php?id=<?php echo $appointment_id; ?>" 
                                               class="btn btn-outline-secondary">
                                                Cancel
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </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="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

    <script>
        let selectedDate = null;
        let selectedTimeSlot = null;
        let flatpickrInstance = null;

        // Initialize flatpickr
        flatpickrInstance = flatpickr("#appointmentDate", {
            minDate: "today",
            maxDate: new Date().fp_incr(30),
            disable: [
                function(date) {
                    return (date.getDay() === 0); // Disable Sundays
                }
            ],
            onChange: function(selectedDates, dateStr) {
                selectedDate = dateStr;
                loadTimeSlots();
            }
        });

        function loadAvailability() {
            const doctorId = $('#doctorSelect').val();
            if (doctorId) {
                $('#appointmentDate').prop('disabled', false);
            }
        }

        function loadTimeSlots() {
            const doctorId = $('#doctorSelect').val();
            
            if (!doctorId || !selectedDate) return;

            $('#timeSlotsSection').show();
            $('#timeSlots').html('<div class="col-12 text-center py-3"><div class="spinner-border text-primary"></div></div>');

            $.ajax({
                url: 'ajax/get_available_slots.php',
                type: 'POST',
                data: {
                    doctor_id: doctorId,
                    date: selectedDate
                },
                dataType: 'json',
                success: function(slots) {
                    if (slots.length === 0) {
                        $('#timeSlots').html('<div class="col-12"><div class="alert alert-info text-center">No available slots for this date.</div></div>');
                        $('#submitBtn').prop('disabled', true);
                        return;
                    }

                    let html = '';
                    slots.forEach(slot => {
                        const classes = `time-slot ${slot.is_available ? '' : 'unavailable'}`;
                        html += `
                            <div class="col-6 col-md-3">
                                <div class="${classes}" 
                                     data-time="${slot.start_time}"
                                     onclick="selectTimeSlot(this, ${slot.is_available})">
                                    <div class="fw-bold">${slot.start_time}</div>
                                </div>
                            </div>
                        `;
                    });

                    $('#timeSlots').html(html);
                },
                error: function() {
                    $('#timeSlots').html('<div class="col-12"><div class="alert alert-danger">Failed to load time slots.</div></div>');
                }
            });
        }

        function selectTimeSlot(element, isAvailable) {
            if (!isAvailable) {
                Swal.fire('Unavailable', 'This time slot is not available', 'warning');
                return;
            }

            $('.time-slot').removeClass('selected');
            element.classList.add('selected');
            
            selectedTimeSlot = element.dataset.time;
            $('#submitBtn').prop('disabled', false);
        }

        $('#rescheduleForm').on('submit', function(e) {
            e.preventDefault();

            if (!selectedTimeSlot) {
                Swal.fire('Error', 'Please select a time slot', 'error');
                return;
            }

            const formData = $(this).serialize() + '&appointment_time=' + selectedTimeSlot;

            Swal.fire({
                title: 'Confirm Reschedule',
                html: `
                    <div class="text-start">
                        <p><strong>New Date:</strong> ${selectedDate}</p>
                        <p><strong>New Time:</strong> ${selectedTimeSlot}</p>
                        <p>Are you sure you want to reschedule this appointment?</p>
                    </div>
                `,
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, reschedule',
                showLoaderOnConfirm: true,
                preConfirm: () => {
                    return $.ajax({
                        url: 'ajax/process_reschedule.php',
                        type: 'POST',
                        data: formData,
                        dataType: 'json'
                    });
                },
                allowOutsideClick: () => !Swal.isLoading()
            }).then((result) => {
                if (result.isConfirmed) {
                    if (result.value.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Rescheduled',
                            text: result.value.message
                        }).then(() => {
                            window.location.href = 'view_appointment.php?id=<?php echo $appointment_id; ?>';
                        });
                    } else {
                        Swal.fire('Error', result.value.message, 'error');
                    }
                }
            });
        });
    </script>
</body>
</html>