<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
session_write_close();

// 🔥 FORCE WEST AFRICA TIME (WAT) TO MATCH LOGS AND LOCAL TIME EXACTLY
date_default_timezone_set('Africa/Lagos');

require 'config.php';

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

$username = $_SESSION['username'];
$role = $_SESSION['role'];
$isManager = strtolower(trim($role)) === 'manager';
$userDeptId = isset($_SESSION['department_id']) ? intval($_SESSION['department_id']) : 0;

$today = date('Y-m-d');
$yesterday = date('Y-m-d', strtotime('-1 day'));
$currentMonth = date('Y-m');

// SCOPE CONDITION (Restricts metrics to the manager's department if applicable)
$deptCondition = "1";
if ($isManager) {
    $deptCondition = "e.department_id = $userDeptId";
}

// COALESCED SHIFT RESOLUTION 
$resolvedShiftSql = "
    COALESCE(
        (SELECT ds.shift_id FROM department_schedules ds WHERE ds.employee_id = e.id AND ds.schedule_date = '$today'),
        e.shift_id
    )
";

// ACTIVE SHIFT REGULATORY CONDITION
$activeCondition = "
(
    (s.crosses_midnight = 0 AND a.date = '$today')
    OR
    (s.crosses_midnight = 1 AND (
        a.date = '$today'
        OR (
            a.date = '$yesterday'
            AND a.check_out >= CONCAT('$today', ' 00:00:00')
        )
    ))
)
";

// BASIC SCOPED COUNTS
$totalEmployees = $conn->query("SELECT COUNT(*) as t FROM employees e WHERE $deptCondition")->fetch_assoc()['t'];
$totalShifts = $conn->query("SELECT COUNT(*) as t FROM shifts")->fetch_assoc()['t'];
$nightShifts = $conn->query("SELECT COUNT(*) as t FROM shifts WHERE crosses_midnight=1")->fetch_assoc()['t'];

