<?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', 'ENT_DOCTOR', 'ENT_CONSULTANT'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

// Get doctor ID
$doctor_id = isset($_GET['doctor_id']) ? (int)$_GET['doctor_id'] : 0;

// If no ID provided and user is a doctor, show their own schedule
if (!$doctor_id && in_array($_SESSION['role_code'], ['ENT_DOCTOR', 'ENT_CONSULTANT'])) {
    $doctor_id = $_SESSION['user_id'];
}

if (!$doctor_id) {
    header('Location: list_doctors.php');
    exit();
}

// Non-admin users can only view their own schedule
if (!in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN']) && $doctor_id !== $_SESSION['user_id']) {
    header('Location: dashboard.php');
    exit();
}

// Fetch doctor details
$doctor_sql = "SELECT 
                    d.*,
                    u.full_name, u.email, u.phone_primary
                FROM doctors d
                INNER JOIN users u ON d.user_id = u.user_id
                WHERE d.doctor_id = ?";

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

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

$doctor = $result->fetch_assoc();

// Parse availability schedule
$availability = json_decode($doctor['availability_schedule'], true);
if (!$availability) {
    $availability = [];
}

// Initialize empty structure for days without data
$days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
foreach ($days as $day) {
    if (!isset($availability[$day])) {
        $availability[$day] = ['sessions' => []];
    }
}

// Get upcoming appointments for the next 7 days
$upcoming_sql = "SELECT 
                    a.*,
                    u.full_name as patient_name,
                    u.phone_primary as patient_phone,
                    p.patient_number
                FROM appointments a
                INNER JOIN patients p ON a.patient_id = p.patient_id
                INNER JOIN users u ON p.user_id = u.user_id
                WHERE a.doctor_id = ?
                AND a.appointment_date >= CURDATE()
                AND a.appointment_date <= DATE_ADD(CURDATE(), INTERVAL 7 DAY)
                AND a.status IN ('SCHEDULED', 'CONFIRMED')
                ORDER BY a.appointment_date ASC, a.appointment_time ASC";
$stmt = $conn->prepare($upcoming_sql);
$stmt->bind_param('i', $doctor_id);
$stmt->execute();
$upcoming_appointments = $stmt->get_result();

// Get today's appointments
$today_sql = "SELECT 
                COUNT(*) as total_today,
                SUM(CASE WHEN status = 'COMPLETED' THEN 1 ELSE 0 END) as completed_today,
                SUM(CASE WHEN status = 'SCHEDULED' THEN 1 ELSE 0 END) as pending_today
            FROM appointments
            WHERE doctor_id = ?
            AND appointment_date = CURDATE()";
