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

if (session_status() === PHP_SESSION_NONE && !headers_sent()) {
    session_start();
    session_write_close();
}

// Adjust relative path to config file as needed
require_once __DIR__ . '/../config.php';

if (!isset($_SESSION['user_id'])) {
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => 'Session expired. Please log in again.']);
        exit;
    }
    header("Location: /ivm/public/login.php");
    exit;
}

$userId   = intval($_SESSION['user_id']);
$username = $_SESSION['username'] ?? 'Staff Member';
$role     = $_SESSION['role']     ?? 'Staff';

/* --- PERMISSION & ROLE DEFINITIONS --- */
$roleLower     = strtolower(trim($role));
$isAdminOrHr   = in_array($roleLower, ['admin', 'superadmin', 'hr', 'human resources']);
$isManager     = in_array($roleLower, ['manager', 'dept head', 'department head', 'supervisor', 'gm', 'opm']);
$canViewOthers = $isAdminOrHr || $isManager;
$canEditLogs   = $isAdminOrHr || $isManager;

/* --- LOGGED-IN EMPLOYEE & DEPARTMENT LOOKUP --- */
$stmt = $conn->prepare("SELECT id, name, department_id FROM employees WHERE user_id = ? LIMIT 1");
$stmt->bind_param("i", $userId);
$stmt->execute();
$currentEmp   = $stmt->get_result()->fetch_assoc();
$myEmployeeId = $currentEmp ? intval($currentEmp['id']) : 0;
$myDeptId     = $currentEmp ? intval($currentEmp['department_id']) : 0;
$stmt->close();

/* --- SCOPE & EMPLOYEE SELECTION --- */
$allEmployees = [];

if ($isAdminOrHr) {
    $empRes = $conn->query("SELECT id, name FROM employees ORDER BY name ASC");
    while ($empRow = $empRes->fetch_assoc()) {
        $allEmployees[] = $empRow;
    }
} elseif ($isManager && $myDeptId > 0) {
    $empStmt = $conn->prepare("SELECT id, name FROM employees WHERE department_id = ? ORDER BY name ASC");
    $empStmt->bind_param("i", $myDeptId);
    $empStmt->execute();
    $empRes = $empStmt->get_result();
    while ($empRow = $empRes->fetch_assoc()) {
        $allEmployees[] = $empRow;
    }
    $empStmt->close();
}

if ($canViewOthers) {
    $employeeId = isset($_REQUEST['employee_id']) ? intval($_REQUEST['employee_id']) : ($myEmployeeId ?: ($allEmployees[0]['id'] ?? 0));
    
    if ($isManager && !$isAdminOrHr) {
        $allowedIds = array_column($allEmployees, 'id');
        if (!in_array($employeeId, $allowedIds)) {
            $employeeId = $myEmployeeId;
        }
    }
} else {
    if (!$myEmployeeId) {
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
            header('Content-Type: application/json');
            echo json_encode(['status' => 'error', 'message' => 'Employee record not found.']);
            exit;
        }
        die("Employee record not found for your logged-in account.");
    }
    $employeeId = $myEmployeeId;
}

/* --- TARGET EMPLOYEE DETAILS --- */
$targetEmpName = 'Employee';
if ($employeeId > 0) {
    $stmt = $conn->prepare("SELECT name FROM employees WHERE id = ? LIMIT 1");
    $stmt->bind_param("i", $employeeId);
    $stmt->execute();
    $targetEmpName = ($stmt->get_result()->fetch_assoc())['name'] ?? 'Employee';
    $stmt->close();
}

/* --- FILTERS & POST ACTIONS --- */
$selectedMonth = isset($_REQUEST['month']) ? intval($_REQUEST['month']) : intval(date('m'));
$selectedYear  = isset($_REQUEST['year'])  ? intval($_REQUEST['year'])  : intval(date('Y'));

$message = '';
$messageClass = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'request_regularization') {
    $reqDate = $_POST['req_date'];
    $reqIn   = !empty($_POST['requested_check_in'])  ? $_POST['requested_check_in']  : null;
    $reqOut  = !empty($_POST['requested_check_out']) ? $_POST['requested_check_out'] : null;
    $reason  = trim($_POST['reason']);
    $postTargetEmpId = isset($_POST['target_employee_id']) ? intval($_POST['target_employee_id']) : $employeeId;

    if (empty($reason)) {
        $message = "Please provide a reason or note for this action.";
        $messageClass = "bg-rose-50 border-rose-300 text-rose-900";
    } else {
        if ($canEditLogs) {
            if ($isManager && !$isAdminOrHr) {
                $chkStmt = $conn->prepare("SELECT department_id FROM employees WHERE id = ? LIMIT 1");
                $chkStmt->bind_param("i", $postTargetEmpId);
                $chkStmt->execute();
                $targetDept = ($chkStmt->get_result()->fetch_assoc())['department_id'] ?? 0;
                $chkStmt->close();

                if (intval($targetDept) !== $myDeptId) {
                    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
                        header('Content-Type: application/json');
                        echo json_encode(['status' => 'error', 'message' => 'Unauthorized action for an employee outside your department.']);
                        exit;
                    }
                    die("Unauthorized action for an employee outside your department.");
                }
            }

            $stmt = $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)
            ");
            $stmt->bind_param("isss", $postTargetEmpId, $reqDate, $reqIn, $reqOut);
            
            if ($stmt->execute()) {
                $stmtReg = $conn->prepare("UPDATE attendance_regularizations SET status = 'Approved' WHERE employee_id = ? AND date = ?");
                $stmtReg->bind_param("is", $postTargetEmpId, $reqDate);
                $stmtReg->execute();
                $stmtReg->close();

                $message = "Attendance logs updated directly by " . htmlspecialchars($role) . ".";
                $messageClass = "bg-emerald-50 border-emerald-300 text-emerald-900";
            } else {
                $message = "Error updating attendance log direct entry.";
                $messageClass = "bg-rose-50 border-rose-300 text-rose-900";
            }
            $stmt->close();
        } else {
            $stmt = $conn->prepare("
                INSERT INTO attendance_regularizations (employee_id, date, requested_check_in, requested_check_out, reason, status)
                VALUES (?, ?, ?, ?, ?, 'Pending')
                ON DUPLICATE KEY UPDATE requested_check_in = VALUES(requested_check_in), requested_check_out = VALUES(requested_check_out), reason = VALUES(reason), status = 'Pending'
            ");
            $stmt->bind_param("issss", $myEmployeeId, $reqDate, $reqIn, $reqOut, $reason);
            $message = $stmt->execute() ? "Regularization request submitted successfully." : "Error submitting request.";
            $messageClass = $stmt->execute() ? "bg-emerald-50 border-emerald-300 text-emerald-900" : "bg-rose-50 border-rose-300 text-rose-900";
            $stmt->close();
        }
    }
}

