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

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

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

// Get appointment ID
$appointment_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$appointment_id) {
    header('Location: list_appointments.php');
    exit();
}

// Fetch appointment details with patient and doctor information
$appointment_sql = "SELECT 
                        a.*,
                        p.patient_number, p.blood_group, p.allergies, p.chronic_conditions,
                        u_patient.full_name as patient_name, u_patient.email as patient_email,
                        u_patient.phone_primary as patient_phone, u_patient.gender as patient_gender,
                        u_patient.date_of_birth, u_patient.national_id,
                        TIMESTAMPDIFF(YEAR, u_patient.date_of_birth, CURDATE()) as patient_age,
                        u_doctor.full_name as doctor_name,
                        d.specialization, d.consultation_fee,
                        u_cancelled.full_name as cancelled_by_name,
                        u_created.full_name as created_by_name
                    FROM appointments a
                    INNER JOIN patients p ON a.patient_id = p.patient_id
                    INNER JOIN users u_patient ON p.user_id = u_patient.user_id
                    INNER JOIN doctors d ON a.doctor_id = d.doctor_id
                    INNER JOIN users u_doctor ON d.user_id = u_doctor.user_id
                    LEFT JOIN users u_cancelled ON a.cancelled_by = u_cancelled.user_id
                    LEFT JOIN users u_created ON a.created_at = u_created.created_at
                    WHERE a.appointment_id = ?";

$stmt = $conn->prepare($appointment_sql);
$stmt->bind_param('i', $appointment_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    header('Location: list_appointments.php');
    exit();
}

$appointment = $result->fetch_assoc();

// Get related visit and consultation if exists
$visit_consultation_sql = "SELECT 
                            pv.visit_id, pv.visit_number,
                            c.consultation_id, c.consultation_number, c.consultation_type,
                            c.chief_complaint, c.diagnosis_primary, c.diagnosis_secondary,
                            c.treatment_plan, c.status, c.started_at, c.completed_at,
                            u.full_name as consultation_doctor_name
                         FROM patient_visits pv
                         LEFT JOIN consultations c ON pv.visit_id = c.visit_id
                         LEFT JOIN users u ON c.doctor_id = u.user_id
                         WHERE pv.patient_id = ?
                         AND DATE(pv.registration_date) = ?
                         ORDER BY c.started_at DESC
                         LIMIT 1";
$stmt = $conn->prepare($visit_consultation_sql);
$stmt->bind_param('is', $appointment['patient_id'], $appointment['appointment_date']);
$stmt->execute();
$visit_result = $stmt->get_result();
$visit_data = $visit_result->num_rows > 0 ? $visit_result->fetch_assoc() : null;
$consultation = ($visit_data && $visit_data['consultation_id']) ? $visit_data : null;

// Get prescriptions if consultation exists
$prescriptions = [];
if ($consultation) {
    $prescription_sql = "SELECT 
                            pr.*,
                            GROUP_CONCAT(
                                CONCAT(pi.medication_name, ' - ', pi.dosage, ' (', pi.frequency, ')')
                                SEPARATOR '||'
                            ) as medications
                         FROM prescriptions pr
                         LEFT JOIN prescription_items pi ON pr.prescription_id = pi.prescription_id
                         WHERE pr.consultation_id = ?
                         GROUP BY pr.prescription_id";
    $stmt = $conn->prepare($prescription_sql);
    $stmt->bind_param('i', $consultation['consultation_id']);
    $stmt->execute();
    $prescription_result = $stmt->get_result();
    while ($row = $prescription_result->fetch_assoc()) {
        $prescriptions[] = $row;
    }
}

// Get lab orders for this patient on this appointment date
$lab_orders_sql = "SELECT 
                      lo.*,
                      u.full_name as ordered_by_name,
                      COUNT(lot.order_test_id) as tests_count
                   FROM lab_orders lo
                   LEFT JOIN users u ON lo.ordered_by = u.user_id
                   LEFT JOIN lab_order_tests lot ON lo.order_id = lot.order_id
                   WHERE lo.patient_id = ?
                   AND DATE(lo.order_date) = ?
                   GROUP BY lo.order_id";
$stmt = $conn->prepare($lab_orders_sql);
$stmt->bind_param('is', $appointment['patient_id'], $appointment['appointment_date']);
$stmt->execute();
$lab_orders = $stmt->get_result();

