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

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

// Access Control - Require Login & Admin/HR/Manager Role
if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit;
}

$allowedRoles = ['admin', 'hr', 'human resources', 'superadmin', 'super admin', 'manager'];
$userRole     = strtolower(trim($_SESSION['role'] ?? ''));
$username     = $_SESSION['username'] ?? 'User';
$role         = $_SESSION['role']     ?? 'Staff';

$isAdminOrHr = in_array($userRole, $allowedRoles);

if (!$isAdminOrHr) {
    die("Access Denied: You do not have permission to manage employee attendance logs. (Your current role: " . htmlspecialchars($_SESSION['role'] ?? 'None') . ")");
}

/*
|--------------------------------------------------------------------------
| FETCH ALL EMPLOYEES FOR SELECTION
|--------------------------------------------------------------------------
*/
$allEmployees = [];
$empRes = $conn->query("SELECT id, name FROM employees ORDER BY name ASC");
if ($empRes) {
    while ($empRow = $empRes->fetch_assoc()) {
        $allEmployees[] = $empRow;
    }
}

/*
|--------------------------------------------------------------------------
| DETERMINE TARGET EMPLOYEE & DATE FILTERS
|--------------------------------------------------------------------------
*/
$selectedEmployeeId = isset($_GET['employee_id']) ? intval($_GET['employee_id']) : (!empty($allEmployees) ? intval($allEmployees[0]['id']) : 0);
$selectedMonth      = isset($_GET['month']) ? intval($_GET['month']) : intval(date('m'));
$selectedYear       = isset($_GET['year'])  ? intval($_GET['year'])  : intval(date('Y'));

// Fetch targeted employee details
$targetEmpName = 'Select Employee';
if ($selectedEmployeeId > 0) {
    $stmt = $conn->prepare("SELECT name FROM employees WHERE id = ? LIMIT 1");
    $stmt->bind_param("i", $selectedEmployeeId);
    $stmt->execute();
    $targetEmpInfo = $stmt->get_result()->fetch_assoc();
    $targetEmpName = $targetEmpInfo['name'] ?? 'Employee';
    $stmt->close();
}

/*
|--------------------------------------------------------------------------
| POST HANDLER: DIRECT ATTENDANCE CORRECTION BY ADMIN/HR
|--------------------------------------------------------------------------
*/
$message = '';
$messageClass = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'fix_attendance_log') {
    $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;
    $postTargetEmpId = intval($_POST['target_employee_id']);

    if ($postTargetEmpId <= 0) {
        $message = "Invalid employee selected.";
        $messageClass = "bg-rose-50 border-rose-300 text-rose-900";
    } else {
        // Direct update or insert into attendance
        $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()) {
            // Auto-resolve any pending regularization requests for this date
            $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 log updated successfully for " . htmlspecialchars($targetEmpName) . ".";
            $messageClass = "bg-emerald-50 border-emerald-300 text-emerald-900";
        } else {
            $message = "Error updating attendance log.";
            $messageClass = "bg-rose-50 border-rose-300 text-rose-900";
        }
        $stmt->close();
    }
}

/*
|--------------------------------------------------------------------------
| LOAD SCHEDULE + ATTENDANCE FOR SELECTED EMPLOYEE
|--------------------------------------------------------------------------
*/
$rows = [];
$worked = 0;
$absent = 0;
$late = 0;
$incomplete = 0;
$offDays = 0;
$sickLeave = 0;
$publicHolidays = 0;
$scheduled = 0;
$notResumed = 0;

$todayDate = date('Y-m-d');
$currentTime = date('H:i:s');