/* --- LOOKUPS & DATA QUERY --- */
$regLookup = [];
$regStmt = $conn->prepare("SELECT date, status FROM attendance_regularizations WHERE employee_id = ?");
$regStmt->bind_param("i", $employeeId);
$regStmt->execute();
$regRes = $regStmt->get_result();
while($r = $regRes->fetch_assoc()) { $regLookup[$r['date']] = $r['status']; }
$regStmt->close();

// Approved leave days for the selected employee/month, and whether they're
// on leave RIGHT NOW (today falls inside an approved range) -- this page
// previously had no leave awareness at all, so someone on approved leave
// just showed up as plain "Absent" here, same as an unexplained no-show.
$leaveByDate = [];
$activeLeave = null;
$monthStart = sprintf('%04d-%02d-01', $selectedYear, $selectedMonth);
$monthEnd = date('Y-m-t', strtotime($monthStart));
$todayDateForLeave = date('Y-m-d');
$leaveStmt = $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'
      AND lr.start_date <= ? AND lr.end_date >= ?
");
$leaveStmt->bind_param("iss", $employeeId, $monthEnd, $monthStart);
$leaveStmt->execute();
$leaveRes = $leaveStmt->get_result();
while ($leave = $leaveRes->fetch_assoc()) {
    $leaveType = trim($leave['leave_type'] ?? '') ?: 'Leave';
    $rangeStart = max(strtotime($leave['start_date']), strtotime($monthStart));
    $rangeEnd = min(strtotime($leave['end_date']), strtotime($monthEnd));
    for ($d = $rangeStart; $d <= $rangeEnd; $d += 86400) {
        $leaveByDate[date('Y-m-d', $d)] = $leaveType;
    }
    if ($leave['start_date'] <= $todayDateForLeave && $leave['end_date'] >= $todayDateForLeave) {
        $activeLeave = $leaveType;
    }
}
$leaveStmt->close();

