<?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();
}

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

// Fetch appointment details
$sql = "SELECT 
            a.*,
            p.patient_number,
            pu.full_name as patient_name,
            pu.phone_primary as patient_phone,
            pu.email as patient_email,
            pu.gender as patient_gender,
            pu.date_of_birth as patient_dob,
            du.full_name as doctor_name,
            d.specialization as doctor_specialization,
            d.consultation_fee,
            pay.payment_id,
            pay.amount as payment_amount,
            pay.status as payment_status,
            pay.payment_method,
            pay.payment_date as paid_at,
            s.start_time as slot_start_time,
            s.end_time as slot_end_time,
            s.room_number
        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
        LEFT JOIN appointment_slots s ON a.slot_id = s.slot_id
        LEFT JOIN payments pay ON a.appointment_id = pay.visit_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=no_record');
    exit();
}

// Role-specific checks
if (in_array($_SESSION['role_code'], ['ENT_DOCTOR', 'ENT_CONSULTANT'])) {
    $doctor_check_sql = "SELECT doctor_id FROM doctors WHERE user_id = ?";
    $doctor_stmt = $conn->prepare($doctor_check_sql);
    $doctor_stmt->bind_param("i", $_SESSION['user_id']);
    $doctor_stmt->execute();
    $doctor_result = $doctor_stmt->get_result()->fetch_assoc();
    $doctor_stmt->close();
    
    if ($doctor_result && $appointment['doctor_id'] != $doctor_result['doctor_id']) {
        header('Location: list_appointments.php?error=unauthorized');
        exit();
    }
}

// Calculate patient age
$patient_age = null;
if ($appointment['patient_dob']) {
    $birth_date = new DateTime($appointment['patient_dob']);
    $today = new DateTime();
    $patient_age = $today->diff($birth_date)->y;
}

// Get all active doctors for reschedule dropdown
$doctors_sql = "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
                ORDER BY u.full_name";
$doctors = $conn->query($doctors_sql);