$stmt = $conn->prepare($today_sql);
$stmt->bind_param('i', $doctor_id);
$stmt->execute();
$today_stats = $stmt->get_result()->fetch_assoc();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Doctor Schedule')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .schedule-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
        }
        
        .schedule-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;
        }
        
        .schedule-card h5 {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1.25rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .day-schedule {
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            transition: all 0.3s;
            background: #f8fafc;
        }
        
        .day-schedule:hover {
            border-color: #667eea;
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.1);
        }
        
        .day-schedule.has-schedule {
            background: #f0fdf4;
            border-color: #86efac;
        }
        
        .day-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.75rem;
        }
        
        .day-name {
            font-weight: 600;
            font-size: 1rem;
            color: #1e293b;
            text-transform: capitalize;
        }
        
        .session-item {
            background: white;
            border-left: 4px solid #667eea;
            padding: 0.75rem;
            margin-bottom: 0.5rem;
            border-radius: 6px;
        }
        
        .session-item.internal {
            border-left-color: #10b981;
            background: #f0fdf4;
        }
        
        .session-item.external {
            border-left-color: #f59e0b;
            background: #fef3c7;
        }
        
        .location-badge {
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
            padding: 0.25rem 0.625rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .location-badge.internal {
            background: #d1fae5;
            color: #065f46;
        }
        
        .location-badge.external {
            background: #fef3c7;
            color: #92400e;
        }
        
        .time-slot {
            display: inline-block;
            background: #667eea;
            color: white;
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            margin-right: 0.5rem;
            margin-bottom: 0.5rem;
            font-size: 0.875rem;
            font-weight: 500;
        }
        
        .facility-info {
            font-size: 0.875rem;
            color: #64748b;
            margin-top: 0.25rem;
        }
        
        .facility-info i {
            color: #f59e0b;
            margin-right: 0.25rem;
        }
        
        .appointment-item {
            background: #f8fafc;
            border-left: 4px solid #667eea;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 0.75rem;
        }
        
        .appointment-item:hover {
            background: #f1f5f9;
        }
        
        .stat-box {
            text-align: center;
            padding: 1.5rem;
            background: white;
            border-radius: 8px;
            border: 1px solid #e2e8f0;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .badge {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-weight: 500;
            font-size: 0.75rem;
            text-transform: uppercase;
        }
        
        .badge-available {
            background: #d1fae5;
            color: #065f46;
        }
        
        .badge-unavailable {
            background: #fee2e2;
            color: #991b1b;
        }
        
        /* Modal Styles */
        .session-group {
            background: #f8fafc;
            border: 2px dashed #cbd5e1;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            position: relative;
        }
        
        .session-group.internal-session {
            background: #f0fdf4;
            border-color: #86efac;
        }
        
        .session-group.external-session {
            background: #fef3c7;
            border-color: #fbbf24;
        }
        
        .session-type-badge {
            position: absolute;
            top: -10px;
            left: 10px;
            background: white;
            padding: 0.25rem 0.75rem;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 600;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .session-type-badge.internal {
            color: #065f46;
            border: 2px solid #86efac;
        }
        
        .session-type-badge.external {
            color: #92400e;
            border: 2px solid #fbbf24;
        }
        
        .add-session-btn {
            width: 100%;
            padding: 0.75rem;
            border: 2px dashed #cbd5e1;
            background: white;
            border-radius: 6px;
            color: #64748b;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: 500;
        }
        
        .add-session-btn:hover {
            border-color: #667eea;
            color: #667eea;
            background: #f0f4ff;
        }
        
        .remove-session-btn {
            position: absolute;
            top: -8px;
            right: 10px;
            background: #ef4444;
            color: white;
            border: none;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 0.875rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.2);
        }
        
        .remove-session-btn:hover {
            background: #dc2626;
        }
        
        .facility-fields {
            background: #fffbeb;
            padding: 0.75rem;
            border-radius: 6px;
            margin-top: 0.75rem;
            border: 1px solid #fde68a;
        }
        
        .modal-body {
            max-height: 70vh;
            overflow-y: auto;
        }
    </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">Doctor Schedule</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_doctors.php">Doctors</a></li>
                                        <li class="breadcrumb-item active">Schedule</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Schedule Header -->
                    <div class="schedule-header">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <h3 class="mb-2">Dr. <?php echo htmlspecialchars($doctor['full_name']); ?></h3>
                                <div class="d-flex gap-3 flex-wrap">
                                    <div>
                                        <i class="ri-stethoscope-line me-1"></i>
                                        <?php echo htmlspecialchars($doctor['specialization']); ?>
                                    </div>
                                    <div>
                                        <i class="ri-time-line me-1"></i>
                                        <?php echo $doctor['appointment_duration']; ?> min appointments
                                    </div>
                                    <div>
                                        <i class="ri-calendar-check-line me-1"></i>
                                        Max: <?php echo $doctor['max_daily_appointments']; ?> patients/day
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4 text-md-end mt-3 mt-md-0">
                                <?php if (in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN']) || $doctor_id === $_SESSION['user_id']): ?>
                                <button class="btn btn-light" onclick="editSchedule()">
                                    <i class="ri-edit-line me-1"></i> Edit Schedule
                                </button>
                                <a href="view_doctor.php?id=<?php echo $doctor_id; ?>" class="btn btn-light">
                                    <i class="ri-user-line me-1"></i> View Profile
                                </a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Today's Statistics -->
                    <div class="row mb-4">
                        <div class="col-md-4">
                            <div class="stat-box">
                                <div class="stat-value"><?php echo $today_stats['total_today']; ?></div>
                                <div class="stat-label">Today's Appointments</div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="stat-box">
                                <div class="stat-value text-success"><?php echo $today_stats['completed_today']; ?></div>
                                <div class="stat-label">Completed</div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="stat-box">
                                <div class="stat-value text-info"><?php echo $today_stats['pending_today']; ?></div>
                                <div class="stat-label">Pending</div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Weekly Schedule -->
                        <div class="col-lg-7">
                            <div class="schedule-card">
                                <h5><i class="ri-calendar-2-line me-2"></i>Weekly Schedule</h5>
                                
                                <?php foreach ($days as $day): ?>
                                <?php 
                                $dayData = isset($availability[$day]) ? $availability[$day] : ['sessions' => []];
                                $sessions = isset($dayData['sessions']) ? $dayData['sessions'] : [];
                                $hasSchedule = !empty($sessions);
                                ?>
                                <div class="day-schedule <?php echo $hasSchedule ? 'has-schedule' : ''; ?>">
                                    <div class="day-header">
                                        <span class="day-name"><?php echo ucfirst($day); ?></span>
                                        <span class="badge <?php echo $hasSchedule ? 'badge-available' : 'badge-unavailable'; ?>">
                                            <?php echo $hasSchedule ? 'Available' : 'Unavailable'; ?>
                                        </span>
                                    </div>
                                    
                                    <?php if ($hasSchedule): ?>
                                        <?php foreach ($sessions as $session): ?>
                                            <?php 
                                            $locationType = isset($session['location_type']) ? $session['location_type'] : 'internal';
                                            ?>
                                            <div class="session-item <?php echo $locationType; ?>">
                                                <div class="d-flex justify-content-between align-items-start">
                                                    <div class="flex-grow-1">
                                                        <div class="d-flex align-items-center gap-2 mb-1">
                                                            <span class="location-badge <?php echo $locationType; ?>">
                                                                <i class="ri-<?php echo $locationType === 'internal' ? 'hospital' : 'building'; ?>-line"></i>
                                                                <?php echo ucfirst($locationType); ?>
                                                            </span>
                                                            <span class="time-slot">
                                                                <?php echo htmlspecialchars($session['start']); ?> - <?php echo htmlspecialchars($session['end']); ?>
                                                            </span>
                                                        </div>
                                                        
                                                        <?php if ($locationType === 'external'): ?>
                                                            <div class="facility-info">
                                                                <div><i class="ri-building-line"></i><strong><?php echo htmlspecialchars($session['facility_name'] ?? 'External Facility'); ?></strong></div>
                                                                <?php if (!empty($session['facility_address'])): ?>
                                                                    <div><i class="ri-map-pin-line"></i><?php echo htmlspecialchars($session['facility_address']); ?></div>
                                                                <?php endif; ?>
                                                                <?php if (!empty($session['facility_contact'])): ?>
                                                                    <div><i class="ri-phone-line"></i><?php echo htmlspecialchars($session['facility_contact']); ?></div>
                                                                <?php endif; ?>
                                                            </div>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <small class="text-muted">No schedule set</small>
                                    <?php endif; ?>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <!-- Upcoming Appointments -->
                        <div class="col-lg-5">
                            <div class="schedule-card">
                                <h5><i class="ri-calendar-event-line me-2"></i>Upcoming Appointments (Next 7 Days)</h5>
                                
                                <?php if ($upcoming_appointments->num_rows > 0): ?>
                                    <?php while($appointment = $upcoming_appointments->fetch_assoc()): ?>
                                    <div class="appointment-item">
                                        <div class="d-flex justify-content-between align-items-start mb-2">
                                            <div>
                                                <div class="fw-bold"><?php echo htmlspecialchars($appointment['patient_name']); ?></div>
                                                <small class="text-muted">
                                                    #<?php echo htmlspecialchars($appointment['patient_number']); ?>
                                                </small>
                                            </div>
                                            <span class="badge bg-<?php echo $appointment['status'] === 'CONFIRMED' ? 'success' : 'info'; ?>">
                                                <?php echo $appointment['status']; ?>
                                            </span>
                                        </div>
                                        <div class="small">
                                            <i class="ri-calendar-line me-1"></i>
                                            <?php echo date('D, M d, Y', strtotime($appointment['appointment_date'])); ?>
                                            <span class="ms-2">
                                                <i class="ri-time-line me-1"></i>
                                                <?php echo date('h:i A', strtotime($appointment['appointment_time'])); ?>
                                            </span>
                                        </div>
                                        <?php if ($appointment['reason']): ?>
                                        <div class="small mt-1 text-muted">
                                            <i class="ri-file-text-line me-1"></i>
                                            <?php echo htmlspecialchars($appointment['reason']); ?>
                                        </div>
                                        <?php endif; ?>
                                        <div class="mt-2">
                                            <a href="view_appointment.php?id=<?php echo $appointment['appointment_id']; ?>" 
                                               class="btn btn-sm btn-outline-primary">
                                                View Details
                                            </a>
                                        </div>
                                    </div>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <div class="text-center text-muted py-4">
                                        <i class="ri-calendar-line" style="font-size: 3rem; opacity: 0.3;"></i>
                                        <p class="mt-2">No upcoming appointments</p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Edit Schedule Modal -->
    <div class="modal fade" id="editScheduleModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Weekly Schedule</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="scheduleForm" method="POST" action="update_doctor_schedule.php">
                    <input type="hidden" name="doctor_id" value="<?php echo $doctor_id; ?>">
                    <div class="modal-body">
                        <div class="alert alert-info">
                            <i class="ri-information-line me-2"></i>
                            <strong>Tip:</strong> You can add multiple sessions per day. For example, work at the clinic in the morning and at an external facility in the afternoon.
                        </div>
                        
                        <?php foreach ($days as $day): ?>
                        <?php 
                        $dayData = isset($availability[$day]) ? $availability[$day] : ['sessions' => []];
                        $sessions = isset($dayData['sessions']) ? $dayData['sessions'] : [];
                        ?>
                        <div class="mb-4 p-3 border rounded">
                            <h6 class="fw-bold mb-3"><?php echo ucfirst($day); ?></h6>
                            
                            <div id="sessions_container_<?php echo $day; ?>">
                                <?php if (empty($sessions)): ?>
                                    <!-- Empty state - will be populated by JS -->
                                <?php else: ?>
                                    <?php foreach ($sessions as $index => $session): ?>
                                        <?php 
                                        $locationType = isset($session['location_type']) ? $session['location_type'] : 'internal';
                                        ?>
                                        <div class="session-group <?php echo $locationType; ?>-session" data-session-index="<?php echo $index; ?>">
                                            <span class="session-type-badge <?php echo $locationType; ?>">
                                                <i class="ri-<?php echo $locationType === 'internal' ? 'hospital' : 'building'; ?>-line"></i>
                                                <?php echo ucfirst($locationType); ?>
                                            </span>
                                            <button type="button" class="remove-session-btn" onclick="removeSession('<?php echo $day; ?>', <?php echo $index; ?>)">
                                                <i class="ri-close-line"></i>
                                            </button>
                                            
                                            <input type="hidden" name="schedule[<?php echo $day; ?>][sessions][<?php echo $index; ?>][location_type]" value="<?php echo $locationType; ?>">
                                            
                                            <div class="row">
                                                <div class="col-md-5">
                                                    <label class="form-label">Start Time</label>
                                                    <input type="time" class="form-control" required
                                                           name="schedule[<?php echo $day; ?>][sessions][<?php echo $index; ?>][start]"
                                                           value="<?php echo htmlspecialchars($session['start'] ?? '09:00'); ?>">
                                                </div>
                                                <div class="col-md-5">
                                                    <label class="form-label">End Time</label>
                                                    <input type="time" class="form-control" required
                                                           name="schedule[<?php echo $day; ?>][sessions][<?php echo $index; ?>][end]"
                                                           value="<?php echo htmlspecialchars($session['end'] ?? '17:00'); ?>">
                                                </div>
                                            </div>
                                            
                                            <?php if ($locationType === 'external'): ?>
                                            <div class="facility-fields mt-3">
                                                <div class="mb-2">
                                                    <label class="form-label">Facility Name <span class="text-danger">*</span></label>
                                                    <input type="text" class="form-control" required
                                                           name="schedule[<?php echo $day; ?>][sessions][<?php echo $index; ?>][facility_name]"
                                                           placeholder="e.g., Mediheal"
                                                           value="<?php echo htmlspecialchars($session['facility_name'] ?? ''); ?>">
                                                </div>
                                                <div class="mb-2">
                                                    <label class="form-label">Facility Address</label>
                                                    <input type="text" class="form-control"
                                                           name="schedule[<?php echo $day; ?>][sessions][<?php echo $index; ?>][facility_address]"
                                                           placeholder="e.g., Upperhill"
                                                           value="<?php echo htmlspecialchars($session['facility_address'] ?? ''); ?>">
                                                </div>
                                                <div class="mb-2">
                                                    <label class="form-label">Facility Contact</label>
                                                    <input type="text" class="form-control"
                                                           name="schedule[<?php echo $day; ?>][sessions][<?php echo $index; ?>][facility_contact]"
                                                           placeholder="Phone number"
                                                           value="<?php echo htmlspecialchars($session['facility_contact'] ?? ''); ?>">
                                                </div>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                            
                            <div class="mt-3">
                                <div class="btn-group w-100">
                                    <button type="button" class="add-session-btn" onclick="addSession('<?php echo $day; ?>', 'internal')">
                                        <i class="ri-hospital-line me-1"></i> Add In-Clinic Session
                                    </button>
                                    <button type="button" class="add-session-btn" onclick="addSession('<?php echo $day; ?>', 'external')">
                                        <i class="ri-building-line me-1"></i> Add External Session
                                    </button>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Save Schedule</button>
                    </div>
                </form>
            </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="assets/js/app.js"></script>

    <script>
        let sessionCounters = {};
        
        // Initialize session counters for each day
        <?php foreach ($days as $day): ?>
        sessionCounters['<?php echo $day; ?>'] = <?php echo isset($availability[$day]['sessions']) ? count($availability[$day]['sessions']) : 0; ?>;
        <?php endforeach; ?>
        
        function editSchedule() {
            var modal = new bootstrap.Modal(document.getElementById('editScheduleModal'));
            modal.show();
        }
        
        function addSession(day, locationType) {
            const container = document.getElementById('sessions_container_' + day);
            const index = sessionCounters[day];
            sessionCounters[day]++;
            const sessionHtml = `
            <div class="session-group ${locationType}-session" data-session-index="${index}">
                <span class="session-type-badge ${locationType}">
                    <i class="ri-${locationType === 'internal' ? 'hospital' : 'building'}-line"></i>
                    ${locationType.charAt(0).toUpperCase() + locationType.slice(1)}
                </span>
                <button type="button" class="remove-session-btn" onclick="removeSession('${day}', ${index})">
                    <i class="ri-close-line"></i>
                </button>
                
                <input type="hidden" name="schedule[${day}][sessions][${index}][location_type]" value="${locationType}">
                
                <div class="row">
                    <div class="col-md-5">
                        <label class="form-label">Start Time</label>
                        <input type="time" class="form-control" required
                               name="schedule[${day}][sessions][${index}][start]"
                               value="09:00">
                    </div>
                    <div class="col-md-5">
                        <label class="form-label">End Time</label>
                        <input type="time" class="form-control" required
                               name="schedule[${day}][sessions][${index}][end]"
                               value="17:00">
                    </div>
                </div>
                
                ${locationType === 'external' ? `
                <div class="facility-fields mt-3">
                    <div class="mb-2">
                        <label class="form-label">Facility Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" required
                               name="schedule[${day}][sessions][${index}][facility_name]"
                               placeholder="e.g., Mediheal">
                    </div>
                    <div class="mb-2">
                        <label class="form-label">Facility Address</label>
                        <input type="text" class="form-control"
                               name="schedule[${day}][sessions][${index}][facility_address]"
                               placeholder="e.g., Upperhill">
                    </div>
                    <div class="mb-2">
                        <label class="form-label">Facility Contact</label>
                        <input type="text" class="form-control"
                               name="schedule[${day}][sessions][${index}][facility_contact]"
                               placeholder="Phone number">
                    </div>
                </div>
                ` : ''}
            </div>
        `;
        
        container.insertAdjacentHTML('beforeend', sessionHtml);
    }
    
    function removeSession(day, index) {
        const sessionGroup = document.querySelector(`#sessions_container_${day} .session-group[data-session-index="${index}"]`);
        if (sessionGroup) {
            Swal.fire({
                title: 'Remove Session?',
                text: 'Are you sure you want to remove this session?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#ef4444',
                cancelButtonColor: '#64748b',
                confirmButtonText: 'Yes, remove it'
            }).then((result) => {
                if (result.isConfirmed) {
                    sessionGroup.remove();
                }
            });
        }
    }
    
    // Show success/error messages
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('success') === 'schedule_updated') {
        Swal.fire({
            icon: 'success',
            title: 'Schedule Updated',
            text: 'Doctor schedule has been updated successfully',
            timer: 3000,
            showConfirmButton: false
        });
    }
    
    // Form submission
    $('#scheduleForm').on('submit', function(e) {
        e.preventDefault();
        
        $.ajax({
            url: $(this).attr('action'),
            method: 'POST',
            data: $(this).serialize(),
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: response.message,
                        timer: 2000,
                        showConfirmButton: false
                    }).then(() => {
                        window.location.reload();
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: response.message
                    });
                }
            },
            error: function(xhr, status, error) {
                console.error('Ajax error:', error);
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Failed to update schedule. Please try again.'
                });
            }
        });
    });
</script>
</body>
</html>