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

require '../config.php';
session_start();
session_write_close();

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

$employeeId = intval($_GET['employee_id'] ?? 0);
if (!$employeeId) {
    die("Invalid Employee");
}

$todayStr = date('Y-m-d'); // Current system date indicator

/*
|--------------------------------------------------------------------------
| POST HANDLER: APPROVAL/REJECTION LOGIC
|--------------------------------------------------------------------------
*/
$adminMsg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reg_action'])) {
    $regId = intval($_POST['reg_id']);
    $actionDecision = $_POST['reg_action']; // 'Approved' or 'Rejected'

    if ($actionDecision === 'Approved') {
        $infoStmt = $conn->prepare("SELECT date, requested_check_in, requested_check_out FROM attendance_regularizations WHERE id = ?");
        $infoStmt->bind_param("i", $regId);
        $infoStmt->execute();
        $reqData = $infoStmt->get_result()->fetch_assoc();
        $infoStmt->close();

        if ($reqData) {
            $targetDate = $reqData['date'];
            $fullIn  = !empty($reqData['requested_check_in']) ? $targetDate . ' ' . $reqData['requested_check_in'] : null;
            $fullOut = !empty($reqData['requested_check_out']) ? $targetDate . ' ' . $reqData['requested_check_out'] : null;

            $attStmt = $conn->prepare("
                INSERT INTO attendance (employee_id, date, check_in, check_out)
                VALUES (?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE check_in = VALUES(check_in), check_out = VALUES(check_out)
            ");
            $attStmt->bind_param("isss", $employeeId, $targetDate, $fullIn, $fullOut);
            $attStmt->execute();
            $attStmt->close();
        }
    }

    $upStmt = $conn->prepare("UPDATE attendance_regularizations SET status = ? WHERE id = ?");
    $upStmt->bind_param("si", $actionDecision, $regId);
    if($upStmt->execute()){
        $adminMsg = "Regularization request marker set to: " . $actionDecision;
    }
    $upStmt->close();
}

/*
|--------------------------------------------------------------------------
| EMPLOYEE INFO
|--------------------------------------------------------------------------
*/
$stmt = $conn->prepare("
    SELECT e.*, d.name department
    FROM employees e
    LEFT JOIN departments d ON d.id = e.department_id
    WHERE e.id = ?
    LIMIT 1
");
$stmt->bind_param("i", $employeeId);
$stmt->execute();
$employee = $stmt->get_result()->fetch_assoc();

if (!$employee) {
    die("Employee not found");
}

/*
|--------------------------------------------------------------------------
| ACTIVE NOTIFICATION ALERTS lookup
|--------------------------------------------------------------------------
*/
$pendingRequests = [];
$pStmt = $conn->prepare("SELECT * FROM attendance_regularizations WHERE employee_id = ? AND status = 'Pending' ORDER BY date DESC");
$pStmt->bind_param("i", $employeeId);
$pStmt->execute();
$pRes = $pStmt->get_result();
while ($r = $pRes->fetch_assoc()) {
    $pendingRequests[] = $r;
}
$pStmt->close();

/*
|--------------------------------------------------------------------------
| PERIOD SELECTOR BOUNDARIES
|--------------------------------------------------------------------------
*/
$viewType = $_GET['type'] ?? 'monthly';
$month = intval($_GET['month'] ?? date('m'));
$year  = intval($_GET['year'] ?? date('Y'));

if ($viewType === 'weekly') {
    $selectedDate = $_GET['start'] ?? date('Y-m-d');
    $startDate = date('Y-m-d', strtotime('monday this week', strtotime($selectedDate)));
    $endDate = date('Y-m-d', strtotime($startDate . ' +6 days'));
} else {
    $startDate = "$year-" . str_pad($month, 2, '0', STR_PAD_LEFT) . "-01";
    $endDate   = date('Y-m-t', strtotime($startDate));
}

/*
|--------------------------------------------------------------------------
| SCHEDULE DETAILS MATRIX
|--------------------------------------------------------------------------
*/
$scheduleDays = [];
$stmt = $conn->prepare("
    SELECT ds.schedule_date, s.name AS shift_name, s.checkin AS shift_checkin, s.checkout AS shift_checkout
    FROM department_schedules ds
    INNER JOIN shifts s ON s.id = ds.shift_id
    WHERE ds.employee_id = ?
      AND ds.schedule_date BETWEEN ? AND ?
    ORDER BY ds.schedule_date
");
$stmt->bind_param("iss", $employeeId, $startDate, $endDate);
$stmt->execute();
$res = $stmt->get_result();

while ($row = $res->fetch_assoc()) {
    $sDate = $row['schedule_date'];
    
    // Default status: "Not Resumed" for today/future scheduled days without check-in, "Absent" for past days
    $defaultStatus = ($sDate >= $todayStr) ? 'Not Resumed' : 'Absent';

    $scheduleDays[$sDate] = [
        'date' => $sDate,
        'shift' => strtoupper(trim($row['shift_name'] ?? '')),
        'shift_start' => $row['shift_checkin'],
        'shift_end'   => $row['shift_checkout'],
        'check_in' => '',
        'check_out' => '',
        'hours' => 0,
        'status' => $defaultStatus
    ];
}
$stmt->close();

/*
|--------------------------------------------------------------------------
| ATTENDANCE ATTRIBUTE LOOKUPS
|--------------------------------------------------------------------------
*/
$stmt = $conn->prepare("
    SELECT * FROM attendance WHERE employee_id = ? AND date BETWEEN ? AND ?
");
$stmt->bind_param("iss", $employeeId, $startDate, $endDate);
$stmt->execute();
$res = $stmt->get_result();

$daysWorked = 0;
$totalHours = 0;

while ($row = $res->fetch_assoc()) {
    $date = $row['date'];
    if (!isset($scheduleDays[$date])) {
        continue;
    }

    $hours = 0;
    $checkIn  = $row['check_in'];
    $checkOut = $row['check_out'];

    if (!empty($checkIn) && !empty($checkOut)) {
        $in  = strtotime($checkIn);
        $out = strtotime($checkOut);

        if ($out < $in) { $out += 86400; }

        $hours = round(($out - $in) / 3600, 2);
        $daysWorked++;
        $totalHours += $hours;
        $status = 'Present';

        $shiftStart = $scheduleDays[$date]['shift_start'];
        $shiftEnd   = $scheduleDays[$date]['shift_end'];

        $late = false; $early = false;

        if (!empty($shiftStart)) { $late = strtotime($checkIn) > strtotime($shiftStart) + (15 * 60); }
        if (!empty($shiftEnd)) { $early = strtotime($checkOut) < strtotime($shiftEnd) - (15 * 60); }

        if ($late && $early) { $status = 'Late / Early Departure'; } 
        elseif ($late) { $status = 'Late Arrival'; } 
        elseif ($early) { $status = 'Early Departure'; }

        $scheduleDays[$date]['status'] = $status;
    } else {
        if ($date < $todayStr) {
            $scheduleDays[$date]['status'] = 'Incomplete';
        } elseif ($date === $todayStr) {
            $scheduleDays[$date]['status'] = !empty($checkIn) ? 'In Progress' : 'Not Resumed';
        }
    }

    $scheduleDays[$date]['check_in']  = $checkIn;
    $scheduleDays[$date]['check_out'] = $checkOut;
    $scheduleDays[$date]['hours']     = $hours;
}
$stmt->close();

/*
|--------------------------------------------------------------------------
| APPROVED LEAVES
|--------------------------------------------------------------------------
*/
$stmt = $conn->prepare("
    SELECT lr.start_date, lr.end_date, lt.name AS leave_type
    FROM leave_requests lr
    LEFT JOIN leave_types lt ON lt.id = lr.leave_type_id
    WHERE lr.employee_id = ? AND lr.manager_status = 'Approved' AND lr.hr_status = 'Approved'
");
$stmt->bind_param("i", $employeeId);
$stmt->execute();
$res = $stmt->get_result();

$leaveDays = 0;
$leaveDates = [];

while ($leave = $res->fetch_assoc()) {
    $start = strtotime($leave['start_date']);
    $end   = strtotime($leave['end_date']);

    for ($d = $start; $d <= $end; $d += 86400) {
        $date = date('Y-m-d', $d);
        if (isset($scheduleDays[$date])) {
            if (!in_array($scheduleDays[$date]['status'], ['Present', 'Late Arrival', 'Early Departure', 'Late / Early Departure'])) {
                $leaveType = trim($leave['leave_type'] ?? '');
                if ($leaveType == '') { $leaveType = 'Leave'; }
                $scheduleDays[$date]['status'] = $leaveType;
                $scheduleDays[$date]['is_leave'] = true;

                // The SQL query above already only returns leave requests
                // fully approved by both manager and HR, so every row here
                // is a genuine leave day -- no whitelist-by-type-name needed
                // (the old one only recognized 5 of the 7 real leave types,
                // silently undercounting Study/Unpaid/PH leave and
                // penalizing those employees' attendance percentage).
                $leaveDates[$date] = true;
            }
        }
    }
}
$leaveDays = count($leaveDates);
$stmt->close();

// Is the viewed employee CURRENTLY on leave (today falls inside an
// approved leave range)? Surfaced as a banner near the top of the page.
$activeLeave = null;
foreach ($scheduleDays as $date => $day) {
    if ($date === $todayStr && !empty($day['is_leave'])) {
        $activeLeave = $day['status'];
        break;
    }
}

/*
|--------------------------------------------------------------------------
| OFF / PH / SL VARIANT PARSING
|--------------------------------------------------------------------------
*/
foreach ($scheduleDays as &$day) {
    switch ($day['shift']) {
        case 'OFF': $day['status'] = (!empty($day['check_in']) && !empty($day['check_out'])) ? 'Worked on Off Day' : 'Off'; break;
        case 'PH':  $day['status'] = (!empty($day['check_in']) && !empty($day['check_out'])) ? 'Worked on Public Holiday' : 'Public Holiday'; break;
        case 'SL':  if ($day['status'] == 'Absent') { $day['status'] = 'Sick Leave'; } break;
    }
}
unset($day);

/*
|--------------------------------------------------------------------------
| SUMMARY COUNTS METRIC CALCULATOR
|--------------------------------------------------------------------------
*/
$scheduledDays = 0; $absentDays = 0; $lateCount = 0; $earlyCount = 0;

foreach ($scheduleDays as $day) {
    if ($day['status'] == 'Late Arrival') $lateCount++;
    if ($day['status'] == 'Early Departure') $earlyCount++;
    if ($day['status'] == 'Late / Early Departure') { $lateCount++; $earlyCount++; }

    if (in_array($day['shift'], ['AM', 'PM', 'MOD', 'W'])) { $scheduledDays++; }
    if ($day['status'] === 'Absent') { $absentDays++; }
}

$expectedDays = max(0, $scheduledDays - $leaveDays);
$attendancePercent = 0;
if ($expectedDays > 0) { $attendancePercent = min(100, ($daysWorked / $expectedDays) * 100); }

ksort($scheduleDays);
$attendanceLogs = array_values($scheduleDays);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Attendance Summary - 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>
    <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">Attendance Center</h1>
                        <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">Employee Sheet Evaluation</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($employee['name'] ?? 'Staff'); ?></span>
                        <span class="text-[9px] text-indigo-700 uppercase font-black tracking-wider leading-none mt-0.5"><?= htmlspecialchars($employee['department'] ?? 'Operations'); ?></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($employee['name'] ?? 'S', 0, 1)); ?>
                    </div>
                </div>
            </header>

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

                <?php if(!empty($pendingRequests)): ?>
                <div class="bg-amber-50 border border-amber-300 p-5 rounded-2xl shadow-xs">
                    <h3 class="text-amber-900 font-black text-xs uppercase tracking-wider mb-3 flex items-center gap-2">
                        <span>⚠️</span> Regularization Action Required (<?= count($pendingRequests) ?>)
                    </h3>
                    <div class="space-y-3">
                        <?php foreach($pendingRequests as $req): ?>
                        <div class="bg-white border border-amber-200/60 p-4 rounded-xl flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4 shadow-xs">
                            <div class="space-y-1">
                                <p class="text-xs font-black text-slate-900">
                                    Date: <span class="font-mono text-indigo-600 font-bold"><?= date('d M Y', strtotime($req['date'])) ?></span>
                                </p>
                                <p class="text-[11px] font-bold text-slate-400">
                                    Proposed: In <span class="font-mono text-slate-700 font-extrabold"><?= $req['requested_check_in'] ?? '—' ?></span> | 
                                    Out <span class="font-mono text-slate-700 font-extrabold"><?= $req['requested_check_out'] ?? '—' ?></span>
                                </p>
                                <p class="text-xs text-slate-600 italic bg-slate-50 p-3 rounded-lg border border-slate-200/60 font-medium max-w-xl">
                                    "<?= htmlspecialchars($req['reason'] ?? '') ?>"
                                </p>
                            </div>
                            <form method="POST" class="flex gap-2 w-full lg:w-auto shrink-0">
                                <input type="hidden" name="reg_id" value="<?= $req['id'] ?>">
                                <button type="submit" name="reg_action" value="Approved" class="flex-1 lg:flex-none bg-emerald-600 hover:bg-emerald-700 text-white text-[11px] font-black px-4 py-2.5 rounded-lg transition active:scale-[0.97] uppercase tracking-wider shadow-sm">Approve</button>
                                <button type="submit" name="reg_action" value="Rejected" class="flex-1 lg:flex-none bg-rose-50 hover:bg-rose-100 text-rose-600 text-[11px] font-black px-4 py-2.5 rounded-lg transition active:scale-[0.97] uppercase tracking-wider">Deny</button>
                            </form>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>

                <?php if(!empty($adminMsg)): ?>
                <div class="bg-emerald-50 border border-emerald-350 text-emerald-900 p-4 rounded-xl shadow-xs flex items-start gap-3 transition">
                    <div class="text-base leading-none mt-0.5">✅</div>
                    <div class="space-y-0.5">
                        <h3 class="font-black text-xs text-emerald-950">System Database Success</h3>
                        <p class="text-[11px] text-emerald-700 font-semibold leading-tight"><?= htmlspecialchars($adminMsg) ?></p>
                    </div>
                </div>
                <?php endif; ?>

                <?php if ($activeLeave): ?>
                <div class="bg-violet-50 border border-violet-300 text-violet-900 p-4 rounded-xl shadow-xs flex items-center gap-3">
                    <div class="text-lg leading-none">🌴</div>
                    <div>
                        <h3 class="font-black text-xs text-violet-950">Currently On Leave</h3>
                        <p class="text-[11px] text-violet-700 font-semibold leading-tight"><?= htmlspecialchars($employee['name'] ?? 'This employee') ?> is on approved <?= htmlspecialchars($activeLeave) ?> as of today.</p>
                    </div>
                </div>
                <?php endif; ?>

                <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm space-y-3">
                    <div class="flex items-center justify-between border-b border-slate-200 pb-2">
                        <h3 class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Data Filters</h3>
                        <span class="text-[9px] font-bold text-indigo-700 uppercase">Apply viewing boundaries</span>
                    </div>
                    <form method="GET" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-3 items-end">
                        <input type="hidden" name="employee_id" value="<?= $employeeId ?>">
                        <div>
                            <label class="block text-[10px] font-black text-slate-500 uppercase tracking-wider mb-1">View Scope</label>
                            <select id="viewTypeSelect" name="type" class="w-full border border-slate-300 bg-stone-50 focus:bg-white px-3 py-2 rounded-lg text-xs font-bold text-slate-800 focus:border-indigo-500 outline-none transition" onchange="adaptFormInputs()">
                                <option value="monthly" <?= $viewType == 'monthly' ? 'selected' : '' ?>>Monthly Breakdown</option>
                                <option value="weekly" <?= $viewType == 'weekly' ? 'selected' : '' ?>>Weekly Snapshot</option>
                            </select>
                        </div>
                        
                        <div class="month-input-group">
                            <label class="block text-[10px] font-black text-slate-500 uppercase tracking-wider mb-1">Month</label>
                            <select name="month" class="w-full border border-slate-300 bg-stone-50 focus:bg-white px-3 py-2 rounded-lg text-xs font-bold text-slate-800 focus:border-indigo-500 outline-none transition">
                                <?php for($m=1; $m<=12; $m++): ?>
                                    <option value="<?= $m ?>" <?= ($month) == $m ? 'selected' : '' ?>><?= date('F', mktime(0, 0, 0, $m, 1)) ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>
                        <div class="month-input-group">
                            <label class="block text-[10px] font-black text-slate-500 uppercase tracking-wider mb-1">Year</label>
                            <input type="number" name="year" value="<?= $year ?>" class="w-full border border-slate-300 bg-stone-50 focus:bg-white px-3 py-2 rounded-lg text-xs font-black font-mono text-slate-800 focus:border-indigo-500 outline-none transition">
                        </div>
                        
                        <div class="week-input-group hidden">
                            <label class="block text-[10px] font-black text-slate-500 uppercase tracking-wider mb-1">Week Commencement</label>
                            <input type="date" name="start" value="<?= htmlspecialchars($_GET['start'] ?? date('Y-m-d')) ?>" class="w-full border border-slate-300 bg-stone-50 focus:bg-white px-3 py-2 rounded-lg text-xs font-extrabold font-mono text-slate-800 focus:border-indigo-500 outline-none transition">
                        </div>
                        
                        <div class="lg:col-span-1 sm:col-span-2">
                            <button class="w-full bg-slate-900 hover:bg-slate-800 active:scale-[0.99] transition text-white rounded-lg font-bold py-2 text-xs shadow-sm border border-slate-950">Apply Parameters</button>
                        </div>
                    </form>
                </div>

                <div class="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-8 gap-3">
                    <div class="bg-white p-4 rounded-xl text-center border border-slate-300/80 shadow-sm">
                        <span class="text-[9px] font-black text-slate-500 uppercase block tracking-wider">Scheduled</span>
                        <h2 class="text-xl font-black text-slate-850 font-mono mt-1"><?= $scheduledDays ?></h2>
                    </div>
                    <div class="bg-white p-4 rounded-xl text-center border border-slate-300/80 shadow-sm">
                        <span class="text-[9px] font-black text-slate-500 uppercase block tracking-wider">Worked</span>
                        <h2 class="text-xl font-black text-emerald-600 font-mono mt-1"><?= $daysWorked ?></h2>
                    </div>
                    <div class="bg-white p-4 rounded-xl text-center border border-slate-300/80 shadow-sm">
                        <span class="text-[9px] font-black text-slate-500 uppercase block tracking-wider">Absent</span>
                        <h2 class="text-xl font-black text-rose-500 font-mono mt-1"><?= $absentDays ?></h2>
                    </div>
                    <div class="bg-white p-4 rounded-xl text-center border border-slate-300/80 shadow-sm">
                        <span class="text-[9px] font-black text-slate-500 uppercase block tracking-wider">Leave</span>
                        <h2 class="text-xl font-black text-violet-600 font-mono mt-1"><?= $leaveDays ?></h2>
                    </div>
                    <div class="bg-white p-4 rounded-xl text-center border border-slate-300/80 shadow-sm">
                        <span class="text-[9px] font-black text-slate-500 uppercase block tracking-wider">Hours</span>
                        <h2 class="text-xl font-black text-indigo-600 font-mono mt-1"><?= number_format($totalHours, 1) ?></h2>
                    </div>
                    <div class="bg-white p-4 rounded-xl text-center border border-slate-300/80 shadow-sm">
                        <span class="text-[9px] font-black text-slate-500 uppercase block tracking-wider">Attendance</span>
                        <h2 class="text-xl font-black text-purple-600 font-mono mt-1"><?= number_format($attendancePercent, 1) ?>%</h2>
                    </div>
                    <div class="bg-white p-4 rounded-xl text-center border border-slate-300/80 shadow-sm">
                        <span class="text-[9px] font-black text-slate-500 uppercase block tracking-wider">Lates</span>
                        <h2 class="text-xl font-black text-amber-500 font-mono mt-1"><?= $lateCount ?></h2>
                    </div>
                    <div class="bg-white p-4 rounded-xl text-center border border-slate-300/80 shadow-sm">
                        <span class="text-[9px] font-black text-slate-500 uppercase block tracking-wider">Earlies</span>
                        <h2 class="text-xl font-black text-orange-500 font-mono mt-1"><?= $earlyCount ?></h2>
                    </div>
                </div>

                <div class="bg-white border border-slate-300/80 rounded-xl shadow-sm overflow-hidden">
                    <div class="px-4 py-3 bg-stone-50/50 border-b border-slate-300/80 flex items-center justify-between">
                        <div>
                            <h3 class="text-xs font-black text-slate-950 uppercase tracking-tight">System Logs</h3>
                            <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Detailed biometric evaluation data points.</p>
                        </div>
                        <span class="bg-indigo-50 text-indigo-800 border border-indigo-200 px-2.5 py-1 rounded-md font-extrabold text-[10px] font-mono shadow-xs">
                            <?= count($attendanceLogs); ?> Loaded
                        </span>
                    </div>
                    
                    <div class="overflow-x-auto w-full">
                        <table class="w-full min-w-[800px] border-collapse">
                            <thead>
                                <tr class="bg-stone-50 text-slate-500 uppercase text-[9px] font-black tracking-wider border-b border-slate-300/80">
                                    <th class="p-3 text-left">Date</th>
                                    <th class="p-3 text-center">Shift</th>
                                    <th class="p-3 text-center">Check In</th>
                                    <th class="p-3 text-center">Check Out</th>
                                    <th class="p-3 text-center">Total Hours</th>
                                    <th class="p-3 text-center">Status</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-200/80 text-xs font-bold">
                                <?php if (empty($attendanceLogs)): ?>
                                <tr>
                                    <td colspan="6" class="text-center py-12">
                                        <div class="flex flex-col items-center justify-center space-y-2">
                                            <div class="text-3xl">📭</div>
                                            <h4 class="text-xs font-extrabold text-slate-800">No Target Match Logs Found</h4>
                                            <p class="text-[10px] text-slate-600 max-w-xs">Adjust query parameters or apply standard sync processes.</p>
                                        </div>
                                    </td>
                                </tr>
                                <?php endif; ?>

                                <?php foreach($attendanceLogs as $log): ?>
                                <tr class="hover:bg-stone-50/50 transition text-slate-800">
                                    <td class="p-3 font-black whitespace-nowrap font-mono"><?= date('d M Y', strtotime($log['date'])) ?></td>
                                    <td class="p-3 text-center whitespace-nowrap">
                                        <span class="bg-stone-100 px-2.5 py-1 rounded-md text-[10px] font-black border border-slate-300/50"><?= htmlspecialchars($log['shift']) ?></span>
                                    </td>
                                    <td class="p-3 text-center font-mono text-slate-700 whitespace-nowrap"><?= $log['check_in'] ? date('H:i', strtotime($log['check_in'])) : '—' ?></td>
                                    <td class="p-3 text-center font-mono text-slate-700 whitespace-nowrap"><?= $log['check_out'] ? date('H:i', strtotime($log['check_out'])) : '—' ?></td>
                                    <td class="p-3 text-center whitespace-nowrap">
                                        <span class="bg-emerald-50 text-emerald-800 border border-emerald-200 px-2 py-0.5 rounded font-black text-[10px] font-mono">
                                            <?= number_format($log['hours'], 2) ?> hrs
                                        </span>
                                    </td>
                                    <td class="p-3 text-center whitespace-nowrap">
                                        <?php
                                        $status = $log['status'];
                                        $colors = [
                                            'Present' => 'bg-emerald-50 text-emerald-800 border border-emerald-300', 
                                            'Late Arrival' => 'bg-amber-50 text-amber-900 border border-amber-300',
                                            'Early Departure' => 'bg-orange-50 text-orange-900 border border-orange-300', 
                                            'Absent' => 'bg-rose-50 text-rose-900 border border-rose-300',
                                            'Incomplete' => 'bg-stone-100 text-slate-750 border border-slate-300', 
                                            'In Progress' => 'bg-blue-50 text-blue-800 border border-blue-300',
                                            'Off' => 'bg-stone-50 text-slate-700 border border-slate-300',
                                            'Worked on Off Day' => 'bg-cyan-50 text-cyan-900 border border-cyan-300',
                                            'Public Holiday' => 'bg-sky-50 text-sky-900 border border-sky-300',
                                            'Worked on Public Holiday' => 'bg-sky-50 text-sky-900 border border-sky-300',
                                            'Not Resumed' => 'bg-indigo-50 text-indigo-800 border border-indigo-200'
                                        ];
                                        // A leave day gets one consistent, distinct look regardless of the
                                        // specific leave type name -- string-matching against a fixed
                                        // dictionary here would have the exact same "silently missing new
                                        // leave types" problem the stats-counting bug above had.
                                        $badgeClass = !empty($log['is_leave'])
                                            ? 'bg-violet-50 text-violet-900 border border-violet-300'
                                            : ($colors[$status] ?? 'bg-indigo-50 text-indigo-800 border border-indigo-200');
                                        $statusLabel = !empty($log['is_leave']) ? '🌴 ' . $status : $status;
                                        ?>
                                        <span class="px-2.5 py-1 rounded-md text-[10px] font-black inline-block min-w-[85px] text-center uppercase border <?= $badgeClass ?>"><?= htmlspecialchars($statusLabel) ?></span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </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>
    function adaptFormInputs() {
        const selectScope = document.getElementById('viewTypeSelect').value;
        const monthGroups = document.querySelectorAll('.month-input-group');
        const weekGroups = document.querySelectorAll('.week-input-group');

        if (selectScope === 'weekly') {
            monthGroups.forEach(el => el.classList.add('hidden'));
            weekGroups.forEach(el => el.classList.remove('hidden'));
        } else {
            monthGroups.forEach(el => el.classList.remove('hidden'));
            weekGroups.forEach(el => el.classList.add('hidden'));
        }
    }

    // Run immediately rather than waiting for DOMContentLoaded -- this script
    // tag only ever executes once the surrounding markup already exists,
    // whether that's on a normal page load or after an AJAX navigation swap
    // (DOMContentLoaded only ever fires once per real browser page load).
    adaptFormInputs();
    </script>
</body>
</html>