// Status colors
$status_colors = [
    'SCHEDULED' => 'info',
    'CONFIRMED' => 'primary',
    'CHECKED_IN' => 'warning',
    'IN_PROGRESS' => 'secondary',
    'COMPLETED' => 'success',
    'CANCELLED' => 'danger',
    'NO_SHOW' => 'warning'
];
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View 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>
        :root {
            --primary-color: #4f46e5;
            --success-color: #10b981;
            --warning-color: #f59e0b;
            --danger-color: #ef4444;
            --info-color: #06b6d4;
            --secondary-color: #6366f1;
        }
        
        .appointment-hero {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            color: white;
            border-radius: 16px;
            padding: 2rem;
            margin-bottom: 2rem;
            position: relative;
            overflow: hidden;
        }
        
        .appointment-hero::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -10%;
            width: 300px;
            height: 300px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
        }
        
        .appointment-hero::after {
            content: '';
            position: absolute;
            bottom: -30%;
            left: -5%;
            width: 200px;
            height: 200px;
            background: rgba(255, 255, 255, 0.08);
            border-radius: 50%;
        }
        
        .hero-content {
            position: relative;
            z-index: 1;
        }
        
        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 1rem;
            border-radius: 50px;
            font-weight: 600;
            font-size: 0.875rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .status-badge i {
            font-size: 1rem;
        }
        
        .info-card {
            background: white;
            border-radius: 16px;
            padding: 1.5rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            border: 1px solid rgba(0, 0, 0, 0.05);
            margin-bottom: 1.5rem;
            transition: transform 0.2s, box-shadow 0.2s;
        }
        
        .info-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
        }
        
        .card-header-custom {
            display: flex;
            align-items: center;
            gap: 1rem;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid #f1f5f9;
        }
        
        .card-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
        }
        
        .card-icon.patient { background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); color: white; }
        .card-icon.doctor { background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; }
        .card-icon.payment { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); color: white; }
        .card-icon.info { background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%); color: white; }
        
        .detail-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f8fafc;
        }
        
        .detail-row:last-child {
            border-bottom: none;
            padding-bottom: 0;
        }
        
        .detail-label {
            font-weight: 600;
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .detail-value {
            color: #1e293b;
            font-weight: 500;
            text-align: right;
        }
        
        .action-bar {
            background: white;
            border-radius: 16px;
            padding: 1.5rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            margin-bottom: 1.5rem;
        }
        
        .action-btn {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.625rem 1.25rem;
            border: none;
            border-radius: 10px;
            font-weight: 600;
            font-size: 0.875rem;
            cursor: pointer;
            transition: all 0.2s;
            text-decoration: none;
            margin: 0.25rem;
        }
        
        .action-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.15);
        }
        
        .btn-primary { background: var(--primary-color); color: white; }
        .btn-success { background: var(--success-color); color: white; }
        .btn-warning { background: var(--warning-color); color: white; }
        .btn-danger { background: var(--danger-color); color: white; }
        .btn-secondary { background: #64748b; color: white; }
        .btn-outline { background: white; color: #64748b; border: 2px solid #e2e8f0; }
        
        .timeline-section {
            background: white;
            border-radius: 16px;
            padding: 1.5rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .timeline {
            position: relative;
            padding-left: 2rem;
        }
        
        .timeline::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            width: 3px;
            background: linear-gradient(to bottom, var(--primary-color), var(--secondary-color));
            border-radius: 3px;
        }
        
        .timeline-item {
            position: relative;
            padding-bottom: 1.5rem;
        }
        
        .timeline-item:last-child {
            padding-bottom: 0;
        }
        
        .timeline-dot {
            position: absolute;
            left: -2.4rem;
            width: 16px;
            height: 16px;
            border-radius: 50%;
            background: white;
            border: 3px solid var(--primary-color);
        }
        
        .timeline-dot.active {
            background: var(--success-color);
            border-color: var(--success-color);
            box-shadow: 0 0 0 4px rgba(16, 185, 129, 0.2);
        }
        
        .timeline-content {
            background: #f8fafc;
            padding: 1rem;
            border-radius: 10px;
        }
        
        .notes-area {
            width: 100%;
            min-height: 120px;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            padding: 1rem;
            font-size: 0.875rem;
            resize: vertical;
            transition: border-color 0.2s;
        }
        
        .notes-area:focus {
            outline: none;
            border-color: var(--primary-color);
        }
        
        /* Modal Styles */
        .modal-content {
            border-radius: 16px;
            border: none;
        }
        
        .modal-header {
            background: linear-gradient(135deg, var(--warning-color) 0%, #d97706 100%);
            color: white;
            border-radius: 16px 16px 0 0;
            padding: 1.5rem;
        }
        
        .modal-body {
            padding: 2rem;
        }
        
        .time-slot {
            background: white;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            padding: 0.75rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s;
            margin-bottom: 0.5rem;
        }
        
        .time-slot:hover:not(.unavailable) {
            border-color: var(--primary-color);
            background: #eff6ff;
            transform: translateY(-2px);
        }
        
        .time-slot.selected {
            border-color: var(--success-color);
            background: #d1fae5;
            font-weight: 600;
        }
        
        .time-slot.unavailable {
            background: #f1f5f9;
            cursor: not-allowed;
            opacity: 0.6;
        }
        
        .alert-custom {
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 1rem;
            border-left: 4px solid;
        }
        
        .alert-info-custom {
            background: #dbeafe;
            border-color: var(--info-color);
            color: #1e40af;
        }
        
        @media (max-width: 768px) {
            .appointment-hero {
                padding: 1.5rem;
            }
            
            .action-btn {
                width: 100%;
                justify-content: center;
                margin: 0.25rem 0;
            }
        }
    </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">Appointment Details</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">View</li>
                                    </ol>
                                </div>
                                <div>
                                    <a href="list_appointments.php" class="action-btn btn-outline">
                                        <i class="ri-arrow-left-line"></i> Back to List
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Hero Section -->
                    <div class="appointment-hero">
                        <div class="hero-content">
                            <div class="row align-items-center">
                                <div class="col-md-8">
                                    <div class="d-flex align-items-center gap-2 mb-2">
                                        <i class="ri-calendar-event-fill" style="font-size: 1.5rem;"></i>
                                        <h2 class="mb-0"><?php echo htmlspecialchars($appointment['appointment_number']); ?></h2>
                                    </div>
                                    <p class="mb-2" style="opacity: 0.95; font-size: 1.1rem;">
                                        <i class="ri-user-line me-1"></i> <?php echo htmlspecialchars($appointment['patient_name']); ?>
                                    </p>
                                    <p class="mb-0" style="opacity: 0.9;">
                                        <i class="ri-calendar-line me-1"></i>
                                        <?php echo date('l, F d, Y', strtotime($appointment['appointment_date'])); ?> 
                                        at <?php echo date('h:i A', strtotime($appointment['appointment_time'])); ?>
                                    </p>
                                </div>
                                <div class="col-md-4 text-md-end mt-3 mt-md-0">
                                    <span class="status-badge" style="background: rgba(255, 255, 255, 0.2); backdrop-filter: blur(10px);">
                                        <i class="ri-checkbox-circle-line"></i>
                                        <?php echo str_replace('_', ' ', $appointment['status']); ?>
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Patient Information -->
                        <div class="col-lg-4 col-md-6">
                            <div class="info-card">
                                <div class="card-header-custom">
                                    <div class="card-icon patient">
                                        <i class="ri-user-line"></i>
                                    </div>
                                    <div>
                                        <h6 class="mb-0">Patient Information</h6>
                                        <small class="text-muted">Personal details</small>
                                    </div>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Full Name</span>
                                    <span class="detail-value"><?php echo htmlspecialchars($appointment['patient_name']); ?></span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Patient No.</span>
                                    <span class="detail-value"><?php echo htmlspecialchars($appointment['patient_number']); ?></span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Phone</span>
                                    <span class="detail-value"><?php echo htmlspecialchars($appointment['patient_phone'] ?? 'N/A'); ?></span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Email</span>
                                    <span class="detail-value"><?php echo htmlspecialchars($appointment['patient_email'] ?? 'N/A'); ?></span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Gender</span>
                                    <span class="detail-value"><?php echo ucfirst($appointment['patient_gender'] ?? 'N/A'); ?></span>
                                </div>
                                <?php if ($patient_age): ?>
                                <div class="detail-row">
                                    <span class="detail-label">Age</span>
                                    <span class="detail-value"><?php echo $patient_age; ?> years</span>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Doctor Information -->
                        <div class="col-lg-4 col-md-6">
                            <div class="info-card">
                                <div class="card-header-custom">
                                    <div class="card-icon doctor">
                                        <i class="ri-stethoscope-line"></i>
                                    </div>
                                    <div>
                                        <h6 class="mb-0">Doctor Information</h6>
                                        <small class="text-muted">Healthcare provider</small>
                                    </div>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Name</span>
                                    <span class="detail-value">Dr. <?php echo htmlspecialchars($appointment['doctor_name']); ?></span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Specialization</span>
                                    <span class="detail-value"><?php echo htmlspecialchars($appointment['doctor_specialization']); ?></span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Consultation Fee</span>
                                    <span class="detail-value">KES <?php echo number_format($appointment['consultation_fee'] ?? 0, 2); ?></span>
                                </div>
                                <?php if ($appointment['slot_start_time']): ?>
                                <div class="detail-row">
                                    <span class="detail-label">Time Slot</span>
                                    <span class="detail-value">
                                        <?php echo date('h:i A', strtotime($appointment['slot_start_time'])); ?> - 
                                        <?php echo date('h:i A', strtotime($appointment['slot_end_time'])); ?>
                                    </span>
                                </div>
                                <?php endif; ?>
                                <?php if ($appointment['room_number']): ?>
                                <div class="detail-row">
                                    <span class="detail-label">Room</span>
                                    <span class="detail-value"><?php echo htmlspecialchars($appointment['room_number']); ?></span>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Payment Information -->
                        <div class="col-lg-4 col-md-12">
                            <div class="info-card">
                                <div class="card-header-custom">
                                    <div class="card-icon payment">
                                        <i class="ri-money-dollar-circle-line"></i>
                                    </div>
                                    <div>
                                        <h6 class="mb-0">Payment Information</h6>
                                        <small class="text-muted">Billing details</small>
                                    </div>
                                </div>
                                <?php if ($appointment['payment_id']): ?>
                                <div class="detail-row">
                                    <span class="detail-label">Amount</span>
                                    <span class="detail-value" style="font-size: 1.125rem; font-weight: 700; color: var(--success-color);">
                                        KES <?php echo number_format($appointment['payment_amount'] ?? 0, 2); ?>
                                    </span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Status</span>
                                    <span class="detail-value">
                                        <span class="badge" style="background: #d1fae5; color: #065f46; padding: 0.375rem 0.75rem; border-radius: 6px;">
                                            <i class="ri-check-line me-1"></i>
                                            <?php echo ucwords(str_replace('_', ' ', $appointment['payment_status'] ?? 'Pending')); ?>
                                        </span>
                                    </span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Method</span>
                                    <span class="detail-value"><?php echo htmlspecialchars($appointment['payment_method'] ?? 'N/A'); ?></span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Paid On</span>
                                    <span class="detail-value">
                                        <?php echo $appointment['paid_at'] ? date('M d, Y h:i A', strtotime($appointment['paid_at'])) : 'N/A'; ?>
                                    </span>
                                </div>
                                <?php else: ?>
                                <div class="text-center py-3">
                                    <i class="ri-money-dollar-circle-line" style="font-size: 3rem; color: #cbd5e1;"></i>
                                    <p class="text-muted mt-2 mb-0">No payment recorded</p>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Appointment Details -->
                    <div class="row">
                        <div class="col-12">
                            <div class="info-card">
                                <div class="card-header-custom">
                                    <div class="card-icon info">
                                        <i class="ri-file-text-line"></i>
                                    </div>
                                    <div>
                                        <h6 class="mb-0">Appointment Details</h6>
                                        <small class="text-muted">Complete information</small>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="detail-row">
                                            <span class="detail-label">Appointment Type</span>
                                            <span class="detail-value">
                                                <span class="badge" style="background: #dbeafe; color: #1e40af; padding: 0.375rem 0.75rem; border-radius: 6px;">
                                                    <?php echo str_replace('_', ' ', ucwords($appointment['appointment_type'])); ?>
                                                </span>
                                            </span>
                                        </div>
                                        <div class="detail-row">
                                            <span class="detail-label">Booking Source</span>
                                            <span class="detail-value"><?php echo str_replace('_', ' ', ucwords($appointment['booking_source'])); ?></span>
                                        </div>
                                        <div class="detail-row">
                                            <span class="detail-label">Status</span>
                                            <span class="detail-value">
                                                <span class="badge badge-<?php echo $status_colors[$appointment['status']] ?? 'secondary'; ?>" 
                                                      style="padding: 0.375rem 0.75rem; border-radius: 6px;">
                                                    <?php echo str_replace('_', ' ', ucwords($appointment['status'])); ?>
                                                </span>
                                            </span>
                                        </div>
                                        <div class="detail-row">
                                            <span class="detail-label">Created On</span>
                                            <span class="detail-value"><?php echo date('M d, Y h:i A', strtotime($appointment['created_at'])); ?></span>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <?php if ($appointment['chief_complaint']): ?>
                                        <div class="detail-row">
                                            <span class="detail-label">Chief Complaint</span>
                                            <span class="detail-value"><?php echo htmlspecialchars($appointment['chief_complaint']); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        <?php if ($appointment['special_requirements']): ?>
                                        <div class="detail-row">
                                            <span class="detail-label">Special Requirements</span>
                                            <span class="detail-value"><?php echo htmlspecialchars($appointment['special_requirements']); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        <div class="detail-row">
                                            <span class="detail-label">Duration</span>
                                            <span class="detail-value"><?php echo $appointment['estimated_duration'] ?? 30; ?> minutes</span>
                                        </div>
                                        <?php if ($appointment['updated_at'] && $appointment['updated_at'] != $appointment['created_at']): ?>
                                        <div class="detail-row">
                                            <span class="detail-label">Last Updated</span>
                                            <span class="detail-value"><?php echo date('M d, Y h:i A', strtotime($appointment['updated_at'])); ?></span>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Action Bar -->
                    <div class="row">
                        <div class="col-12">
                            <div class="action-bar">
                                <h6 class="mb-3"><i class="ri-flashlight-line me-2"></i>Quick Actions</h6>
                                <div class="d-flex flex-wrap">
                                    <?php if (in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'RECEPTIONIST', 'NURSE']) && $appointment['status'] == 'SCHEDULED'): ?>
                                    <button onclick="updateStatus('CONFIRMED')" class="action-btn btn-primary">
                                        <i class="ri-check-line"></i> Confirm Appointment
                                    </button>
                                    <?php endif; ?>
                                    
                                    <?php if (in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'RECEPTIONIST', 'NURSE']) && in_array($appointment['status'], ['SCHEDULED', 'CONFIRMED'])): ?>
                                    <button onclick="updateStatus('CHECKED_IN')" class="action-btn btn-success">
                                        <i class="ri-user-check-line"></i> Check-In Patient
                                    </button>
                                    <?php endif; ?>
                                    
                                    <?php if (in_array($_SESSION['role_code'], ['ENT_DOCTOR', 'ENT_CONSULTANT']) && $appointment['status'] == 'CHECKED_IN'): ?>
                                    <button onclick="updateStatus('IN_PROGRESS')" class="action-btn btn-warning">
                                        <i class="ri-play-circle-line"></i> Start Consultation
                                    </button>
                                    <?php endif; ?>
                                    
                                    <?php if (in_array($_SESSION['role_code'], ['ENT_DOCTOR', 'ENT_CONSULTANT']) && $appointment['status'] == 'IN_PROGRESS'): ?>
                                    <button onclick="updateStatus('COMPLETED')" class="action-btn btn-success">
                                        <i class="ri-check-double-line"></i> Complete
                                    </button>
                                    <?php endif; ?>
                                    
                                    <?php if (in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'RECEPTIONIST']) && in_array($appointment['status'], ['SCHEDULED', 'CONFIRMED'])): ?>
                                    <button onclick="openRescheduleModal()" class="action-btn btn-secondary">
                                        <i class="ri-calendar-line"></i> Reschedule
                                    </button>
                                    <button onclick="cancelAppointment(<?php echo $appointment_id; ?>)" class="action-btn btn-danger">
                                        <i class="ri-close-line"></i> Cancel
                                    </button>
                                    <?php endif; ?>
                                    
                                    <?php if (!$appointment['payment_id'] && in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'RECEPTIONIST'])): ?>
                                    <a href="process_payment.php?appointment_id=<?php echo $appointment_id; ?>" class="action-btn btn-warning">
                                        <i class="ri-money-dollar-circle-line"></i> Process Payment
                                    </a>
                                    <?php endif; ?>
                                    
                                    <button onclick="sendReminder()" class="action-btn btn-outline">
                                        <i class="ri-mail-send-line"></i> Send Reminder
                                    </button>
                                    
                                    <button onclick="printAppointment()" class="action-btn btn-outline">
                                        <i class="ri-printer-line"></i> Print
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Timeline and Notes -->
                    <div class="row">
                        <div class="col-lg-6">
                            <div class="timeline-section">
                                <div class="card-header-custom">
                                    <div class="card-icon" style="background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%); color: white;">
                                        <i class="ri-time-line"></i>
                                    </div>
                                    <div>
                                        <h6 class="mb-0">Appointment Timeline</h6>
                                        <small class="text-muted">Status history</small>
                                    </div>
                                </div>
                                <div class="timeline">
                                    <div class="timeline-item">
                                        <div class="timeline-dot active"></div>
                                        <div class="timeline-content">
                                            <strong>Appointment Scheduled</strong>
                                            <p class="mb-0 small text-muted">
                                                <?php echo date('M d, Y h:i A', strtotime($appointment['created_at'])); ?>
                                            </p>
                                        </div>
                                    </div>
                                    <?php if ($appointment['status'] != 'SCHEDULED'): ?>
                                    <div class="timeline-item">
                                        <div class="timeline-dot active"></div>
                                        <div class="timeline-content">
                                            <strong><?php echo str_replace('_', ' ', ucwords($appointment['status'])); ?></strong>
                                            <p class="mb-0 small text-muted">
                                                <?php echo $appointment['updated_at'] ? date('M d, Y h:i A', strtotime($appointment['updated_at'])) : 'N/A'; ?>
                                            </p>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                    <?php if ($appointment['status'] == 'COMPLETED'): ?>
                                    <div class="timeline-item">
                                        <div class="timeline-dot active"></div>
                                        <div class="timeline-content">
                                            <strong>Consultation Completed</strong>
                                            <p class="mb-0 small text-muted">
                                                <?php echo $appointment['completed_at'] ? date('M d, Y h:i A', strtotime($appointment['completed_at'])) : 'N/A'; ?>
                                            </p>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <?php if (in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ENT_DOCTOR', 'ENT_CONSULTANT', 'NURSE'])): ?>
                        <div class="col-lg-6">
                            <div class="info-card">
                                <div class="card-header-custom">
                                    <div class="card-icon" style="background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%); color: white;">
                                        <i class="ri-file-list-line"></i>
                                    </div>
                                    <div>
                                        <h6 class="mb-0">Clinical Notes</h6>
                                        <small class="text-muted">Add observations</small>
                                    </div>
                                </div>
                                <textarea class="notes-area" placeholder="Add clinical notes, observations, or special instructions..." 
                                          onblur="saveNotes(this.value)"><?php echo htmlspecialchars($appointment['notes'] ?? ''); ?></textarea>
                                <small class="text-muted"><i class="ri-information-line"></i> Notes are automatically saved</small>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Reschedule Modal -->
    <div class="modal fade" id="rescheduleModal" tabindex="-1" aria-labelledby="rescheduleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <div>
                        <h5 class="modal-title mb-1" id="rescheduleModalLabel">
                            <i class="ri-calendar-line me-2"></i>Reschedule Appointment
                        </h5>
                        <p class="mb-0 small" style="opacity: 0.9;">
                            <?php echo htmlspecialchars($appointment['appointment_number']); ?> • <?php echo htmlspecialchars($appointment['patient_name']); ?>
                        </p>
                    </div>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <!-- Current Appointment Info -->
                    <div class="alert-custom alert-info-custom">
                        <div class="d-flex align-items-start gap-2">
                            <i class="ri-information-line" style="font-size: 1.25rem;"></i>
                            <div>
                                <strong>Current Appointment</strong>
                                <p class="mb-0 small">
                                    <?php echo date('l, F d, Y', strtotime($appointment['appointment_date'])); ?> at 
                                    <?php echo date('h:i A', strtotime($appointment['appointment_time'])); ?> with 
                                    Dr. <?php echo htmlspecialchars($appointment['doctor_name']); ?>
                                </p>
                            </div>
                        </div>
                    </div>

                    <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">
                                <i class="ri-stethoscope-line me-1"></i>Select Doctor
                            </label>
                            <select class="form-select" name="doctor_id" id="doctorSelect" required onchange="loadAvailability()">
                                <option value="">Choose doctor...</option>
                                <?php 
                                $doctors->data_seek(0); // Reset pointer
                                while($doctor = $doctors->fetch_assoc()): 
                                ?>
                                <option value="<?php echo $doctor['doctor_id']; ?>" 
                                        <?php echo $doctor['doctor_id'] == $appointment['doctor_id'] ? 'selected' : ''; ?>>
                                    Dr. <?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">
                                <i class="ri-calendar-2-line me-1"></i>Select New Date <span class="text-danger">*</span>
                            </label>
                            <input type="text" class="form-control" id="appointmentDate" name="appointment_date" 
                                   placeholder="Click to select date" required readonly style="background: white;">
                        </div>

                        <!-- Time Slots -->
                        <div id="timeSlotsSection" style="display: none;">
                            <label class="form-label fw-bold">
                                <i class="ri-time-line me-1"></i>Available Time Slots <span class="text-danger">*</span>
                            </label>
                            <div id="timeSlots" class="row g-2 mb-4"></div>
                        </div>

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

                        <!-- Submit Buttons -->
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-warning flex-grow-1" id="submitBtn" disabled>
                                <i class="ri-calendar-check-line me-2"></i>Confirm Reschedule
                            </button>
                            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                                Cancel
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </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>
        const appointmentId = <?php echo $appointment_id; ?>;
        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 openRescheduleModal() {
            $('#rescheduleModal').modal('show');
            loadAvailability();
        }

        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-4"><div class="spinner-border text-primary"></div><p class="mt-2 text-muted">Loading available slots...</p></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-warning text-center"><i class="ri-calendar-close-line me-2"></i>No available slots for this date. Please choose another 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})">
                                    <i class="ri-time-line d-block mb-1"></i>
                                    <div class="fw-bold">${slot.start_time}</div>
                                    <small class="text-muted">${slot.is_available ? 'Available' : 'Booked'}</small>
                                </div>
                            </div>
                        `;
                    });

                    $('#timeSlots').html(html);
                },
                error: function() {
                    $('#timeSlots').html('<div class="col-12"><div class="alert alert-danger"><i class="ri-error-warning-line me-2"></i>Failed to load time slots. Please try again.</div></div>');
                }
            });
        }

        function selectTimeSlot(element, isAvailable) {
            if (!isAvailable) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Slot Unavailable',
                    text: 'This time slot is already booked. Please select another slot.',
                    confirmButtonColor: 'var(--warning-color)'
                });
                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({
                    icon: 'error',
                    title: 'Time Slot Required',
                    text: 'Please select a time slot for the rescheduled appointment.',
                    confirmButtonColor: 'var(--danger-color)'
                });
                return;
            }

            const doctorName = $('#doctorSelect option:selected').text();
            const formData = $(this).serialize() + '&appointment_time=' + selectedTimeSlot;

            Swal.fire({
                title: 'Confirm Reschedule',
                html: `
                    <div class="text-start p-3" style="background: #f8fafc; border-radius: 10px;">
                        <p class="mb-2"><strong>New Doctor:</strong> ${doctorName}</p>
                        <p class="mb-2"><strong>New Date:</strong> ${new Date(selectedDate).toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}</p>
                        <p class="mb-0"><strong>New Time:</strong> ${selectedTimeSlot}</p>
                    </div>
                    <p class="mt-3 mb-0">Are you sure you want to reschedule this appointment?</p>
                `,
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: '<i class="ri-check-line me-1"></i> Yes, Reschedule',
                cancelButtonText: 'Cancel',
                confirmButtonColor: 'var(--warning-color)',
                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: 'Appointment Rescheduled!',
                            text: result.value.message,
                            confirmButtonColor: 'var(--success-color)'
                        }).then(() => {
                            window.location.reload();
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Reschedule Failed',
                            text: result.value.message,
                            confirmButtonColor: 'var(--danger-color)'
                        });
                    }
                }
            });
        });

        function updateStatus(newStatus) {
            const statusLabels = {
                'CONFIRMED': 'Confirm Appointment',
                'CHECKED_IN': 'Check-In Patient',
                'IN_PROGRESS': 'Start Consultation',
                'COMPLETED': 'Complete Appointment'
            };
            const label = statusLabels[newStatus] || 'Update Status';

            Swal.fire({
                title: label,
                text: "This will update the appointment status.",
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, Update',
                confirmButtonColor: 'var(--primary-color)'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: 'ajax/update_appointment_status.php',
                        method: 'POST',
                        data: { appointment_id: appointmentId, status: newStatus },
                        dataType: 'json',
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Status Updated',
                                    text: response.message,
                                    confirmButtonColor: 'var(--success-color)'
                                }).then(() => {
                                    window.location.reload();
                                });
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Update Failed',
                                    text: response.message,
                                    confirmButtonColor: 'var(--danger-color)'
                                });
                            }
                        },
                        error: function() {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: 'Failed to update appointment status',
                                confirmButtonColor: 'var(--danger-color)'
                            });
                        }
                    });
                }
            });
        }

        function cancelAppointment(id) {
            Swal.fire({
                title: 'Cancel Appointment?',
                text: "This action cannot be undone",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: 'var(--danger-color)',
                confirmButtonText: 'Yes, Cancel It',
                input: 'textarea',
                inputLabel: 'Cancellation Reason',
                inputPlaceholder: 'Please provide a reason for cancellation...',
                inputValidator: (value) => {
                    if (!value) {
                        return 'Cancellation reason is required';
                    }
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: 'ajax/cancel_appointment.php',
                        method: 'POST',
                        data: {
                            appointment_id: id,
                            cancellation_reason: result.value
                        },
                        dataType: 'json',
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Appointment Cancelled',
                                    text: response.message,
                                    confirmButtonColor: 'var(--success-color)'
                                }).then(() => {
                                    window.location.href = 'list_appointments.php';
                                });
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Cancellation Failed',
                                    text: response.message,
                                    confirmButtonColor: 'var(--danger-color)'
                                });
                            }
                        },
                        error: function() {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: 'Failed to cancel appointment',
                                confirmButtonColor: 'var(--danger-color)'
                            });
                        }
                    });
                }
            });
        }

        function saveNotes(notes) {
            $.ajax({
                url: 'ajax/update_appointment_notes.php',
                method: 'POST',
                data: { appointment_id: appointmentId, notes: notes },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        // Show subtle success indicator
                        const Toast = Swal.mixin({
                            toast: true,
                            position: 'bottom-end',
                            showConfirmButton: false,
                            timer: 2000,
                            timerProgressBar: true
                        });
                        Toast.fire({
                            icon: 'success',
                            title: 'Notes saved'
                        });
                    }
                }
            });
        }

        function sendReminder() {
            Swal.fire({
                title: 'Send Reminder',
                text: 'Send appointment reminder to patient?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Send Reminder',
                confirmButtonColor: 'var(--info-color)'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: 'ajax/send_appointment_reminder.php',
                        method: 'POST',
                        data: { appointment_id: appointmentId },
                        dataType: 'json',
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Reminder Sent',
                                    text: response.message,
                                    confirmButtonColor: 'var(--success-color)'
                                });
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Send Failed',
                                    text: response.message,
                                    confirmButtonColor: 'var(--danger-color)'
                                });
                            }
                        }
                    });
                }
            });
        }

        function printAppointment() {
            window.print();
        }

        // Show messages from URL params
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('error') === 'no_record') {
            Swal.fire({
                icon: 'error',
                title: 'Not Found',
                text: 'Appointment not found',
                confirmButtonColor: 'var(--danger-color)'
            });
        }
        if (urlParams.get('success') === 'rescheduled') {
            Swal.fire({
                icon: 'success',
                title: 'Rescheduled Successfully',
                text: 'The appointment has been rescheduled',
                confirmButtonColor: 'var(--success-color)'
            });
        }
    </script>

    <style media="print">
        .page-title-box, .action-bar, .main-menu, .topnav, footer {
            display: none !important;
        }
        .info-card {
            page-break-inside: avoid;
        }
    </style>
</body>
</html>