$stmt = $conn->prepare("
    SELECT
        ds.schedule_date, s.name AS shift_name, s.checkin AS shift_start, s.checkout AS shift_end,
        a.check_in, a.check_out
    FROM department_schedules ds
    LEFT JOIN shifts s ON s.id = ds.shift_id
    LEFT JOIN attendance a ON a.employee_id = ds.employee_id AND a.date = ds.schedule_date
    WHERE ds.employee_id = ? AND MONTH(ds.schedule_date) = ? AND YEAR(ds.schedule_date) = ?
    ORDER BY ds.schedule_date ASC
");
$stmt->bind_param("iii", $employeeId, $selectedMonth, $selectedYear);
$stmt->execute();
$result = $stmt->get_result();

$rows = [];
$worked = $absent = $late = $offDays = $publicHolidays = $scheduled = $onLeave = 0;
$todayDate = date('Y-m-d');

while ($row = $result->fetch_assoc()) {
    $status = 'Absent';
    $shiftName = strtoupper(trim($row['shift_name'] ?? ''));
    $isLeave = false;

    if ($shiftName === 'PH') {
        $status = 'Public Holiday';
    } elseif ($shiftName === 'OFF') {
        $status = 'Off';
    } elseif (!empty($row['check_in']) && !empty($row['check_out'])) {
        $status = 'Present';
        if (!empty($row['shift_start']) && (strtotime($row['check_in']) > strtotime($row['shift_start']) + 900)) {
            $status = 'Late Arrival';
        }
    } elseif (in_array($shiftName, ['AM', 'PM', 'MOD', 'W']) || !empty($shiftName)) {
        if ($row['schedule_date'] > $todayDate) {
            $status = 'Scheduled';
        } else {
            $status = 'Absent';
        }
    }

    // Approved leave takes priority over whatever the schedule/shift would
    // otherwise imply, unless they actually clocked in that day.
    if (isset($leaveByDate[$row['schedule_date']]) && !in_array($status, ['Present', 'Late Arrival'], true)) {
        $status = $leaveByDate[$row['schedule_date']];
        $isLeave = true;
    }

    switch ($status) {
        case 'Public Holiday': $publicHolidays++; break;
        case 'Off': $offDays++; break;
        case 'Present': $worked++; break;
        case 'Late Arrival': $worked++; $late++; break;
        case 'Scheduled': $scheduled++; break;
        case 'Absent': $absent++; break;
    }
    if ($isLeave) { $onLeave++; }

    $row['status'] = $status;
    $row['is_leave'] = $isLeave;
    $rows[] = $row;
}
$stmt->close();

/* --- AJAX JSON RESPONSE HANDLER --- */
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
    header('Content-Type: application/json');

    // Buffer HTML for Header Title Block
    ob_start(); ?>
    <h1 class="text-lg font-black text-slate-900 tracking-tight">
        <?= $canViewOthers && $employeeId !== $myEmployeeId ? htmlspecialchars($targetEmpName) . "'s Attendance Log" : "My Attendance Ledger" ?>
    </h1>
    <p class="text-xs text-slate-500 font-semibold mt-0.5">Viewing period for <?= date("F Y", mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)) ?></p>
    <?php $headerHtml = ob_get_clean();

    // Buffer HTML for Alert Message
    ob_start();
    if(!empty($message)): ?>
    <div id="msg-alert" class="<?= $messageClass ?> p-4 rounded-xl shadow-xs border 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-slate-950">System Action Message</h3>
            <p class="text-[11px] font-semibold leading-tight"><?= htmlspecialchars($message) ?></p>
        </div>
    </div>
    <?php endif;
    $alertHtml = ob_get_clean();

    // Buffer HTML for Table Container
    ob_start();
    if (empty($rows)): ?>
    <div class="text-center py-16">
        <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 Attendance Tracks Found</h4>
            <p class="text-[10px] text-slate-500 max-w-xs">No roster schedules registered for this monthly period.</p>
            <button onclick="openRegularizationModal('<?= date('Y-m-d') ?>', '', '')" class="mt-4 bg-slate-900 hover:bg-slate-800 transition text-white rounded-lg font-bold py-2 px-4 text-xs shadow-sm active:scale-95">
                File Manual Logging Request
            </button>
        </div>
    </div>
    <?php else: ?>
    <!-- Mobile Responsive View -->
    <div class="block md:hidden divide-y divide-slate-100 max-h-[600px] overflow-y-auto font-bold">
        <?php foreach($rows as $row): 
            $badge = match($row['status']) {
                'Present' => 'bg-emerald-50 text-emerald-800 border-emerald-300',
                'Late Arrival' => 'bg-amber-50 text-amber-900 border-amber-300',
                'Absent' => 'bg-rose-50 text-rose-900 border-rose-300',
                'Scheduled' => 'bg-indigo-50 text-indigo-900 border-indigo-300',
                'Public Holiday' => 'bg-sky-50 text-sky-900 border-sky-300',
                default => 'bg-slate-100 text-slate-700 border-slate-300'
            };
            if (!empty($row['is_leave'])) { $badge = 'bg-violet-50 text-violet-900 border-violet-300'; }
            $cIn = $row['check_in'] ? date('H:i', strtotime($row['check_in'])) : '';
            $cOut = $row['check_out'] ? date('H:i', strtotime($row['check_out'])) : '';
            $isFixableStatus = in_array($row['status'], ['Absent', 'Off']) && empty($row['is_leave']);
        ?>
        <div class="p-4 flex items-center justify-between gap-3 hover:bg-slate-50/50 transition text-slate-800">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-slate-100 border border-slate-200 flex flex-col items-center justify-center text-center shrink-0">
                    <span class="text-xs font-black text-slate-900 leading-none"><?= date('d', strtotime($row['schedule_date'])) ?></span>
                    <span class="text-[8px] font-black text-slate-500 uppercase tracking-tight mt-0.5"><?= date('M', strtotime($row['schedule_date'])) ?></span>
                </div>
                <div class="space-y-1">
                    <div class="flex items-center gap-1.5 flex-wrap">
                        <span class="text-[9px] font-black px-2 py-0.5 border rounded-md uppercase tracking-wider <?= $badge ?>">
                            <?= $row['status'] === 'Late Arrival' ? 'LATE' : (!empty($row['is_leave']) ? '🌴 ' . $row['status'] : $row['status']) ?>
                        </span>
                        <span class="text-[9px] text-indigo-700 font-black px-1.5 py-0.5 rounded border border-indigo-100 bg-indigo-50/50">
                            <?= htmlspecialchars($row['shift_name'] ?? '-') ?>
                        </span>
                    </div>
                    <p class="text-[10px] font-mono text-slate-600 flex items-center gap-1">
                        <span class="font-bold text-slate-900">IN:</span><?= $row['check_in'] ? date('h:i A', strtotime($row['check_in'])) : '--:--' ?> 
                        <span class="font-bold text-slate-900 ml-1">OUT:</span><?= $row['check_out'] ? date('h:i A', strtotime($row['check_out'])) : '--:--' ?>
                    </p>
                </div>
            </div>

            <div class="shrink-0">
                <?php if ($canEditLogs): ?>
                    <?php if ($isFixableStatus): ?>
                        <button type="button" onclick="openRegularizationModal('<?= $row['schedule_date'] ?>', '<?= $cIn ?>', '<?= $cOut ?>')" class="bg-indigo-600 hover:bg-indigo-700 text-white font-black px-2.5 py-1 rounded-md text-[10px] uppercase tracking-wider transition active:scale-95 shadow-xs">
                            Fix Log
                        </button>
                    <?php else: ?>
                        <span class="text-slate-300 font-black text-xs mr-2">—</span>
                    <?php endif; ?>
                <?php elseif (isset($regLookup[$row['schedule_date']])): 
                    $regStat = $regLookup[$row['schedule_date']];
                    $statCol = match($regStat) { 'Pending' => 'bg-amber-50 text-amber-900 border-amber-300', 'Approved' => 'bg-emerald-50 text-emerald-900 border-emerald-300', default => 'bg-rose-50 text-rose-900 border-rose-300' };
                ?>
                    <span class="text-[9px] font-black px-2 py-1 rounded-md border <?= $statCol ?> font-mono">RG: <?= strtoupper(substr($regStat, 0, 4)) ?></span>
                <?php elseif ($isFixableStatus && $row['schedule_date'] <= $todayDate): ?>
                    <button type="button" onclick="openRegularizationModal('<?= $row['schedule_date'] ?>', '<?= $cIn ?>', '<?= $cOut ?>')" class="bg-indigo-600 hover:bg-indigo-700 text-white font-black px-2.5 py-1 rounded-md text-[10px] uppercase tracking-wider transition active:scale-95 shadow-xs">
                        Fix Log
                    </button>
                <?php else: ?>
                    <span class="text-slate-300 font-black text-xs mr-2">—</span>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- Desktop Table View -->
    <div class="hidden md:block overflow-x-auto w-full">
        <table class="w-full border-collapse">
            <thead>
                <tr class="bg-slate-50/80 text-slate-400 uppercase text-[10px] font-black tracking-wider border-b border-slate-100">
                    <th class="p-3.5 text-left pl-6">Date</th>
                    <th class="p-3.5 text-center">Shift</th>
                    <th class="p-3.5 text-center">Check In</th>
                    <th class="p-3.5 text-center">Check Out</th>
                    <th class="p-3.5 text-center">Status</th>
                    <th class="p-3.5 pr-6 text-center">Action</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-100 text-xs font-bold">
                <?php foreach($rows as $row): 
                    $badgeColor = match($row['status']) {
                        'Present' => 'bg-emerald-50 text-emerald-800 border-emerald-300',
                        'Late Arrival' => 'bg-amber-50 text-amber-900 border-amber-300',
                        'Absent' => 'bg-rose-50 text-rose-900 border-rose-300',
                        'Scheduled' => 'bg-indigo-50 text-indigo-900 border-indigo-300',
                        'Public Holiday' => 'bg-sky-50 text-sky-900 border-sky-300',
                        default => 'bg-slate-100 text-slate-700 border-slate-300'
                    };
                    if (!empty($row['is_leave'])) { $badgeColor = 'bg-violet-50 text-violet-900 border-violet-300'; }
                    $cIn = $row['check_in'] ? date('H:i', strtotime($row['check_in'])) : '';
                    $cOut = $row['check_out'] ? date('H:i', strtotime($row['check_out'])) : '';
                    $isFixableStatus = in_array($row['status'], ['Absent', 'Off']) && empty($row['is_leave']);
                ?>
                    <tr class="hover:bg-slate-50/80 transition text-slate-800">
                        <td class="p-3.5 pl-6 font-extrabold text-slate-900 whitespace-nowrap"><?= date('d M Y (D)', strtotime($row['schedule_date'])) ?></td>
                        <td class="p-3.5 text-center whitespace-nowrap">
                            <span class="bg-slate-100 text-slate-700 px-2.5 py-1 rounded-md border border-slate-200 font-black text-[10px] uppercase tracking-wider"><?= htmlspecialchars($row['shift_name'] ?? '—') ?></span>
                        </td>
                        <td class="p-3.5 text-center font-mono text-xs text-slate-700 whitespace-nowrap"><?= $row['check_in'] ? date('h:i A', strtotime($row['check_in'])) : '<span class="text-slate-300 font-normal">—</span>' ?></td>
                        <td class="p-3.5 text-center font-mono text-xs text-slate-700 whitespace-nowrap"><?= $row['check_out'] ? date('h:i A', strtotime($row['check_out'])) : '<span class="text-slate-300 font-normal">—</span>' ?></td>
                        <td class="p-3.5 text-center whitespace-nowrap">
                            <span class="px-2.5 py-0.5 rounded-full text-[10px] font-black tracking-wider border <?= $badgeColor ?>"><?= (!empty($row['is_leave']) ? '🌴 ' : '') . strtoupper($row['status']) ?></span>
                        </td>
                        <td class="p-3.5 pr-6 text-center whitespace-nowrap">
                            <?php if ($canEditLogs): ?>
                                <?php if ($isFixableStatus): ?>
                                    <button type="button" onclick="openRegularizationModal('<?= $row['schedule_date'] ?>', '<?= $cIn ?>', '<?= $cOut ?>')" class="bg-indigo-50 hover:bg-indigo-100 text-indigo-700 px-3 py-1 rounded-md text-[10px] font-black uppercase tracking-wider transition border border-indigo-200 shadow-xs">Fix Log</button>
                                <?php else: ?>
                                    <span class="text-slate-300 text-xs">—</span>
                                <?php endif; ?>
                            <?php elseif (isset($regLookup[$row['schedule_date']])): 
                                $regStat = $regLookup[$row['schedule_date']];
                                $statColor = match($regStat) { 'Pending' => 'text-amber-900 bg-amber-50 border-amber-300', 'Approved' => 'text-emerald-900 bg-emerald-50 border-emerald-300', default => 'text-rose-900 bg-rose-50 border-rose-300' };
                            ?>
                                <span class="text-[10px] font-black px-2 py-1 rounded-md border <?= $statColor ?> font-mono">Reg. <?= $regStat ?></span>
                            <?php elseif ($isFixableStatus && $row['schedule_date'] <= $todayDate): ?>
                                <button type="button" onclick="openRegularizationModal('<?= $row['schedule_date'] ?>', '<?= $cIn ?>', '<?= $cOut ?>')" class="bg-indigo-50 hover:bg-indigo-100 text-indigo-700 px-3 py-1 rounded-md text-[10px] font-black uppercase tracking-wider transition border border-indigo-200 shadow-xs">Fix Log</button>
                            <?php else: ?>
                                <span class="text-slate-300 text-xs">—</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif;
    $tableHtml = ob_get_clean();

    echo json_encode([
        'status'     => 'success',
        'kpis'       => [
            'worked'    => $worked . 'd',
            'absent'    => $absent . 'd',
            'late'      => $late . 'd',
            'scheduled' => $scheduled . 'd',
            'off_ph'    => ($offDays + $publicHolidays) . 'd'
        ],
        'headerHtml' => $headerHtml,
        'alertHtml'  => $alertHtml,
        'tableHtml'  => $tableHtml,
        'employeeId' => $employeeId
    ]);
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Attendance Ledger - ESS</title>
    
    <!-- Mulish Font -->
    <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:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Custom Sidebar CSS -->
    <link rel="stylesheet" href="../components/sidebar.css">