if ($selectedEmployeeId > 0) {
    $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", $selectedEmployeeId, $selectedMonth, $selectedYear);
    $stmt->execute();
    $result = $stmt->get_result();

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

        if ($shiftName === 'OFF') {
            $status = 'Off';
            $offDays++;
        } elseif ($shiftName === 'SL') {
            $status = 'Sick Leave';
            $sickLeave++;
        } elseif ($shiftName === 'PH') {
            $status = 'Public Holiday';
            $publicHolidays++;
        } elseif (!empty($row['check_in']) && !empty($row['check_out'])) {
            $status = 'Present';
            $worked++;

            if (!empty($row['shift_start'])) {
                if (strtotime($row['check_in']) > strtotime($row['shift_start']) + (15 * 60)) {
                    $status = 'Late Arrival';
                    $late++;
                }
            }
        } elseif (!empty($row['check_in']) || !empty($row['check_out'])) {
            $status = 'Incomplete';
            $incomplete++;
        } else {
            if ($row['schedule_date'] > $todayDate) {
                $status = 'Scheduled';
                $scheduled++;
            } elseif ($row['schedule_date'] === $todayDate) {
                if (!empty($row['shift_start']) && $currentTime < $row['shift_start']) {
                    $status = 'Not Resumed';
                    $notResumed++;
                } else {
                    $status = 'Absent';
                    $absent++;
                }
            } else {
                $status = 'Absent';
                $absent++;
            }
        }

        $row['status'] = $status;
        $rows[] = $row;
    }
    $stmt->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fix Attendance Logs - HR System</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">
        
        <!-- SIDEBAR INTEGRATION: No wrapping div (sidebar.php contains #sidebar) -->
        <?php include '../components/sidebar.php'; ?>

        <!-- MOBILE OVERLAY TOGGLE -->
        <div id="sidebar-overlay" class="fixed inset-0 bg-slate-900/40 hidden z-40 transition-opacity duration-300 md:hidden" 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">
            
            <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 type="button" onclick="toggleSidebar()" class="p-1.5 rounded-lg text-slate-600 hover:bg-slate-200/80 transition active:scale-95" aria-label="Toggle Navigation Sidebar">
                        <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">Fix Individual Attendance Logs</h1>
                        <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">Administrative Correction Tool</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); ?></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">

                <?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; ?>

                <!-- Selection & Filter Panel -->
                <div class="bg-white border border-slate-300/80 p-4 rounded-xl shadow-xs flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
                    <div>
                        <h2 class="text-xs font-black text-slate-950 uppercase tracking-tight">Target Selection</h2>
                        <p class="text-[10px] text-slate-500 font-semibold mt-0.5">Viewing logs for <span class="text-indigo-600 font-bold"><?= htmlspecialchars($targetEmpName) ?></span> in <?= date("F Y", mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)) ?></p>
                    </div>

                    <form method="GET" class="flex flex-wrap items-center gap-2 w-full sm:w-auto">
                        
                        <!-- EMPLOYEE SELECTOR -->
                        <select name="employee_id" class="bg-stone-50 border border-slate-300 text-xs font-bold text-slate-800 rounded-lg px-3 py-1.5 focus:outline-none focus:border-indigo-500 min-w-[180px]">
                            <?php foreach ($allEmployees as $emp): ?>
                                <option value="<?= $emp['id'] ?>" <?= $emp['id'] === $selectedEmployeeId ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($emp['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>

                        <!-- MONTH SELECTOR -->
                        <select name="month" class="bg-stone-50 border border-slate-300 text-xs font-bold text-slate-800 rounded-lg px-3 py-1.5 focus:outline-none focus:border-indigo-500">
                            <?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>

                        <!-- YEAR SELECTOR -->
                        <select name="year" class="bg-stone-50 border border-slate-300 text-xs font-bold text-slate-800 rounded-lg px-3 py-1.5 focus:outline-none focus:border-indigo-500">
                            <?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-1.5 rounded-lg transition shadow-xs">
                            Load Employee
                        </button>
                    </form>
                </div>

                <!-- Summary Cards -->
                <div class="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-8 gap-3">
                    <div class="bg-white border border-slate-300/80 rounded-xl p-3 shadow-sm hover:border-indigo-400 transition-all">
                        <div class="flex items-start justify-between">
                            <div class="space-y-0.5">
                                <p class="text-[9px] font-extrabold text-slate-500 uppercase tracking-wider">Worked</p>
                                <h4 class="text-xl font-black tracking-tight text-slate-950"><?= $worked ?>d</h4>
                            </div>
                            <div class="w-7 h-7 rounded-lg bg-emerald-50 border border-emerald-200 flex items-center justify-center text-xs shrink-0">✅</div>
                        </div>
                    </div>

                    <div class="bg-white border border-slate-300/80 rounded-xl p-3 shadow-sm hover:border-indigo-400 transition-all">
                        <div class="flex items-start justify-between">
                            <div class="space-y-0.5">
                                <p class="text-[9px] font-extrabold text-slate-500 uppercase tracking-wider">Absent</p>
                                <h4 class="text-xl font-black tracking-tight text-slate-950"><?= $absent ?>d</h4>
                            </div>
                            <div class="w-7 h-7 rounded-lg bg-rose-50 border border-rose-200 flex items-center justify-center text-xs shrink-0">❌</div>
                        </div>
                    </div>

                    <div class="bg-white border border-slate-300/80 rounded-xl p-3 shadow-sm hover:border-indigo-400 transition-all">
                        <div class="flex items-start justify-between">
                            <div class="space-y-0.5">
                                <p class="text-[9px] font-extrabold text-slate-500 uppercase tracking-wider">Late</p>
                                <h4 class="text-xl font-black tracking-tight text-slate-950"><?= $late ?>d</h4>
                            </div>
                            <div class="w-7 h-7 rounded-lg bg-amber-50 border border-amber-200 flex items-center justify-center text-xs shrink-0">🕒</div>
                        </div>
                    </div>

                    <div class="bg-white border border-slate-300/80 rounded-xl p-3 shadow-sm hover:border-indigo-400 transition-all">
                        <div class="flex items-start justify-between">
                            <div class="space-y-0.5">
                                <p class="text-[9px] font-extrabold text-slate-500 uppercase tracking-wider">Incomplete</p>
                                <h4 class="text-xl font-black tracking-tight text-slate-950"><?= $incomplete ?>d</h4>
                            </div>
                            <div class="w-7 h-7 rounded-lg bg-orange-50 border border-orange-200 flex items-center justify-center text-xs shrink-0">⚠️</div>
                        </div>
                    </div>

                    <div class="bg-white border border-slate-300/80 rounded-xl p-3 shadow-sm hover:border-indigo-400 transition-all">
                        <div class="flex items-start justify-between">
                            <div class="space-y-0.5">
                                <p class="text-[9px] font-extrabold text-slate-500 uppercase tracking-wider">Not Resumed</p>
                                <h4 class="text-xl font-black tracking-tight text-slate-950"><?= $notResumed ?>d</h4>
                            </div>
                            <div class="w-7 h-7 rounded-lg bg-sky-50 border border-sky-200 flex items-center justify-center text-xs shrink-0">⏳</div>
                        </div>
                    </div>

                    <div class="bg-white border border-slate-300/80 rounded-xl p-3 shadow-sm hover:border-indigo-400 transition-all">
                        <div class="flex items-start justify-between">
                            <div class="space-y-0.5">
                                <p class="text-[9px] font-extrabold text-slate-500 uppercase tracking-wider">Scheduled</p>
                                <h4 class="text-xl font-black tracking-tight text-slate-950"><?= $scheduled ?>d</h4>
                            </div>
                            <div class="w-7 h-7 rounded-lg bg-indigo-50 border border-indigo-200 flex items-center justify-center text-xs shrink-0">📅</div>
                        </div>
                    </div>

                    <div class="bg-white border border-slate-300/80 rounded-xl p-3 shadow-sm hover:border-indigo-400 transition-all">
                        <div class="flex items-start justify-between">
                            <div class="space-y-0.5">
                                <p class="text-[9px] font-extrabold text-slate-500 uppercase tracking-wider">Sick Leave</p>
                                <h4 class="text-xl font-black tracking-tight text-slate-950"><?= $sickLeave ?>d</h4>
                            </div>
                            <div class="w-7 h-7 rounded-lg bg-teal-50 border border-teal-200 flex items-center justify-center text-xs shrink-0">🏥</div>
                        </div>
                    </div>

                    <div class="bg-white border border-slate-300/80 rounded-xl p-3 shadow-sm hover:border-indigo-400 transition-all">
                        <div class="flex items-start justify-between">
                            <div class="space-y-0.5">
                                <p class="text-[9px] font-extrabold text-slate-500 uppercase tracking-wider">Off / Holiday</p>
                                <h4 class="text-xl font-black tracking-tight text-slate-950"><?= ($offDays + $publicHolidays) ?>d</h4>
                            </div>
                            <div class="w-7 h-7 rounded-lg bg-stone-100 border border-slate-300 flex items-center justify-center text-xs shrink-0">⚓</div>
                        </div>
                    </div>
                </div>

                <!-- Table Container -->
                <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">Roster Logs: <?= htmlspecialchars($targetEmpName) ?></h3>
                            <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Click "Fix Log" on any date to manually enter or override attendance entries.</p>
                        </div>
                    </div>

                    <?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 Schedules Found</h4>
                            <p class="text-[10px] text-slate-600 max-w-xs">No active shift schedules found for <?= htmlspecialchars($targetEmpName) ?> in this period.</p>
                        </div>
                    </div>
                    <?php else: ?>

                    <!-- Mobile Responsive Layout Card Blocks -->
                    <div class="block md:hidden divide-y divide-slate-200/80 max-h-[600px] overflow-y-auto font-bold">
                        <?php foreach($rows as $row): 
                            $mBadge = match($row['status']) {
                                'Present'        => 'bg-emerald-50 text-emerald-800 border-emerald-300',
                                'Late Arrival'   => 'bg-amber-50 text-amber-900 border-amber-300',
                                'Incomplete'     => 'bg-orange-50 text-orange-900 border-orange-300',
                                'Absent'         => 'bg-rose-50 text-rose-900 border-rose-300',
                                'Not Resumed'    => 'bg-sky-50 text-sky-900 border-sky-300',
                                'Scheduled'      => 'bg-indigo-50 text-indigo-900 border-indigo-300',
                                'Sick Leave'     => 'bg-teal-50 text-teal-900 border-teal-300',
                                'Public Holiday' => 'bg-sky-50 text-sky-900 border-sky-300',
                                default          => 'bg-stone-100 text-slate-700 border-slate-300'
                            };
                            $formattedDay   = date('d', strtotime($row['schedule_date']));
                            $formattedMonth = date('M', strtotime($row['schedule_date']));
                            $mCleanIn       = $row['check_in'] ? date('H:i', strtotime($row['check_in'])) : '';
                            $mCleanOut      = $row['check_out'] ? date('H:i', strtotime($row['check_out'])) : '';
                        ?>
                        <div class="p-4 flex items-center justify-between gap-3 hover:bg-stone-50/50 transition text-slate-800">
                            <div class="flex items-center gap-3">
                                <div class="w-10 h-10 rounded-lg bg-stone-100 border border-slate-300 flex flex-col items-center justify-center text-center shrink-0">
                                    <span class="text-xs font-black text-slate-950 leading-none"><?= $formattedDay ?></span>
                                    <span class="text-[8px] font-black text-slate-500 uppercase tracking-tight mt-0.5"><?= $formattedMonth ?></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 <?= $mBadge ?>">
                                            <?= $row['status'] === 'Late Arrival' ? 'LATE' : $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">
                                <button type="button" onclick="openFixModal('<?= $row['schedule_date'] ?>', '<?= $mCleanIn ?>', '<?= $mCleanOut ?>')" 
                                        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
                                </button>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Main Desktop Structural Table Framework -->
                    <div class="hidden md:block overflow-x-auto w-full">
                        <table class="w-full 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 pl-6">Date Frame</th>
                                    <th class="p-3 text-center">Assigned Shift</th>
                                    <th class="p-3 text-center">System Check In</th>
                                    <th class="p-3 text-center">System Check Out</th>
                                    <th class="p-3 text-center">Metrics Status</th>
                                    <th class="p-3 pr-6 text-center">Operations</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-200/80 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',
                                        'Incomplete'     => 'bg-orange-50 text-orange-900 border-orange-300',
                                        'Absent'         => 'bg-rose-50 text-rose-900 border-rose-300',
                                        'Not Resumed'    => 'bg-sky-50 text-sky-900 border-sky-300',
                                        'Scheduled'      => 'bg-indigo-50 text-indigo-900 border-indigo-300',
                                        'Sick Leave'     => 'bg-teal-50 text-teal-900 border-teal-300',
                                        'Public Holiday' => 'bg-sky-50 text-sky-900 border-sky-300',
                                        default          => 'bg-stone-100 text-slate-700 border-slate-300'
                                    };
                                    $cleanIn  = $row['check_in'] ? date('H:i', strtotime($row['check_in'])) : '';
                                    $cleanOut = $row['check_out'] ? date('H:i', strtotime($row['check_out'])) : '';
                                ?>
                                    <tr class="hover:bg-stone-50/50 transition text-slate-800">
                                        <td class="p-3 pl-6 font-extrabold text-slate-900 whitespace-nowrap">
                                            <?= date('d M Y', strtotime($row['schedule_date'])) ?>
                                        </td>
                                        <td class="p-3 text-center whitespace-nowrap">
                                            <span class="bg-stone-100 text-slate-700 px-2.5 py-1 rounded-md border border-slate-300 font-black text-[10px] uppercase tracking-wider"><?= htmlspecialchars($row['shift_name'] ?? '—') ?></span>
                                        </td>
                                        <td class="p-3 text-center font-mono text-[10px] text-slate-700 whitespace-nowrap">
                                            <?= $row['check_in'] ? date('h:i A', strtotime($row['check_in'])) : '<span class="text-rose-400 font-normal">Missing</span>' ?>
                                        </td>
                                        <td class="p-3 text-center font-mono text-[10px] text-slate-700 whitespace-nowrap">
                                            <?= $row['check_out'] ? date('h:i A', strtotime($row['check_out'])) : '<span class="text-rose-400 font-normal">Missing</span>' ?>
                                        </td>
                                        <td class="p-3 text-center whitespace-nowrap">
                                            <span class="px-2 py-0.5 rounded text-[10px] font-black tracking-wider border <?= $badgeColor ?>">
                                                <?= strtoupper($row['status']) ?>
                                            </span>
                                        </td>
                                        <td class="p-3 pr-6 text-center whitespace-nowrap">
                                            <button type="button" 
                                                    onclick="openFixModal('<?= $row['schedule_date'] ?>', '<?= $cleanIn ?>', '<?= $cleanOut ?>')" 
                                                    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>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>
                </div>

            </main>
        </div>
    </div>

    <!-- ADMIN FIX ATTENDANCE MODAL -->
    <div id="fixModal" class="fixed inset-0 bg-slate-900/50 backdrop-blur-xs hidden z-50 flex items-center justify-center p-4">
        <div class="bg-white rounded-2xl border border-slate-300 shadow-2xl max-w-md w-full overflow-hidden transform transition-all">
            <div class="p-5 border-b border-slate-200 bg-stone-50 flex items-center justify-between">
                <div>
                    <h3 class="text-sm font-black text-slate-950 uppercase tracking-tight">Direct Attendance Override</h3>
                    <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider mt-0.5">Updating: <?= htmlspecialchars($targetEmpName) ?></p>
                </div>
                <button type="button" onclick="closeFixModal()" class="text-slate-400 hover:text-slate-600 text-lg font-bold leading-none">&times;</button>
            </div>
            
            <form method="POST" class="p-5 space-y-4">
                <input type="hidden" name="action" value="fix_attendance_log">
                <input type="hidden" name="target_employee_id" value="<?= $selectedEmployeeId ?>">
                
                <div>
                    <label class="block text-[10px] font-extrabold text-slate-500 uppercase tracking-wider mb-1">Target Log Date</label>
                    <input type="date" id="modal_req_date" name="req_date" readonly class="w-full bg-stone-100 border border-slate-300 text-xs font-bold text-slate-800 rounded-lg p-2.5 focus:outline-none cursor-not-allowed">
                </div>

                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="block text-[10px] font-extrabold text-slate-500 uppercase tracking-wider mb-1">Check-In Time</label>
                        <input type="time" id="modal_req_in" name="requested_check_in" class="w-full bg-stone-50 border border-slate-300 text-xs font-bold text-slate-800 rounded-lg p-2.5 focus:outline-none focus:border-indigo-500">
                    </div>
                    <div>
                        <label class="block text-[10px] font-extrabold text-slate-500 uppercase tracking-wider mb-1">Check-Out Time</label>
                        <input type="time" id="modal_req_out" name="requested_check_out" class="w-full bg-stone-50 border border-slate-300 text-xs font-bold text-slate-800 rounded-lg p-2.5 focus:outline-none focus:border-indigo-500">
                    </div>
                </div>

                <div class="pt-2 flex items-center justify-end gap-2 border-t border-slate-100">
                    <button type="button" onclick="closeFixModal()" class="px-4 py-2 bg-stone-100 hover:bg-stone-200 text-slate-700 font-bold rounded-lg text-xs transition">
                        Cancel
                    </button>
                    <button type="submit" class="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white font-bold rounded-lg text-xs shadow-xs transition">
                        Save Correction
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- SIDEBAR ENGINE SCRIPT INCLUDE -->
    <script src="../components/sidebar.js"></script>

    <!-- MODAL HANDLERS -->
    <script>
        function openFixModal(date, checkIn, checkOut) {
            document.getElementById('modal_req_date').value = date;
            document.getElementById('modal_req_in').value = checkIn;
            document.getElementById('modal_req_out').value = checkOut;
            document.getElementById('fixModal').classList.remove('hidden');
        }

        function closeFixModal() {
            document.getElementById('fixModal').classList.add('hidden');
        }
    </script>
</body>
</html>