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

// Fetch all doctors with external schedules
$doctors_sql = "SELECT 
                    d.doctor_id,
                    d.availability_schedule,
                    u.full_name,
                    d.specialization,
                    u.phone_primary
                FROM doctors d
                INNER JOIN users u ON d.user_id = u.user_id
                WHERE d.is_active = 1
                ORDER BY u.full_name ASC";

$doctors_result = $conn->query($doctors_sql);

$external_schedules = [];
$days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];

while ($doctor = $doctors_result->fetch_assoc()) {
    $availability = json_decode($doctor['availability_schedule'], true);
    
    if ($availability) {
        foreach ($days as $day) {
            if (isset($availability[$day]) && 
                isset($availability[$day]['available']) && 
                $availability[$day]['available'] && 
                isset($availability[$day]['location_type']) && 
                $availability[$day]['location_type'] === 'external') {
                
                $external_schedules[] = [
                    'doctor_id' => $doctor['doctor_id'],
                    'doctor_name' => $doctor['full_name'],
                    'specialization' => $doctor['specialization'],
                    'phone' => $doctor['phone_primary'],
                    'day' => $day,
                    'facility_name' => $availability[$day]['facility_name'] ?? 'Not specified',
                    'facility_address' => $availability[$day]['facility_address'] ?? '',
                    'facility_contact' => $availability[$day]['facility_contact'] ?? '',
                    'slots' => $availability[$day]['slots'] ?? []
                ];
            }
        }
    }
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'External Schedules')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <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;
        }
        
        .external-schedule-item {
            background: #fef3c7;
            border-left: 4px solid #f59e0b;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
        }
        
        .external-schedule-item:hover {
            background: #fde68a;
        }
        
        .facility-badge {
            background: #92400e;
            color: white;
            padding: 0.25rem 0.625rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .time-slot {
            display: inline-block;
            background: #f59e0b;
            color: white;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            margin-right: 0.5rem;
            font-size: 0.875rem;
        }
    </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">External Schedules</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 active">External Schedules</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Header -->
                    <div class="schedule-header">
                        <h3 class="mb-2">Doctors' External/Out-of-Clinic Schedules</h3>
                        <p class="mb-0">View all external clinic locations and schedules</p>
                    </div>

                    <!-- Schedules by Day -->
                    <?php if (empty($external_schedules)): ?>
                        <div class="schedule-card">
                            <div class="text-center text-muted py-5">
                                <i class="ri-building-line" style="font-size: 3rem; opacity: 0.3;"></i>
                                <p class="mt-3">No external schedules configured</p>
                            </div>
                        </div>
                    <?php else: ?>
                        <?php foreach ($days as $day): ?>
                            <?php 
                            $day_schedules = array_filter($external_schedules, function($schedule) use ($day) {
                                return $schedule['day'] === $day;
                            });
                            ?>
                            
                            <?php if (!empty($day_schedules)): ?>
                                <div class="schedule-card">
                                    <h5 class="mb-3">
                                        <i class="ri-calendar-line me-2"></i>
                                        <?php echo ucfirst($day); ?>
                                        <span class="badge bg-warning ms-2"><?php echo count($day_schedules); ?> doctor(s)</span>
                                    </h5>
                                    
                                    <?php foreach ($day_schedules as $schedule): ?>
                                        <div class="external-schedule-item">
                                            <div class="row align-items-center">
                                                <div class="col-md-3">
                                                    <div class="fw-bold">Dr. <?php echo htmlspecialchars($schedule['doctor_name']); ?></div>
                                                    <small class="text-muted"><?php echo htmlspecialchars($schedule['specialization']); ?></small>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="mb-1">
                                                        <i class="ri-building-line me-1"></i>
                                                        <strong><?php echo htmlspecialchars($schedule['facility_name']); ?></strong>
                                                    </div>
                                                    <?php if (!empty($schedule['facility_address'])): ?>
                                                        <div class="small">
                                                            <i class="ri-map-pin-line me-1"></i>
                                                            <?php echo htmlspecialchars($schedule['facility_address']); ?>
                                                        </div>
                                                    <?php endif; ?>
                                                    <?php if (!empty($schedule['facility_contact'])): ?>
                                                        <div class="small">
                                                            <i class="ri-phone-line me-1"></i>
                                                            <?php echo htmlspecialchars($schedule['facility_contact']); ?>
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                                <div class="col-md-3">
                                                    <?php foreach ($schedule['slots'] as $slot): ?>
                                                        <span class="time-slot">
                                                            <?php echo htmlspecialchars($slot['start']); ?> - <?php echo htmlspecialchars($slot['end']); ?>
                                                        </span>
                                                    <?php endforeach; ?>
                                                </div>
                                                <div class="col-md-2 text-end">
                                                    <a href="doctor_schedules.php?doctor_id=<?php echo $schedule['doctor_id']; ?>" 
                                                       class="btn btn-sm btn-outline-primary">
                                                        View Full Schedule
                                                    </a>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
</body>
</html>