</head>
<body class="bg-slate-50 font-['Mulish',sans-serif] text-slate-800 antialiased selection:bg-indigo-600 selection:text-white relative">

    <!-- GLOBAL AJAX LOADING SPINNER SPINNER OVERLAY -->
    <div id="loading-spinner" class="fixed inset-0 bg-slate-900/20 backdrop-blur-[2px] hidden items-center justify-center z-[100] transition-all">
        <div class="bg-white p-5 rounded-2xl shadow-2xl border border-slate-100 flex flex-col items-center gap-3">
            <svg class="animate-spin h-8 w-8 text-indigo-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            <span class="text-xs font-black text-slate-700 tracking-wider uppercase">Updating Log...</span>
        </div>
    </div>

    <!-- SIDEBAR INCLUDE -->
    <?php include '../components/sidebar.php'; ?>
    
    <!-- MOBILE BACKDROP OVERLAY -->
    <div id="sidebar-overlay" class="fixed inset-0 bg-slate-900/40 hidden md:hidden z-40 transition-opacity duration-300" onclick="toggleSidebar()"></div>

    <!-- MAIN CONTENT AREA -->
    <div id="main-content" class="flex-1 min-w-0 md:pl-60 transition-all duration-300 min-h-screen flex flex-col">
        
        <!-- MOBILE TOP TRIGGER BAR -->
        <div class="mobile-trigger-bar md:hidden flex items-center justify-between bg-white border-b border-slate-200 px-4 py-3 shrink-0">
            <button onclick="toggleSidebar()" class="text-slate-600 p-1 rounded-lg hover:bg-slate-100 focus:outline-none active:scale-95 transition" aria-label="Toggle Navigation Drawer">
                <svg class="w-6 h-6" 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>
            <span class="font-bold text-xs text-slate-900 uppercase tracking-wider">Attendance Ledger</span>
            <div class="w-6"></div>
        </div>

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

            <!-- Message Notification Alert Container -->
            <div id="alert-container">
                <?php if(!empty($message)): ?>
                <div id="msg-alert" class="<?= $messageClass ?> p-4 rounded-xl shadow-xs border 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-slate-950">System Action Message</h3>
                        <p class="text-[11px] font-semibold leading-tight"><?= htmlspecialchars($message) ?></p>
                    </div>
                </div>
                <?php endif; ?>
            </div>

            <!-- Filter Controls Header -->
            <div class="bg-white border border-slate-200/80 p-5 rounded-2xl shadow-sm flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
                <div id="header-title-block">
                    <h1 class="text-lg font-black text-slate-900 tracking-tight">
                        <?= $canViewOthers && $employeeId !== $myEmployeeId ? htmlspecialchars($targetEmpName) . "'s Attendance Log" : "My Attendance Ledger" ?>
                    </h1>
                    <p class="text-xs text-slate-500 font-semibold mt-0.5">Viewing period for <?= date("F Y", mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)) ?></p>
                </div>

                <form id="filter-form" method="GET" class="flex flex-wrap items-center gap-2 w-full sm:w-auto" onsubmit="handleFilterSubmit(event)">
                    <?php if ($canViewOthers && !empty($allEmployees)): ?>
                    <select name="employee_id" class="bg-slate-50 border border-slate-300 text-xs font-bold text-slate-800 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none transition">
                        <?php foreach ($allEmployees as $emp): ?>
                            <option value="<?= $emp['id'] ?>" <?= $emp['id'] === $employeeId ? 'selected' : '' ?>><?= htmlspecialchars($emp['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <?php endif; ?>

                    <select name="month" class="bg-slate-50 border border-slate-300 text-xs font-bold text-slate-800 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none transition">
                        <?php for ($m = 1; $m <= 12; $m++): ?>
                            <option value="<?= $m ?>" <?= $m === $selectedMonth ? 'selected' : '' ?>><?= date("F", mktime(0, 0, 0, $m, 1)) ?></option>
                        <?php endfor; ?>
                    </select>

                    <select name="year" class="bg-slate-50 border border-slate-300 text-xs font-bold text-slate-800 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none transition">
                        <?php $currY = intval(date('Y')); for ($y = $currY - 2; $y <= $currY + 1; $y++): ?>
                            <option value="<?= $y ?>" <?= $y === $selectedYear ? 'selected' : '' ?>><?= $y ?></option>
                        <?php endfor; ?>
                    </select>

                    <button type="submit" class="bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-black px-4 py-2 rounded-lg transition shadow-xs active:scale-95">Filter</button>
                </form>
            </div>

            <!-- Summary Statistics KPIs -->
            <?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">
                        <?= $canViewOthers && $employeeId !== $myEmployeeId ? htmlspecialchars($targetEmpName) : 'You' ?> <?= $canViewOthers && $employeeId !== $myEmployeeId ? 'is' : 'are' ?> on approved <?= htmlspecialchars($activeLeave) ?> as of today.
                    </p>
                </div>
            </div>
            <?php endif; ?>
            <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-4">
                <div class="bg-white border border-slate-200/80 rounded-2xl p-4 shadow-sm hover:border-indigo-300 transition-all flex items-start justify-between">
                    <div class="space-y-1">
                        <p class="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">Worked Cycles</p>
                        <h4 id="kpi-worked" class="text-2xl font-black tracking-tight text-slate-900"><?= $worked ?>d</h4>
                        <p class="text-[10px] text-slate-500 font-semibold">Processed days on-site</p>
                    </div>
                    <div class="w-8 h-8 rounded-xl bg-emerald-50 border border-emerald-200/80 flex items-center justify-center text-xs shrink-0">✅</div>
                </div>

                <div class="bg-white border border-slate-200/80 rounded-2xl p-4 shadow-sm hover:border-indigo-300 transition-all flex items-start justify-between">
                    <div class="space-y-1">
                        <p class="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">Absent Intervals</p>
                        <h4 id="kpi-absent" class="text-2xl font-black tracking-tight text-slate-900"><?= $absent ?>d</h4>
                        <p class="text-[10px] text-slate-500 font-semibold">Unresolved/missed schedules</p>
                    </div>
                    <div class="w-8 h-8 rounded-xl bg-rose-50 border border-rose-200/80 flex items-center justify-center text-xs shrink-0">❌</div>
                </div>

                <div class="bg-white border border-slate-200/80 rounded-2xl p-4 shadow-sm hover:border-indigo-300 transition-all flex items-start justify-between">
                    <div class="space-y-1">
                        <p class="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">Late Arrivals</p>
                        <h4 id="kpi-late" class="text-2xl font-black tracking-tight text-slate-900"><?= $late ?>d</h4>
                        <p class="text-[10px] text-slate-500 font-semibold">Logs past grace period</p>
                    </div>
                    <div class="w-8 h-8 rounded-xl bg-amber-50 border border-amber-200/80 flex items-center justify-center text-xs shrink-0">🕒</div>
                </div>

                <div class="bg-white border border-slate-200/80 rounded-2xl p-4 shadow-sm hover:border-indigo-300 transition-all flex items-start justify-between">
                    <div class="space-y-1">
                        <p class="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">Scheduled Days</p>
                        <h4 id="kpi-scheduled" class="text-2xl font-black tracking-tight text-slate-900"><?= $scheduled ?>d</h4>
                        <p class="text-[10px] text-slate-500 font-semibold">Upcoming assigned shifts</p>
                    </div>
                    <div class="w-8 h-8 rounded-xl bg-indigo-50 border border-indigo-200/80 flex items-center justify-center text-xs shrink-0">📅</div>
                </div>

                <div class="bg-white border border-slate-200/80 rounded-2xl p-4 shadow-sm hover:border-indigo-300 transition-all flex items-start justify-between">
                    <div class="space-y-1">
                        <p class="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">Off / Holidays</p>
                        <h4 id="kpi-off-ph" class="text-2xl font-black tracking-tight text-slate-900"><?= ($offDays + $publicHolidays) ?>d</h4>
                        <p class="text-[10px] text-slate-500 font-semibold">Official rest & holidays</p>
                    </div>
                    <div class="w-8 h-8 rounded-xl bg-slate-50 border border-slate-200/80 flex items-center justify-center text-xs shrink-0">⚓</div>
                </div>

                <div class="bg-white border border-slate-200/80 rounded-2xl p-4 shadow-sm hover:border-indigo-300 transition-all flex items-start justify-between">
                    <div class="space-y-1">
                        <p class="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">On Leave</p>
                        <h4 id="kpi-leave" class="text-2xl font-black tracking-tight text-slate-900"><?= $onLeave ?>d</h4>
                        <p class="text-[10px] text-slate-500 font-semibold">Approved leave days</p>
                    </div>
                    <div class="w-8 h-8 rounded-xl bg-violet-50 border border-violet-200/80 flex items-center justify-center text-xs shrink-0">🌴</div>
                </div>
            </div>

            <!-- Attendance Data Table Container -->
            <div class="bg-white border border-slate-200/80 rounded-2xl shadow-sm overflow-hidden">
                <div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between">
                    <div>
                        <h3 class="text-xs font-black text-slate-900 uppercase tracking-tight">Attendance Log Tracks</h3>
                        <p class="text-[10px] text-slate-500 font-semibold mt-0.5">Chronological roster logs for period selected.</p>
                    </div>
                    <span class="bg-indigo-50 text-indigo-700 border border-indigo-200/80 px-2.5 py-1 rounded-md font-extrabold text-[10px] font-mono shadow-xs">Live Sync</span>
                </div>

                <div id="attendance-table-wrapper">
                    <?php if (empty($rows)): ?>
                    <div class="text-center py-16">
                        <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 Attendance Tracks Found</h4>
                            <p class="text-[10px] text-slate-500 max-w-xs">No roster schedules registered for this monthly period.</p>
                            <button onclick="openRegularizationModal('<?= date('Y-m-d') ?>', '', '')" class="mt-4 bg-slate-900 hover:bg-slate-800 transition text-white rounded-lg font-bold py-2 px-4 text-xs shadow-sm active:scale-95">
                                File Manual Logging Request
                            </button>
                        </div>
                    </div>
                    <?php else: ?>

                    <!-- Mobile Responsive View -->
                    <div class="block md:hidden divide-y divide-slate-100 max-h-[600px] overflow-y-auto font-bold">
                        <?php foreach($rows as $row): 
                            $badge = match($row['status']) {
                                'Present' => 'bg-emerald-50 text-emerald-800 border-emerald-300',
                                'Late Arrival' => 'bg-amber-50 text-amber-900 border-amber-300',
                                'Absent' => 'bg-rose-50 text-rose-900 border-rose-300',
                                'Scheduled' => 'bg-indigo-50 text-indigo-900 border-indigo-300',
                                'Public Holiday' => 'bg-sky-50 text-sky-900 border-sky-300',
                                default => 'bg-slate-100 text-slate-700 border-slate-300'
                            };
                            if (!empty($row['is_leave'])) { $badge = 'bg-violet-50 text-violet-900 border-violet-300'; }
                            $cIn = $row['check_in'] ? date('H:i', strtotime($row['check_in'])) : '';
                            $cOut = $row['check_out'] ? date('H:i', strtotime($row['check_out'])) : '';
                            $isFixableStatus = in_array($row['status'], ['Absent', 'Off']) && empty($row['is_leave']);
                        ?>
                        <div class="p-4 flex items-center justify-between gap-3 hover:bg-slate-50/50 transition text-slate-800">
                            <div class="flex items-center gap-3">
                                <div class="w-10 h-10 rounded-xl bg-slate-100 border border-slate-200 flex flex-col items-center justify-center text-center shrink-0">
                                    <span class="text-xs font-black text-slate-900 leading-none"><?= date('d', strtotime($row['schedule_date'])) ?></span>
                                    <span class="text-[8px] font-black text-slate-500 uppercase tracking-tight mt-0.5"><?= date('M', strtotime($row['schedule_date'])) ?></span>
                                </div>
                                <div class="space-y-1">
                                    <div class="flex items-center gap-1.5 flex-wrap">
                                        <span class="text-[9px] font-black px-2 py-0.5 border rounded-md uppercase tracking-wider <?= $badge ?>">
                                            <?= $row['status'] === 'Late Arrival' ? 'LATE' : (!empty($row['is_leave']) ? '🌴 ' . $row['status'] : $row['status']) ?>
                                        </span>
                                        <span class="text-[9px] text-indigo-700 font-black px-1.5 py-0.5 rounded border border-indigo-100 bg-indigo-50/50">
                                            <?= htmlspecialchars($row['shift_name'] ?? '-') ?>
                                        </span>
                                    </div>
                                    <p class="text-[10px] font-mono text-slate-600 flex items-center gap-1">
                                        <span class="font-bold text-slate-900">IN:</span><?= $row['check_in'] ? date('h:i A', strtotime($row['check_in'])) : '--:--' ?> 
                                        <span class="font-bold text-slate-900 ml-1">OUT:</span><?= $row['check_out'] ? date('h:i A', strtotime($row['check_out'])) : '--:--' ?>
                                    </p>
                                </div>
                            </div>

                            <div class="shrink-0">
                                <?php if ($canEditLogs): ?>
                                    <?php if ($isFixableStatus): ?>
                                        <button type="button" onclick="openRegularizationModal('<?= $row['schedule_date'] ?>', '<?= $cIn ?>', '<?= $cOut ?>')" class="bg-indigo-600 hover:bg-indigo-700 text-white font-black px-2.5 py-1 rounded-md text-[10px] uppercase tracking-wider transition active:scale-95 shadow-xs">
                                            Fix Log
                                        </button>
                                    <?php else: ?>
                                        <span class="text-slate-300 font-black text-xs mr-2">—</span>
                                    <?php endif; ?>
                                <?php elseif (isset($regLookup[$row['schedule_date']])): 
                                    $regStat = $regLookup[$row['schedule_date']];
                                    $statCol = match($regStat) { 'Pending' => 'bg-amber-50 text-amber-900 border-amber-300', 'Approved' => 'bg-emerald-50 text-emerald-900 border-emerald-300', default => 'bg-rose-50 text-rose-900 border-rose-300' };
                                ?>
                                    <span class="text-[9px] font-black px-2 py-1 rounded-md border <?= $statCol ?> font-mono">RG: <?= strtoupper(substr($regStat, 0, 4)) ?></span>
                                <?php elseif ($isFixableStatus && $row['schedule_date'] <= $todayDate): ?>
                                    <button type="button" onclick="openRegularizationModal('<?= $row['schedule_date'] ?>', '<?= $cIn ?>', '<?= $cOut ?>')" class="bg-indigo-600 hover:bg-indigo-700 text-white font-black px-2.5 py-1 rounded-md text-[10px] uppercase tracking-wider transition active:scale-95 shadow-xs">
                                        Fix Log
                                    </button>
                                <?php else: ?>
                                    <span class="text-slate-300 font-black text-xs mr-2">—</span>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Desktop Table View -->
                    <div class="hidden md:block overflow-x-auto w-full">
                        <table class="w-full border-collapse">
                            <thead>
                                <tr class="bg-slate-50/80 text-slate-400 uppercase text-[10px] font-black tracking-wider border-b border-slate-100">
                                    <th class="p-3.5 text-left pl-6">Date</th>
                                    <th class="p-3.5 text-center">Shift</th>
                                    <th class="p-3.5 text-center">Check In</th>
                                    <th class="p-3.5 text-center">Check Out</th>
                                    <th class="p-3.5 text-center">Status</th>
                                    <th class="p-3.5 pr-6 text-center">Action</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100 text-xs font-bold">
                                <?php foreach($rows as $row): 
                                    $badgeColor = match($row['status']) {
                                        'Present' => 'bg-emerald-50 text-emerald-800 border-emerald-300',
                                        'Late Arrival' => 'bg-amber-50 text-amber-900 border-amber-300',
                                        'Absent' => 'bg-rose-50 text-rose-900 border-rose-300',
                                        'Scheduled' => 'bg-indigo-50 text-indigo-900 border-indigo-300',
                                        'Public Holiday' => 'bg-sky-50 text-sky-900 border-sky-300',
                                        default => 'bg-slate-100 text-slate-700 border-slate-300'
                                    };
                                    if (!empty($row['is_leave'])) { $badgeColor = 'bg-violet-50 text-violet-900 border-violet-300'; }
                                    $cIn = $row['check_in'] ? date('H:i', strtotime($row['check_in'])) : '';
                                    $cOut = $row['check_out'] ? date('H:i', strtotime($row['check_out'])) : '';
                                    $isFixableStatus = in_array($row['status'], ['Absent', 'Off']) && empty($row['is_leave']);
                                ?>
                                    <tr class="hover:bg-slate-50/80 transition text-slate-800">
                                        <td class="p-3.5 pl-6 font-extrabold text-slate-900 whitespace-nowrap"><?= date('d M Y (D)', strtotime($row['schedule_date'])) ?></td>
                                        <td class="p-3.5 text-center whitespace-nowrap">
                                            <span class="bg-slate-100 text-slate-700 px-2.5 py-1 rounded-md border border-slate-200 font-black text-[10px] uppercase tracking-wider"><?= htmlspecialchars($row['shift_name'] ?? '—') ?></span>
                                        </td>
                                        <td class="p-3.5 text-center font-mono text-xs text-slate-700 whitespace-nowrap"><?= $row['check_in'] ? date('h:i A', strtotime($row['check_in'])) : '<span class="text-slate-300 font-normal">—</span>' ?></td>
                                        <td class="p-3.5 text-center font-mono text-xs text-slate-700 whitespace-nowrap"><?= $row['check_out'] ? date('h:i A', strtotime($row['check_out'])) : '<span class="text-slate-300 font-normal">—</span>' ?></td>
                                        <td class="p-3.5 text-center whitespace-nowrap">
                                            <span class="px-2.5 py-0.5 rounded-full text-[10px] font-black tracking-wider border <?= $badgeColor ?>"><?= (!empty($row['is_leave']) ? '🌴 ' : '') . strtoupper($row['status']) ?></span>
                                        </td>
                                        <td class="p-3.5 pr-6 text-center whitespace-nowrap">
                                            <?php if ($canEditLogs): ?>
                                                <?php if ($isFixableStatus): ?>
                                                    <button type="button" onclick="openRegularizationModal('<?= $row['schedule_date'] ?>', '<?= $cIn ?>', '<?= $cOut ?>')" class="bg-indigo-50 hover:bg-indigo-100 text-indigo-700 px-3 py-1 rounded-md text-[10px] font-black uppercase tracking-wider transition border border-indigo-200 shadow-xs">Fix Log</button>
                                                <?php else: ?>
                                                    <span class="text-slate-300 text-xs">—</span>
                                                <?php endif; ?>
                                            <?php elseif (isset($regLookup[$row['schedule_date']])): 
                                                $regStat = $regLookup[$row['schedule_date']];
                                                $statColor = match($regStat) { 'Pending' => 'text-amber-900 bg-amber-50 border-amber-300', 'Approved' => 'text-emerald-900 bg-emerald-50 border-emerald-300', default => 'text-rose-900 bg-rose-50 border-rose-300' };
                                            ?>
                                                <span class="text-[10px] font-black px-2 py-1 rounded-md border <?= $statColor ?> font-mono">Reg. <?= $regStat ?></span>
                                            <?php elseif ($isFixableStatus && $row['schedule_date'] <= $todayDate): ?>
                                                <button type="button" onclick="openRegularizationModal('<?= $row['schedule_date'] ?>', '<?= $cIn ?>', '<?= $cOut ?>')" class="bg-indigo-50 hover:bg-indigo-100 text-indigo-700 px-3 py-1 rounded-md text-[10px] uppercase tracking-wider transition border border-indigo-200 shadow-xs">Fix Log</button>
                                            <?php else: ?>
                                                <span class="text-slate-300 text-xs">—</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>

    <!-- Regularization Modal -->
    <div id="regModal" class="fixed inset-0 bg-slate-900/40 hidden items-center justify-center p-4 z-50 backdrop-blur-sm transition-all duration-200">
        <div class="bg-white rounded-2xl w-full max-w-md p-6 shadow-xl border border-slate-200 transform transition-transform scale-95 opacity-0 duration-200" id="modalContainer">
            <div class="flex justify-between items-center mb-4 pb-2 border-b border-slate-100">
                <h3 class="text-xs font-black text-slate-900 uppercase tracking-tight"><?= $canEditLogs ? 'Override Attendance Record' : 'Modify Attendance Record' ?></h3>
                <button onclick="closeRegularizationModal()" class="text-slate-400 hover:text-slate-600 transition p-1 text-xs font-black rounded-lg hover:bg-slate-100">✕</button>
            </div>
            <form id="regularization-form" method="POST" onsubmit="handleModalSubmit(event)">
                <input type="hidden" name="action" value="request_regularization">
                <input type="hidden" id="modal_date" name="req_date">
                <input type="hidden" id="target_employee_id" name="target_employee_id" value="<?= $employeeId ?>">

                <div class="mb-4">
                    <label class="block text-[10px] font-black text-slate-500 uppercase tracking-wider mb-1">Target Date</label>
                    <input type="text" id="modal_date_display" class="w-full border border-slate-300 bg-slate-50 rounded-lg px-3 py-2 text-xs font-bold text-slate-800 font-mono cursor-not-allowed outline-none" readonly>
                </div>

                <div class="grid grid-cols-2 gap-3 mb-4">
                    <div>
                        <label class="block text-[10px] font-black text-slate-500 uppercase tracking-wider mb-1">Correct Check-In</label>
                        <input type="time" id="modal_in" name="requested_check_in" class="w-full border border-slate-300 bg-slate-50 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none text-xs text-slate-800 font-mono font-bold">
                    </div>
                    <div>
                        <label class="block text-[10px] font-black text-slate-500 uppercase tracking-wider mb-1">Correct Check-Out</label>
                        <input type="time" id="modal_out" name="requested_check_out" class="w-full border border-slate-300 bg-slate-50 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none text-xs text-slate-800 font-mono font-bold">
                    </div>
                </div>

                <div class="mb-5">
                    <label class="block text-[10px] font-black text-slate-500 uppercase tracking-wider mb-1">Reason / Context Note</label>
                    <textarea id="modal_reason" name="reason" rows="3" placeholder="Provide details regarding why logs are missing or out of alignment..." class="w-full border border-slate-300 bg-slate-50 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none text-xs text-slate-800 placeholder-slate-400 font-bold resize-none" required></textarea>
                </div>

                <div class="flex items-center justify-end gap-3 pt-3 border-t border-slate-100">
                    <button type="button" onclick="closeRegularizationModal()" class="w-1/2 bg-slate-100 hover:bg-slate-200 border border-slate-200 text-slate-700 py-2 rounded-lg font-bold text-xs transition">Cancel</button>
                    <button type="submit" class="w-1/2 bg-slate-900 hover:bg-slate-800 active:scale-[0.98] transition text-white rounded-lg font-bold py-2 text-xs shadow-sm">
                        <?= $canEditLogs ? 'Save Log Override' : 'Submit Request' ?>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Include JavaScript assets -->
    <script src="../components/sidebar.js"></script>
    <script>
    function showSpinner() {
        const spinner = document.getElementById('loading-spinner');
        spinner.classList.remove('hidden');
        spinner.classList.add('flex');
    }

    function hideSpinner() {
        const spinner = document.getElementById('loading-spinner');
        spinner.classList.remove('flex');
        spinner.classList.add('hidden');
    }

    function openRegularizationModal(date, currentIn, currentOut) {
        document.getElementById('modal_date').value = date;
        document.getElementById('modal_date_display').value = date;
        document.getElementById('modal_in').value = currentIn || "";
        document.getElementById('modal_out').value = currentOut || "";
        document.getElementById('modal_reason').value = "";

        const modal = document.getElementById('regModal');
        const container = document.getElementById('modalContainer');
        
        modal.classList.remove('hidden');
        modal.classList.add('flex');
        
        setTimeout(() => {
            container.classList.remove('scale-95', 'opacity-0');
            container.classList.add('scale-100', 'opacity-100');
        }, 10);
    }

    function closeRegularizationModal() {
        const modal = document.getElementById('regModal');
        const container = document.getElementById('modalContainer');

        container.classList.remove('scale-100', 'opacity-100');
        container.classList.add('scale-95', 'opacity-0');
        
        setTimeout(() => {
            modal.classList.remove('flex');
            modal.classList.add('hidden');
        }, 150);
    }

    function updateDOM(data) {
        if (data.status === 'success') {
            document.getElementById('kpi-worked').textContent = data.kpis.worked;
            document.getElementById('kpi-absent').textContent = data.kpis.absent;
            document.getElementById('kpi-late').textContent = data.kpis.late;
            document.getElementById('kpi-scheduled').textContent = data.kpis.scheduled;
            document.getElementById('kpi-off-ph').textContent = data.kpis.off_ph;

            document.getElementById('header-title-block').innerHTML = data.headerHtml;
            document.getElementById('alert-container').innerHTML = data.alertHtml;
            document.getElementById('attendance-table-wrapper').innerHTML = data.tableHtml;
            
            if (data.employeeId) {
                document.getElementById('target_employee_id').value = data.employeeId;
            }
        }
    }

    function handleFilterSubmit(e) {
        e.preventDefault();
        showSpinner();

        const form = document.getElementById('filter-form');
        const formData = new FormData(form);
        const params = new URLSearchParams(formData);

        fetch(window.location.pathname + '?' + params.toString(), {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(res => res.json())
        .then(data => {
            hideSpinner();
            updateDOM(data);
            window.history.pushState({}, '', window.location.pathname + '?' + params.toString());
        })
        .catch(err => {
            hideSpinner();
            console.error('Fetch error:', err);
        });
    }

    function handleModalSubmit(e) {
        e.preventDefault();
        showSpinner();

        const form = document.getElementById('regularization-form');
        const formData = new FormData(form);
        const filterForm = document.getElementById('filter-form');
        const filterData = new FormData(filterForm);

        for (let [key, val] of filterData.entries()) {
            if (!formData.has(key)) {
                formData.append(key, val);
            }
        }

        fetch(window.location.pathname, {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(res => res.json())
        .then(data => {
            hideSpinner();
            closeRegularizationModal();
            updateDOM(data);
        })
        .catch(err => {
            hideSpinner();
            console.error('Fetch error:', err);
        });
    }
    </script>
</body>
</html>