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

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

// Ensure user is a receptionist
if ($_SESSION['role_code'] !== 'RECEPTIONIST') {
    header('Location: index.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role_code'];

// Get department filter
$department_filter = $_GET['department'] ?? 'all';
$status_filter = $_GET['status'] ?? 'active';

// Fetch department statistics
$dept_stats_sql = "SELECT 
    d.department_id,
    d.department_name,
    d.department_code,
    COUNT(CASE WHEN q.queue_status = 'WAITING' THEN 1 END) as waiting_count,
    COUNT(CASE WHEN q.queue_status = 'IN_SERVICE' THEN 1 END) as in_service_count,
    COUNT(CASE WHEN q.queue_status IN ('WAITING', 'IN_SERVICE') THEN 1 END) as active_count,
    COUNT(CASE WHEN q.queue_status = 'COMPLETED' THEN 1 END) as completed_today,
    AVG(CASE 
        WHEN q.queue_status IN ('IN_SERVICE', 'COMPLETED') 
        THEN TIMESTAMPDIFF(MINUTE, q.queue_entry_time, COALESCE(q.service_start_time, NOW()))
    END) as avg_wait_minutes,
    MAX(CASE 
        WHEN q.queue_status = 'WAITING'
        THEN TIMESTAMPDIFF(MINUTE, q.queue_entry_time, NOW())
    END) as longest_wait_minutes,
    d.max_queue_capacity,
    ROUND((COUNT(CASE WHEN q.queue_status IN ('WAITING', 'IN_SERVICE') THEN 1 END) / d.max_queue_capacity) * 100, 2) as capacity_percentage
FROM departments d
LEFT JOIN patient_queue q ON d.department_id = q.department_id 
    AND DATE(q.queue_entry_time) = CURDATE()
WHERE d.is_active = 1
GROUP BY d.department_id, d.department_name, d.department_code, d.max_queue_capacity
ORDER BY d.display_order";
$dept_stats_result = $conn->query($dept_stats_sql);

// Build queue query
$queue_sql = "SELECT 
    q.queue_id,
    q.queue_number,
    q.patient_id,
    q.patient_name,
    q.patient_number,
    q.phone_number,
    q.age,
    q.gender,
    d.department_id,
    d.department_name,
    d.department_code,
    q.queue_status,
    q.priority,
    q.registration_type,
    q.position_in_queue,
    q.estimated_wait_minutes,
    q.service_type,
    q.chief_complaint,
    q.triage_category,
    q.vitals_taken,
    q.queue_entry_time,
    q.service_start_time,
    TIMESTAMPDIFF(MINUTE, q.queue_entry_time, NOW()) as actual_wait_minutes,
    q.serving_staff_name,
    q.has_appointment,
    q.is_vip,
    q.special_needs,
    q.alert_flags,
    u.full_name as created_by_name,
    q.created_at
FROM patient_queue q
INNER JOIN departments d ON q.department_id = d.department_id
LEFT JOIN users u ON q.created_by = u.user_id
WHERE DATE(q.queue_entry_time) = CURDATE()
AND q.queue_status IN ('WAITING', 'IN_SERVICE')";

if ($department_filter !== 'all') {
    $queue_sql .= " AND q.department_id = " . intval($department_filter);
}

if ($status_filter === 'active') {
    $queue_sql .= " AND queue_status IN ('WAITING', 'IN_SERVICE')";
} elseif ($status_filter === 'waiting') {
    $queue_sql .= " AND queue_status = 'WAITING'";
} elseif ($status_filter === 'in_service') {
    $queue_sql .= " AND queue_status = 'IN_SERVICE'";
}

$queue_sql .= " ORDER BY 
    CASE priority
        WHEN 'EMERGENCY' THEN 1
        WHEN 'URGENT' THEN 2
        WHEN 'NORMAL' THEN 3
    END,
    queue_entry_time";

$queue_result = $conn->query($queue_sql);

// Get total counts for today
$counts_sql = "SELECT 
    COUNT(CASE WHEN queue_status IN ('WAITING', 'IN_SERVICE') THEN 1 END) as active_count,
    COUNT(CASE WHEN queue_status = 'WAITING' THEN 1 END) as waiting_count,
    COUNT(CASE WHEN queue_status = 'IN_SERVICE' THEN 1 END) as in_service_count,
    COUNT(CASE WHEN queue_status = 'COMPLETED' THEN 1 END) as completed_count,
    COUNT(CASE WHEN priority = 'EMERGENCY' THEN 1 END) as emergency_count
FROM patient_queue 
WHERE DATE(queue_entry_time) = CURDATE()";

$counts_result = $conn->query($counts_sql);
$counts = $counts_result->fetch_assoc();

// Get today's registrations by receptionist
$my_registrations_sql = "SELECT COUNT(*) as count 
                         FROM patient_visits pv 
                         WHERE DATE(pv.registration_date) = CURDATE() 
                         AND pv.registered_by = ?";
$stmt = $conn->prepare($my_registrations_sql);
$stmt->bind_param('i', $user_id);
$stmt->execute();
$my_registrations = $stmt->get_result()->fetch_assoc()['count'];
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Reception Dashboard')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border-left: 4px solid #667eea;
            transition: all 0.3s;
        }
        
        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .stat-card.waiting {
            border-left-color: #3b82f6;
        }
        
        .stat-card.in-service {
            border-left-color: #f59e0b;
        }
        
        .stat-card.completed {
            border-left-color: #10b981;
        }
        
        .stat-card.my-work {
            border-left-color: #8b5cf6;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin: 0;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .stat-icon {
            font-size: 2.5rem;
            opacity: 0.2;
            position: absolute;
            right: 1rem;
            top: 50%;
            transform: translateY(-50%);
        }
        
        .queue-table {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .queue-table thead {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .queue-table th {
            padding: 1rem;
            font-weight: 600;
            border: none;
        }
        
        .queue-table td {
            padding: 1rem;
            vertical-align: middle;
        }
        
        .queue-table tbody tr {
            border-bottom: 1px solid #f1f5f9;
            transition: background 0.2s;
        }
        
        .queue-table tbody tr:hover {
            background: #f8fafc;
        }
        
        .priority-badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .priority-normal {
            background: #dcfce7;
            color: #166534;
        }
        
        .priority-urgent {
            background: #fef3c7;
            color: #92400e;
        }
        
        .priority-emergency {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .status-badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .status-waiting {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .status-in-service {
            background: #fef3c7;
            color: #92400e;
        }
        
        .patient-info {
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        
        .patient-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
            font-size: 1rem;
        }
        
        .patient-details {
            flex: 1;
        }
        
        .patient-name {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.125rem;
        }
        
        .patient-meta {
            font-size: 0.75rem;
            color: #64748b;
        }
        
        .wait-time {
            font-size: 0.875rem;
            color: #64748b;
        }
        
        .wait-time.long {
            color: #dc2626;
            font-weight: 600;
        }
        
        .vip-flag {
            display: inline-block;
            padding: 0.125rem 0.5rem;
            background: #fef3c7;
            color: #92400e;
            border-radius: 4px;
            font-size: 0.625rem;
            font-weight: 600;
            margin-left: 0.5rem;
        }
        
        .refresh-indicator {
            display: inline-block;
            color: #10b981;
            font-size: 0.875rem;
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        
        .empty-state {
            text-align: center;
            padding: 3rem;
            color: #64748b;
        }
        
        .empty-state i {
            font-size: 4rem;
            margin-bottom: 1rem;
            opacity: 0.3;
        }

        .quick-action-card {
            background: white;
            border-radius: 10px;
            padding: 1.5rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            border: 2px solid #e2e8f0;
        }

        .quick-action-card:hover {
            border-color: #667eea;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
        }

        .quick-action-icon {
            width: 60px;
            height: 60px;
            margin: 0 auto 1rem;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.75rem;
        }

        .quick-action-title {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }

        .quick-action-desc {
            font-size: 0.75rem;
            color: #64748b;
        }
    </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">
                                    <i class="ri-dashboard-line me-2"></i>Reception Dashboard
                                    <span class="refresh-indicator ms-3">
                                        <i class="ri-refresh-line"></i> Live
                                    </span>
                                </h4>
                                <div class="page-title-right">
                                    <button class="btn btn-secondary" onclick="refreshQueue()">
                                        <i class="ri-refresh-line me-1"></i> Refresh
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="position-relative">
                                    <p class="stat-label">Total Active</p>
                                    <h2 class="stat-value"><?php echo $counts['active_count']; ?></h2>
                                    <i class="ri-team-line stat-icon"></i>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card waiting">
                                <div class="position-relative">
                                    <p class="stat-label">Waiting</p>
                                    <h2 class="stat-value"><?php echo $counts['waiting_count']; ?></h2>
                                    <i class="ri-time-line stat-icon"></i>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card in-service">
                                <div class="position-relative">
                                    <p class="stat-label">In Service</p>
                                    <h2 class="stat-value"><?php echo $counts['in_service_count']; ?></h2>
                                    <i class="ri-user-settings-line stat-icon"></i>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card my-work">
                                <div class="position-relative">
                                    <p class="stat-label">My Registrations Today</p>
                                    <h2 class="stat-value"><?php echo $my_registrations; ?></h2>
                                    <i class="ri-user-add-line stat-icon"></i>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Quick Actions -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                                    <h5 class="mb-0">
                                        <i class="ri-flashlight-line me-2"></i>Quick Actions
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="row g-3">
                                        <div class="col-md-3">
                                            <div class="quick-action-card" onclick="location.href='register_patient.php'">
                                                <div class="quick-action-icon">
                                                    <i class="ri-user-add-line"></i>
                                                </div>
                                                <div class="quick-action-title">Register Patient</div>
                                                <div class="quick-action-desc">New patient entry</div>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="quick-action-card" onclick="location.href='book_appointment.php'">
                                                <div class="quick-action-icon">
                                                    <i class="ri-calendar-line"></i>
                                                </div>
                                                <div class="quick-action-title">Book Appointment</div>
                                                <div class="quick-action-desc">Schedule visit</div>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="quick-action-card" onclick="location.href='list_patients.php'">
                                                <div class="quick-action-icon">
                                                    <i class="ri-search-line"></i>
                                                </div>
                                                <div class="quick-action-title">Patient Search</div>
                                                <div class="quick-action-desc">Find records</div>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="quick-action-card" onclick="location.href='list_appointments.php'">
                                                <div class="quick-action-icon">
                                                    <i class="ri-list-check"></i>
                                                </div>
                                                <div class="quick-action-title">View Appointments</div>
                                                <div class="quick-action-desc">Today's schedule</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Queue Display -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center" 
                                     style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                                    <h5 class="mb-0">
                                        <i class="ri-list-check me-2"></i>Current Queue
                                    </h5>
                                    <div>
                                        <select class="form-select form-select-sm" style="width: auto; display: inline-block;" 
                                                onchange="filterByStatus(this.value)">
                                            <option value="active" <?php echo $status_filter === 'active' ? 'selected' : ''; ?>>Active</option>
                                            <option value="waiting" <?php echo $status_filter === 'waiting' ? 'selected' : ''; ?>>Waiting Only</option>
                                            <option value="in_service" <?php echo $status_filter === 'in_service' ? 'selected' : ''; ?>>In Service</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="card-body p-0">
                                    <?php if ($queue_result->num_rows > 0): ?>
                                    <div class="table-responsive">
                                        <table class="table queue-table mb-0">
                                            <thead>
                                                <tr>
                                                    <th style="width: 5%;">#</th>
                                                    <th style="width: 25%;">Patient</th>
                                                    <th style="width: 15%;">Department</th>
                                                    <th style="width: 10%;">Priority</th>
                                                    <th style="width: 10%;">Status</th>
                                                    <th style="width: 15%;">Wait Time</th>
                                                    <th style="width: 10%;">Position</th>
                                                    <th style="width: 10%;">Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php 
                                                $row_num = 1;
                                                while ($queue = $queue_result->fetch_assoc()): 
                                                    $wait_minutes = $queue['actual_wait_minutes'];
                                                    $is_long_wait = $wait_minutes > 60;
                                                ?>
                                                <tr>
                                                    <td>
                                                        <strong><?php echo $row_num++; ?></strong>
                                                    </td>
                                                    <td>
                                                        <div class="patient-info">
                                                            <div class="patient-avatar">
                                                                <?php echo strtoupper(substr($queue['patient_name'], 0, 1)); ?>
                                                            </div>
                                                            <div class="patient-details">
                                                                <div class="patient-name">
                                                                    <?php echo htmlspecialchars($queue['patient_name']); ?>
                                                                    <?php if ($queue['is_vip']): ?>
                                                                    <span class="vip-flag">VIP</span>
                                                                    <?php endif; ?>
                                                                </div>
                                                                <div class="patient-meta">
                                                                    <?php echo $queue['patient_number']; ?> • 
                                                                    <?php echo $queue['age']; ?>Y <?php echo $queue['gender']; ?> •
                                                                    <?php echo substr($queue['phone_number'], 0, 10); ?>
                                                                </div>
                                                                <?php if ($queue['chief_complaint']): ?>
                                                                <div class="patient-meta">
                                                                    <i class="ri-stethoscope-line"></i> <?php echo htmlspecialchars(substr($queue['chief_complaint'], 0, 40)); ?>...
                                                                </div>
                                                                <?php endif; ?>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <strong><?php echo htmlspecialchars($queue['department_name']); ?></strong>
                                                    </td>
                                                    <td>
                                                        <span class="priority-badge priority-<?php echo strtolower($queue['priority']); ?>">
                                                            <?php echo $queue['priority']; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <span class="status-badge status-<?php echo str_replace('_', '-', strtolower($queue['queue_status'])); ?>">
                                                            <?php echo str_replace('_', ' ', $queue['queue_status']); ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <div class="wait-time <?php echo $is_long_wait ? 'long' : ''; ?>">
                                                            <i class="ri-time-line me-1"></i>
                                                            <?php 
                                                            if ($wait_minutes < 60) {
                                                                echo $wait_minutes . ' min';
                                                            } else {
                                                                $hours = floor($wait_minutes / 60);
                                                                $mins = $wait_minutes % 60;
                                                                echo $hours . 'h ' . $mins . 'm';
                                                            }
                                                            ?>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <?php if ($queue['queue_status'] === 'WAITING'): ?>
                                                        <span class="badge bg-info">#<?php echo $queue['position_in_queue']; ?></span>
                                                        <?php else: ?>
                                                        <span class="text-muted">-</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group btn-group-sm">
                                                            <button class="btn btn-info" onclick="viewDetails(<?php echo $queue['patient_id']; ?>)"
                                                                    title="View Details">
                                                                <i class="ri-eye-line"></i>
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <?php else: ?>
                                    <div class="empty-state">
                                        <i class="ri-inbox-line"></i>
                                        <h5>No Patients in Queue</h5>
                                        <p class="text-muted">The queue is currently empty.</p>
                                        <button class="btn btn-primary mt-3" onclick="location.href='register_patient.php'">
                                            <i class="ri-user-add-line me-1"></i> Register New Patient
                                        </button>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
    // Auto-refresh every 30 seconds
    setInterval(function() {
        location.reload();
    }, 30000);
    
    function filterByStatus(status) {
        const url = new URL(window.location.href);
        url.searchParams.set('status', status);
        window.location.href = url.toString();
    }
    
    function refreshQueue() {
        location.reload();
    }
    
    function viewDetails(patientId) {
        window.location.href = `view_patient.php?id=${patientId}`;
    }
    </script>

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