// Get procedures for this patient on this appointment date  
$procedures_sql = "SELECT 
                     pp.*,
                     ept.procedure_name, ept.category,
                     u.full_name as performed_by_name
                   FROM patient_procedures pp
                   LEFT JOIN ent_procedure_types ept ON pp.procedure_type_id = ept.procedure_type_id
                   LEFT JOIN users u ON pp.performed_by = u.user_id
                   WHERE pp.patient_id = ?
                   AND DATE(pp.procedure_date) = ?";
$stmt = $conn->prepare($procedures_sql);
$stmt->bind_param('is', $appointment['patient_id'], $appointment['appointment_date']);
$stmt->execute();
$procedures = $stmt->get_result();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Appointment Details')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .appointment-header {
            background: linear-gradient(135deg, #2d7a2d 0%, #26a69a 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
        }
        
        .detail-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        
        .section-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1.25rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .info-row {
            display: flex;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .info-row:last-child {
            border-bottom: none;
        }
        
        .info-label {
            width: 200px;
            font-weight: 600;
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .info-value {
            flex: 1;
            color: #1e293b;
        }
        
        .status-badge {
            padding: 0.5rem 1rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.875rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .status-SCHEDULED {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .status-CONFIRMED {
            background: #d1fae5;
            color: #065f46;
        }
        
        .status-CHECKED_IN {
            background: #fef3c7;
            color: #92400e;
        }
        
        .status-IN_PROGRESS {
            background: #e0e7ff;
            color: #3730a3;
        }
        
        .status-COMPLETED {
            background: #dcfce7;
            color: #166534;
        }
        
        .status-CANCELLED {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .status-NO_SHOW {
            background: #f1f5f9;
            color: #475569;
        }
        
        .timeline-item {
            position: relative;
            padding-left: 30px;
            margin-bottom: 1.5rem;
        }

        .timeline-item::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #2d7a2d;
            border: 3px solid #fff;
            box-shadow: 0 0 0 2px #2d7a2d;
        }

        .timeline-item::after {
            content: '';
            position: absolute;
            left: 5px;
            top: 12px;
            width: 2px;
            height: calc(100% + 12px);
            background: #e2e8f0;
        }

        .timeline-item:last-child::after {
            display: none;
        }

        .action-btn {
            padding: 0.5rem 1.25rem;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s;
            border: none;
            cursor: pointer;
        }

        .alert-box {
            background: #fef3c7;
            border-left: 4px solid #f59e0b;
            padding: 1rem;
            border-radius: 6px;
            margin-bottom: 1rem;
        }

        .medication-item {
            background: #f8fafc;
            border-radius: 6px;
            padding: 0.75rem;
            margin-bottom: 0.5rem;
        }
    </style>
</head>

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

                    <!-- Appointment Header -->
                    <div class="appointment-header">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <div class="d-flex align-items-center gap-3 mb-3">
                                    <h3 class="mb-0"><?php echo htmlspecialchars($appointment['appointment_number']); ?></h3>
                                    <span class="status-badge status-<?php echo $appointment['status']; ?>">
                                        <?php echo str_replace('_', ' ', $appointment['status']); ?>
                                    </span>
                                </div>
                                <div class="d-flex gap-4 flex-wrap">
                                    <div>
                                        <i class="ri-calendar-line me-1"></i>
                                        <?php echo date('l, d M Y', strtotime($appointment['appointment_date'])); ?>
                                    </div>
                                    <div>
                                        <i class="ri-time-line me-1"></i>
                                        <?php echo date('h:i A', strtotime($appointment['appointment_time'])); ?>
                                    </div>
                                    <div>
                                        <i class="ri-file-list-3-line me-1"></i>
                                        <?php echo str_replace('_', ' ', $appointment['appointment_type']); ?>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4 text-md-end mt-3 mt-md-0">
                                <?php if ($appointment['status'] === 'SCHEDULED' || $appointment['status'] === 'CONFIRMED'): ?>
                                <div class="btn-group" role="group">
                                    <?php if ($appointment['status'] === 'SCHEDULED'): ?>
                                    <button type="button" class="btn btn-light" onclick="confirmAppointment()">
                                        <i class="ri-check-line me-1"></i> Confirm
                                    </button>
                                    <?php endif; ?>
                                    <?php if ($appointment['status'] === 'CONFIRMED'): ?>
                                    <button type="button" class="btn btn-light" onclick="checkInPatient()">
                                        <i class="ri-login-box-line me-1"></i> Check-in
                                    </button>
                                    <?php endif; ?>
                                    <button type="button" class="btn btn-danger" onclick="cancelAppointment()">
                                        <i class="ri-close-line me-1"></i> Cancel
                                    </button>
                                </div>
                                <?php elseif ($appointment['status'] === 'CHECKED_IN'): ?>
                                <a href="new_consultation.php?appointment_id=<?php echo $appointment_id; ?>" class="btn btn-light">
                                    <i class="ri-user-focus-line me-1"></i> Start Consultation
                                </a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Medical Alerts -->
                    <?php if ($appointment['allergies'] || $appointment['chronic_conditions']): ?>
                    <div class="alert-box">
                        <h6 class="mb-2"><i class="ri-alert-line me-2"></i>Medical Alerts</h6>
                        <?php if ($appointment['allergies']): ?>
                        <div><strong>Allergies:</strong> <?php echo htmlspecialchars($appointment['allergies']); ?></div>
                        <?php endif; ?>
                        <?php if ($appointment['chronic_conditions']): ?>
                        <div><strong>Chronic Conditions:</strong> <?php echo htmlspecialchars($appointment['chronic_conditions']); ?></div>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>

                    <div class="row">
                        <!-- Left Column -->
                        <div class="col-lg-4">
                            <!-- Patient Information -->
                            <div class="detail-card">
                                <h5 class="section-title">
                                    <i class="ri-user-line me-2"></i>Patient Information
                                </h5>
                                <div class="info-row">
                                    <div class="info-label">Name</div>
                                    <div class="info-value">
                                        <a href="patient_profile.php?id=<?php echo $appointment['patient_id']; ?>" class="text-primary fw-bold">
                                            <?php echo htmlspecialchars($appointment['patient_name']); ?>
                                        </a>
                                    </div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Patient Number</div>
                                    <div class="info-value"><?php echo htmlspecialchars($appointment['patient_number']); ?></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Age / Gender</div>
                                    <div class="info-value">
                                        <?php echo $appointment['patient_age']; ?> years / 
                                        <?php echo ucfirst(strtolower($appointment['patient_gender'])); ?>
                                    </div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Phone</div>
                                    <div class="info-value">
                                        <i class="ri-phone-line me-1"></i>
                                        <?php echo htmlspecialchars($appointment['patient_phone']); ?>
                                    </div>
                                </div>
                                <?php if ($appointment['patient_email']): ?>
                                <div class="info-row">
                                    <div class="info-label">Email</div>
                                    <div class="info-value">
                                        <i class="ri-mail-line me-1"></i>
                                        <?php echo htmlspecialchars($appointment['patient_email']); ?>
                                    </div>
                                </div>
                                <?php endif; ?>
                                <?php if ($appointment['blood_group']): ?>
                                <div class="info-row">
                                    <div class="info-label">Blood Group</div>
                                    <div class="info-value"><strong><?php echo $appointment['blood_group']; ?></strong></div>
                                </div>
                                <?php endif; ?>
                            </div>

                            <!-- Doctor Information -->
                            <div class="detail-card">
                                <h5 class="section-title">
                                    <i class="ri-user-star-line me-2"></i>Doctor Information
                                </h5>
                                <div class="info-row">
                                    <div class="info-label">Doctor</div>
                                    <div class="info-value">
                                        <strong>Dr. <?php echo htmlspecialchars($appointment['doctor_name']); ?></strong>
                                    </div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Specialization</div>
                                    <div class="info-value"><?php echo htmlspecialchars($appointment['specialization']); ?></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Consultation Fee</div>
                                    <div class="info-value">KES <?php echo number_format($appointment['consultation_fee'], 2); ?></div>
                                </div>
                                <?php if ($appointment['room_number']): ?>
                                <div class="info-row">
                                    <div class="info-label">Room Number</div>
                                    <div class="info-value"><?php echo htmlspecialchars($appointment['room_number']); ?></div>
                                </div>
                                <?php endif; ?>
                            </div>

                            <!-- Appointment Timeline -->
                            <div class="detail-card">
                                <h5 class="section-title">
                                    <i class="ri-time-line me-2"></i>Timeline
                                </h5>
                                
                                <div class="timeline-item">
                                    <div class="fw-bold">Appointment Created</div>
                                    <div class="text-muted small">
                                        <?php echo date('d M Y, h:i A', strtotime($appointment['created_at'])); ?>
                                    </div>
                                </div>

                                <?php if ($appointment['checked_in_at']): ?>
                                <div class="timeline-item">
                                    <div class="fw-bold">Patient Checked In</div>
                                    <div class="text-muted small">
                                        <?php echo date('d M Y, h:i A', strtotime($appointment['checked_in_at'])); ?>
                                    </div>
                                </div>
                                <?php endif; ?>

                                <?php if ($appointment['completed_at']): ?>
                                <div class="timeline-item">
                                    <div class="fw-bold">Appointment Completed</div>
                                    <div class="text-muted small">
                                        <?php echo date('d M Y, h:i A', strtotime($appointment['completed_at'])); ?>
                                    </div>
                                </div>
                                <?php endif; ?>

                                <?php if ($appointment['status'] === 'CANCELLED'): ?>
                                <div class="timeline-item">
                                    <div class="fw-bold text-danger">Appointment Cancelled</div>
                                    <div class="text-muted small">
                                        By: <?php echo htmlspecialchars($appointment['cancelled_by_name'] ?: 'System'); ?>
                                    </div>
                                    <?php if ($appointment['cancellation_reason']): ?>
                                    <div class="text-muted small mt-1">
                                        Reason: <?php echo htmlspecialchars($appointment['cancellation_reason']); ?>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Right Column -->
                        <div class="col-lg-8">
                            <!-- Appointment Details -->
                            <div class="detail-card">
                                <h5 class="section-title">
                                    <i class="ri-file-text-line me-2"></i>Appointment Details
                                </h5>
                                <div class="info-row">
                                    <div class="info-label">Chief Complaint</div>
                                    <div class="info-value"><?php echo htmlspecialchars($appointment['chief_complaint']); ?></div>
                                </div>
                                <?php if ($appointment['special_requirements']): ?>
                                <div class="info-row">
                                    <div class="info-label">Special Requirements</div>
                                    <div class="info-value"><?php echo htmlspecialchars($appointment['special_requirements']); ?></div>
                                </div>
                                <?php endif; ?>
                                <div class="info-row">
                                    <div class="info-label">Booking Source</div>
                                    <div class="info-value"><?php echo str_replace('_', ' ', $appointment['booking_source']); ?></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Duration</div>
                                    <div class="info-value"><?php echo $appointment['estimated_duration']; ?> minutes</div>
                                </div>
                                <?php if ($appointment['notes']): ?>
                                <div class="info-row">
                                    <div class="info-label">Notes</div>
                                    <div class="info-value"><?php echo nl2br(htmlspecialchars($appointment['notes'])); ?></div>
                                </div>
                                <?php endif; ?>
                            </div>

                            <!-- Consultation Information -->
                            <?php if ($consultation): ?>
                            <div class="detail-card">
                                <h5 class="section-title">
                                    <i class="ri-user-focus-line me-2"></i>Consultation Details
                                </h5>
                                <div class="info-row">
                                    <div class="info-label">Consultation Number</div>
                                    <div class="info-value">
                                        <a href="consultation_details.php?id=<?php echo $consultation['consultation_id']; ?>" class="text-primary fw-bold">
                                            <?php echo htmlspecialchars($consultation['consultation_number']); ?>
                                        </a>
                                    </div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Type</div>
                                    <div class="info-value"><?php echo str_replace('_', ' ', $consultation['consultation_type']); ?></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Status</div>
                                    <div class="info-value">
                                        <span class="badge bg-<?php echo $consultation['status'] === 'COMPLETED' ? 'success' : 'warning'; ?>">
                                            <?php echo $consultation['status']; ?>
                                        </span>
                                    </div>
                                </div>
                                <?php if ($consultation['diagnosis_primary']): ?>
                                <div class="info-row">
                                    <div class="info-label">Primary Diagnosis</div>
                                    <div class="info-value"><?php echo htmlspecialchars($consultation['diagnosis_primary']); ?></div>
                                </div>
                                <?php endif; ?>
                                <?php if ($consultation['treatment_plan']): ?>
                                <div class="info-row">
                                    <div class="info-label">Treatment Plan</div>
                                    <div class="info-value"><?php echo nl2br(htmlspecialchars($consultation['treatment_plan'])); ?></div>
                                </div>
                                <?php endif; ?>
                            </div>
                            <?php endif; ?>

                            <!-- Prescriptions -->
                            <?php if (count($prescriptions) > 0): ?>
                            <div class="detail-card">
                                <h5 class="section-title">
                                    <i class="ri-medicine-bottle-line me-2"></i>Prescriptions
                                </h5>
                                <?php foreach ($prescriptions as $prescription): ?>
                                <div class="mb-3">
                                    <div class="fw-bold mb-2">
                                        <?php echo htmlspecialchars($prescription['prescription_number']); ?>
                                        <span class="badge bg-<?php echo $prescription['status'] === 'DISPENSED' ? 'success' : 'warning'; ?> ms-2">
                                            <?php echo $prescription['status']; ?>
                                        </span>
                                    </div>
                                    <?php if ($prescription['medications']): ?>
                                    <?php 
                                    $meds = explode('||', $prescription['medications']);
                                    foreach ($meds as $med): 
                                    ?>
                                    <div class="medication-item">
                                        <i class="ri-capsule-line me-2 text-success"></i>
                                        <?php echo htmlspecialchars($med); ?>
                                    </div>
                                    <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <?php endif; ?>

                            <!-- Lab Orders -->
                            <?php if ($lab_orders->num_rows > 0): ?>
                            <div class="detail-card">
                                <h5 class="section-title">
                                    <i class="ri-test-tube-line me-2"></i>Lab Orders
                                </h5>
                                <?php while ($lab = $lab_orders->fetch_assoc()): ?>
                                <div class="activity-item mb-3">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <div class="fw-bold"><?php echo htmlspecialchars($lab['order_number']); ?></div>
                                            <div class="text-muted small">
                                                <?php echo $lab['tests_count']; ?> test(s) | 
                                                <?php echo date('d M Y', strtotime($lab['order_date'])); ?>
                                            </div>
                                        </div>
                                        <span class="badge bg-<?php 
                                            echo $lab['status'] === 'COMPLETED' ? 'success' : 
                                                ($lab['status'] === 'IN_PROGRESS' ? 'warning' : 'info'); 
                                        ?>">
                                            <?php echo str_replace('_', ' ', $lab['status']); ?>
                                        </span>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                            </div>
                            <?php endif; ?>

                            <!-- Procedures -->
                            <?php if ($procedures->num_rows > 0): ?>
                            <div class="detail-card">
                                <h5 class="section-title">
                                    <i class="ri-surgical-mask-line me-2"></i>Procedures
                                </h5>
                                <?php while ($proc = $procedures->fetch_assoc()): ?>
                                <div class="activity-item mb-3">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <div class="fw-bold"><?php echo htmlspecialchars($proc['procedure_name']); ?></div>
                                            <div class="text-muted small">
                                                <?php echo htmlspecialchars($proc['category']); ?> | 
                                                <?php echo date('d M Y', strtotime($proc['procedure_date'])); ?>
                                            </div>
                                            <?php if ($proc['performed_by_name']): ?>
                                            <div class="text-muted small">
                                                By: <?php echo htmlspecialchars($proc['performed_by_name']); ?>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                        <span class="badge bg-<?php echo $proc['status'] === 'COMPLETED' ? 'success' : 'warning'; ?>">
                                            <?php echo $proc['status']; ?>
                                        </span>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                            </div>
                            <?php endif; ?>
                        </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>
        function confirmAppointment() {
            Swal.fire({
                title: 'Confirm Appointment?',
                text: 'This will update the appointment status to confirmed.',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, Confirm',
                cancelButtonText: 'Cancel',
                confirmButtonColor: '#2d7a2d'
            }).then((result) => {
                if (result.isConfirmed) {
                    updateAppointmentStatus('CONFIRMED');
                }
            });
        }

        function checkInPatient() {
            Swal.fire({
                title: 'Check-in Patient?',
                text: 'Mark patient as checked in for this appointment.',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, Check-in',
                cancelButtonText: 'Cancel',
                confirmButtonColor: '#2d7a2d'
            }).then((result) => {
                if (result.isConfirmed) {
                    updateAppointmentStatus('CHECKED_IN');
                }
            });
        }

        function cancelAppointment() {
            Swal.fire({
                title: 'Cancel Appointment?',
                input: 'textarea',inputLabel: 'Cancellation Reason',
inputPlaceholder: 'Enter reason for cancellation...',
showCancelButton: true,
confirmButtonText: 'Yes, Cancel',
cancelButtonText: 'No',
confirmButtonColor: '#dc2626',
inputValidator: (value) => {
if (!value) {
return 'Please provide a cancellation reason';
}
}
}).then((result) => {
if (result.isConfirmed) {
updateAppointmentStatus('CANCELLED', result.value);
}
});
}
function updateAppointmentStatus(status, reason = null) {
        $.ajax({
            url: 'update_appointment_status.php',
            method: 'POST',
            data: {
                appointment_id: <?php echo $appointment_id; ?>,
                status: status,
                cancellation_reason: reason
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: response.message,
                        timer: 2000,
                        showConfirmButton: false
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: response.message
                    });
                }
            },
            error: function() {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'An unexpected error occurred'
                });
            }
        });
    }
</script>

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