// PRESENT TODAY
$presentToday = $conn->query("
SELECT COUNT(DISTINCT a.employee_id) as t
FROM attendance a
JOIN employees e ON e.id = a.employee_id
JOIN shifts s ON s.id = $resolvedShiftSql
WHERE $activeCondition
AND $deptCondition
")->fetch_assoc()['t'];


// =========================================================================
// 🔥 REAL-TIME ABSENT TRACKING (STRIPPED OF NOT RESUMED STAT)
// =========================================================================
$absentToday = 0;

$rosterSql = "
    SELECT 
        e.id,
        s.name as shift_name,
        s.checkin as expected_in,
        s.crosses_midnight,
        (SELECT a.id FROM attendance a WHERE a.employee_id = e.id AND $activeCondition LIMIT 1) as attendance_id
    FROM employees e
    LEFT JOIN shifts s ON s.id = $resolvedShiftSql
    WHERE $deptCondition
";

$rosterResult = $conn->query($rosterSql);
if (!$rosterResult) {
    die("Roster Query Failed: " . $conn->error);
}

function tableExists($conn, $tableName) {
    $res = $conn->query("SHOW TABLES LIKE '$tableName'");
    return $res && $res->num_rows > 0;
}

$hasLeavesTable = tableExists($conn, 'leave_requests');
$hasHolidaysTable = tableExists($conn, 'holidays');

$currentTime = time();

while ($emp = $rosterResult->fetch_assoc()) {
    if (!empty($emp['attendance_id'])) {
        continue; 
    }

    $shiftName = $emp['shift_name'] ?? 'No Shift';
    $isOffDay = (stripos($shiftName, 'off') !== false || $shiftName === 'No Shift');

    if ($isOffDay) {
        continue;
    }

    $leaveCheck = 0;
    $empId = $emp['id'];
    if ($hasLeavesTable) {
        $leaveCheck = $conn->query("
            SELECT id 
            FROM leave_requests 
            WHERE employee_id = $empId 
            AND '$today' BETWEEN start_date AND end_date 
            AND hr_status = 'Approved' 
            LIMIT 1
        ")->num_rows;
    }

    $holidayCheck = 0;
    if ($hasHolidaysTable) {
        $holidayCheck = $conn->query("SELECT id FROM holidays WHERE date = '$today' LIMIT 1")->num_rows;
    }

    if ($leaveCheck > 0 || $holidayCheck > 0) {
        continue; 
    }

    if (!empty($emp['expected_in'])) {
        $expectedInTimestamp = strtotime($today . ' ' . $emp['expected_in']);
        $cutoffTimestamp = $expectedInTimestamp + 3600;

        if ($currentTime >= $cutoffTimestamp) {
            $absentToday++;
        }
    } else {
        $absentToday++;
    }
}
// =========================================================================

// LATE TODAY
$lateToday = $conn->query("
SELECT COUNT(*) as t
FROM attendance a
JOIN employees e ON e.id = a.employee_id
JOIN shifts s ON s.id = $resolvedShiftSql
WHERE $activeCondition
AND $deptCondition
AND a.check_in > CONCAT(a.date, ' ', s.checkin)
")->fetch_assoc()['t'];

// OVERTIME TODAY
$overtimeToday = $conn->query("
SELECT SUM(
    TIMESTAMPDIFF(
        MINUTE,
        CASE 
            WHEN s.crosses_midnight = 1 
            THEN CONCAT(DATE_ADD(a.date, INTERVAL 1 DAY), ' ', s.checkout)
            ELSE CONCAT(a.date, ' ', s.checkout)
        END,
        a.check_out
    )
) as total
FROM attendance a
JOIN employees e ON e.id = a.employee_id
JOIN shifts s ON s.id = $resolvedShiftSql
WHERE $activeCondition
AND $deptCondition
AND a.check_out IS NOT NULL
AND a.check_out >
    CASE 
        WHEN s.crosses_midnight = 1 
        THEN CONCAT(DATE_ADD(a.date, INTERVAL 1 DAY), ' ', s.checkout)
        ELSE CONCAT(a.date, ' ', s.checkout)
    END
")->fetch_assoc()['total'] ?? 0;

$overtimeHours = round($overtimeToday / 60, 2);

// DYNAMIC PERFORMANCE RATIO CALCULATIONS FOR MONTHLY REPORTING
$reliabilityRate = ($totalEmployees > 0) ? round(($presentToday / $totalEmployees) * 100, 1) : 0;
$lossRate = ($totalEmployees > 0) ? round(($absentToday / $totalEmployees) * 100, 1) : 0;

// TRENDING METRICS (Aggregated within current month)
$trendLabels = [];
$trendData = [];

$result = $conn->query("
SELECT DATE(a.date) as d, COUNT(DISTINCT a.employee_id) as total
FROM attendance a
JOIN employees e ON e.id = a.employee_id
WHERE a.date LIKE '$currentMonth%'
AND $deptCondition
GROUP BY d
ORDER BY d
");

while ($row = $result->fetch_assoc()) {
    $trendLabels[] = $row['d'];
    $trendData[] = $row['total'];
}

$nightAttendance = $conn->query("
SELECT COUNT(DISTINCT a.employee_id) as t
FROM attendance a
JOIN employees e ON e.id = a.employee_id
JOIN shifts s ON s.id = $resolvedShiftSql
WHERE s.crosses_midnight = 1
AND $activeCondition
AND $deptCondition
")->fetch_assoc()['t'];

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - HR Engine</title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Mulish:ital,wght=0,200..1000;1,200..1000&display=swap" rel="stylesheet">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        sans: ['Mulish', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link rel="stylesheet" href="components/sidebar.css">
</head>
<body class="bg-stone-100/60 min-h-screen text-slate-800 antialiased selection:bg-indigo-600 selection:text-white font-sans">

    <div class="flex">
        
        <?php include 'components/sidebar.php'; ?>

        <div id="sidebar-overlay" class="fixed inset-0 bg-slate-900/40 hidden z-40 transition-opacity duration-300" onclick="toggleSidebar()"></div>

        <div id="main-content" class="flex-1 min-w-0 md:pl-60 transition-all duration-300 min-h-screen flex flex-col">
            
            <header class="sticky top-0 bg-white/90 backdrop-blur-md border-b border-slate-300/80 h-14 flex items-center justify-between px-4 sm:px-6 z-30 shadow-xs">
                <div class="flex items-center gap-3">
                    <button onclick="toggleSidebar()" class="p-1.5 rounded-lg text-slate-600 hover:bg-slate-200/80 transition active:scale-95" aria-label="Toggle Side Area Menu">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 12h16M4 18h16"></path>
                        </svg>
                    </button>
                    <div>
                        <h1 class="text-sm font-black tracking-tight text-slate-950">Executive Dashboard</h1>
                        <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">Operations Center</p>
                    </div>
                </div>
                
                <div class="flex items-center gap-4">
                    <div class="hidden sm:flex flex-col text-right">
                        <span class="text-[11px] font-extrabold text-slate-950 leading-tight"><?= htmlspecialchars($username); ?></span>
                        <span class="text-[9px] text-indigo-700 uppercase font-black tracking-wider leading-none mt-0.5"><?= htmlspecialchars($role ?: 'Staff'); ?></span>
                    </div>
                    <div class="w-7 h-7 bg-slate-200 border border-slate-300 rounded-lg flex items-center justify-center font-black text-xs text-slate-700 select-none uppercase">
                        <?= strtoupper(substr($username, 0, 1)); ?>
                    </div>
                </div>
            </header>

            <main class="flex-1 p-4 sm:p-6 max-w-7xl w-full mx-auto space-y-6">

                <div class="bg-gradient-to-br from-slate-900 to-indigo-950 rounded-xl p-6 text-white shadow-md border border-slate-800 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                    <div class="space-y-1.5">
                        <h2 class="text-base font-black tracking-tight text-white flex items-center gap-2">
                            <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 inline-block"></span>
                            Hotel Labor Performance Metrics
                        </h2>
                        <p class="text-[12px] text-slate-300 max-w-xl leading-relaxed">
                            Structured parameters rendered natively for real-time validation and localized optimization metrics within operational framework matrices.
                        </p>
                    </div>
                    <div class="bg-white/10 border border-white/20 rounded-lg px-5 py-3 min-w-[130px] text-center shrink-0">
                        <p class="text-[10px] text-indigo-200 uppercase tracking-widest font-black">Active Staffing</p>
                        <p class="text-2xl font-black tracking-tight mt-0.5 text-white"><?= $totalEmployees; ?></p>
                    </div>
                </div>

                <div class="border-b border-slate-300 pb-2 flex items-center justify-between">
                    <h3 class="text-[10px] font-black text-slate-500 uppercase tracking-widest">Financial & Resource Indicators</h3>
                    <span class="text-[10px] text-slate-800 font-mono bg-white border border-slate-300/80 px-2.5 py-1 rounded font-bold shadow-xs"><?= date('F Y'); ?></span>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                    
                    <div class="bg-white border border-slate-300/80 rounded-xl p-5 shadow-sm hover:border-indigo-400 transition-all">
                        <div class="flex items-start justify-between">
                            <div class="space-y-2">
                                <p class="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">Overtime Accumulation</p>
                                <h4 class="text-2xl font-black tracking-tight text-slate-950">
                                    <?= $overtimeHours; ?><span class="text-xs font-bold text-slate-500 ml-1">Hrs</span>
                                </h4>
                                <p class="text-[11px] text-slate-600 leading-normal">Directly impacts unbudgeted gross labor wages.</p>
                            </div>
                            <div class="w-8 h-8 rounded-lg bg-indigo-50 border border-indigo-200 flex items-center justify-center text-sm shrink-0">⚡</div>
                        </div>
                    </div>

                    <div class="bg-white border border-slate-300/80 rounded-xl p-5 shadow-sm hover:border-rose-400 transition-all">
                        <div class="flex items-start justify-between">
                            <div class="space-y-2">
                                <p class="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">Shift Absenteeism</p>
                                <h4 class="text-2xl font-black tracking-tight text-rose-700">
                                    <?= $absentToday; ?><span class="text-xs font-bold text-slate-500 ml-1">Staff</span>
                                </h4>
                                <p class="text-[11px] text-slate-600 leading-normal">Drives immediate contingent contractor dependency risk.</p>
                            </div>
                            <div class="w-8 h-8 rounded-lg bg-rose-50 border border-rose-200 flex items-center justify-center text-sm shrink-0">⚠️</div>
                        </div>
                    </div>

                    <div class="bg-white border border-slate-300/80 rounded-xl p-5 shadow-sm hover:border-emerald-400 transition-all sm:col-span-2 lg:col-span-1">
                        <div class="flex items-start justify-between">
                            <div class="space-y-2">
                                <p class="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">Active Deployments</p>
                                <h4 class="text-2xl font-black tracking-tight text-emerald-700">
                                    <?= $presentToday; ?><span class="text-xs font-bold text-slate-500 ml-1">On-Duty</span>
                                </h4>
                                <p class="text-[11px] text-slate-600 leading-normal">Actual verified capacity active right now on-site.</p>
                            </div>
                            <div class="w-8 h-8 rounded-lg bg-emerald-50 border border-emerald-200 flex items-center justify-center text-sm shrink-0">🤝</div>
                        </div>
                    </div>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
                    <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm text-center space-y-1">
                        <p class="text-[9px] font-black text-slate-500 uppercase tracking-wider">Staff Reliability Index</p>
                        <p class="text-2xl font-black text-slate-905 text-slate-900"><?= $reliabilityRate; ?>%</p>
                    </div>
                    <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm text-center space-y-1">
                        <p class="text-[9px] font-black text-slate-500 uppercase tracking-wider">Late Arrivals</p>
                        <p class="text-2xl font-black text-amber-700"><?= $lateToday; ?></p>
                    </div>
                    <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm text-center space-y-1">
                        <p class="text-[9px] font-black text-slate-500 uppercase tracking-wider">Capacity Variance Loss</p>
                        <p class="text-2xl font-black text-rose-700"><?= $lossRate; ?>%</p>
                    </div>
                </div>

                <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    
                    <div class="bg-white border border-slate-300/80 rounded-xl p-5 shadow-sm lg:col-span-2 flex flex-col">
                        <div class="mb-4">
                            <h4 class="text-xs font-black text-slate-950 uppercase tracking-tight">Labor Volume Trajectory</h4>
                            <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Month-to-date deployment frequency changes.</p>
                        </div>
                        <div class="relative w-full h-[220px] mt-auto">
                            <canvas id="trendChart"></canvas>
                        </div>
                    </div>

                    <div class="bg-white border border-slate-300/80 rounded-xl p-5 shadow-sm flex flex-col">
                        <div class="mb-4">
                            <h4 class="text-xs font-black text-slate-950 uppercase tracking-tight">Roster Proportion Breakdown</h4>
                            <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Absolute distribution slice comparing today's values.</p>
                        </div>
                        <div class="relative w-full h-[180px] mx-auto my-auto flex items-center justify-center">
                            <canvas id="pieChart"></canvas>
                        </div>
                    </div>
                </div>

            </main>

            <footer class="mt-auto border-t border-slate-300 bg-white px-6 py-4 text-center">
                <p class="text-[9px] text-slate-500 font-mono tracking-wider">&copy; 2026 Core HR Engine System Platform • Dynamic Secure Architecture Protocol.</p>
            </footer>
        </div>
    </div>

    <script src="components/sidebar.js"></script>
    <script>
    // High Contrast Light Theme configurations for Chart.js
    const ctxTrend = document.getElementById('trendChart');
    if(ctxTrend) {
        new Chart(ctxTrend, {
            type: 'line',
            data: {
                labels: <?php echo json_encode($trendLabels); ?>,
                datasets: [{
                    label: 'Active Roster Count',
                    data: <?php echo json_encode($trendData); ?>,
                    borderColor: '#3730a3', // Dark deep indigo line
                    backgroundColor: 'rgba(55, 48, 163, 0.04)',
                    fill: true,
                    tension: 0.25,
                    borderWidth: 2.5,
                    pointBackgroundColor: '#3730a3',
                    pointRadius: 4,
                    pointHoverRadius: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: { 
                    y: { 
                        beginAtZero: true, 
                        ticks: { stepSize: 1, color: '#334155', font: { size: 9, family: 'monospace', weight: 'bold' } }, 
                        grid: { color: '#e2e8f0' } 
                    },
                    x: { 
                        ticks: { color: '#334155', font: { size: 9, family: 'monospace', weight: 'bold' } }, 
                        grid: { display: false } 
                    }
                }
            }
        });
    }

    const ctxPie = document.getElementById('pieChart');
    if(ctxPie) {
        new Chart(ctxPie, {
            type: 'doughnut',
            data: {
                labels: ['Present Today', 'Absent Today'],
                datasets: [{
                    data: [<?php echo $presentToday; ?>, <?php echo $absentToday; ?>],
                    backgroundColor: ['#047857', '#be123c'], // Deeper, high-contrast Emerald and Rose tones
                    borderWidth: 2,
                    borderColor: '#ffffff'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { 
                    legend: { 
                        position: 'bottom', 
                        labels: { boxWidth: 10, padding: 12, color: '#1e293b', font: { size: 10, weight: '700', family: 'Mulish' } } 
                    } 
                },
                cutout: '76%'
            }
        });
    }
    </script>
</body>
</html>