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

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

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

$month = intval($_GET['month'] ?? date('m'));
$year  = intval($_GET['year'] ?? date('Y'));

$monthStart = "$year-" . str_pad($month, 2, '0', STR_PAD_LEFT) . "-01";
$monthEnd   = date('Y-m-t', strtotime($monthStart));
$todayStr   = date('Y-m-d'); 

// Helper function to centralize monthly processing logic for exact matching
function calculateEmployeeAttendance($conn, $employeeId, $monthStart, $monthEnd, $todayStr) {
    $scheduleDays = [];
    $lateCount = 0;
    $incompleteCount = 0;
    $daysWorked = 0;
    $totalHours = 0;

    // 1. Fetch Schedule
    $sStmt = $conn->prepare("
        SELECT ds.schedule_date, s.name AS shift_name, s.checkin AS shift_checkin, s.checkout AS shift_checkout 
        FROM department_schedules ds 
        INNER JOIN shifts s ON s.id = ds.shift_id 
        WHERE ds.employee_id = ? AND ds.schedule_date BETWEEN ? AND ?
        ORDER BY ds.schedule_date
    ");
    $sStmt->bind_param("iss", $employeeId, $monthStart, $monthEnd);
    $sStmt->execute();
    $res = $sStmt->get_result();
    while ($row = $res->fetch_assoc()) {
        $sDate = $row['schedule_date'];
        
        // Default status: "Not Resumed" for today/future scheduled days without check-in, "Absent" for past days
        $defaultStatus = ($sDate >= $todayStr) ? 'Not Resumed' : 'Absent';

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

    // 2. Fetch Attendance
    $aStmt = $conn->prepare("
        SELECT date, check_in, check_out 
        FROM attendance 
        WHERE employee_id = ? AND date BETWEEN ? AND ?
    ");
    $aStmt->bind_param("iss", $employeeId, $monthStart, $monthEnd);
    $aStmt->execute();
    $res = $aStmt->get_result();
    while ($row = $res->fetch_assoc()) {
        $date = $row['date'];
        if (!isset($scheduleDays[$date])) continue;

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

        if (!empty($checkIn) && !empty($checkOut)) {
            $in  = strtotime($checkIn);
            $out = strtotime($checkOut);
            if ($out < $in) { $out += 86400; }
            $hours = round(($out - $in) / 3600, 2);
            $daysWorked++;
            $totalHours += $hours;
            
            $scheduleDays[$date]['status'] = 'Present';
            $scheduleDays[$date]['check_in'] = $checkIn;
            $scheduleDays[$date]['check_out'] = $checkOut;
            $scheduleDays[$date]['hours'] = $hours;

            if (!empty($scheduleDays[$date]['shift_checkin'])) {
                $actualInRelative = strtotime($date . ' ' . $checkIn);
                $expectedIn = strtotime($date . ' ' . $scheduleDays[$date]['shift_checkin']);
                if ($actualInRelative > ($expectedIn + 900)) {
                    $lateCount++;
                }
            }
        } else {
            if ($date < $todayStr) {
                if (!empty($checkIn) || !empty($checkOut)) {
                    $scheduleDays[$date]['status'] = 'Incomplete';
                    $incompleteCount++;
                } else {
                    $scheduleDays[$date]['status'] = 'Absent';
                }
            } elseif ($date === $todayStr) {
                $scheduleDays[$date]['status'] = !empty($checkIn) ? 'In Progress' : 'Not Resumed';
            }
        }
    }
    $aStmt->close();

    // 3. Fetch Leaves
    $lStmt = $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 >= ?)
    ");
    $lStmt->bind_param("iss", $employeeId, $monthEnd, $monthStart);
    $lStmt->execute();
    $res = $lStmt->get_result();

    $leaveDates = [];
    while ($leave = $res->fetch_assoc()) {
        $start = strtotime($leave['start_date']);
        $end   = strtotime($leave['end_date']);
        for ($d = $start; $d <= $end; $d += 86400) {
            $date = date('Y-m-d', $d);
            if (isset($scheduleDays[$date]) && !in_array($scheduleDays[$date]['status'], ['Present'])) {
                $leaveType = trim($leave['leave_type'] ?? 'Leave');
                $scheduleDays[$date]['status'] = $leaveType;
                $scheduleDays[$date]['is_leave'] = true;
                // The SQL query above already only returns leave requests
                // fully approved by both manager and HR, so every row here
                // is a genuine leave day -- no need to also filter by leave
                // TYPE name. The old whitelist here only recognized 5 of
                // the 7 actual leave types (missing Study Leave, Unpaid
                // Leave, and PH), so anyone on those types was silently
                // still counted as "expected to work" and had their
                // attendance percentage unfairly penalized.
                $leaveDates[$date] = true;
            }
        }
    }
    $lStmt->close();

    // 4. Summarize Calculations
    $scheduledDays = 0; 
    $absentDays = 0;
    foreach ($scheduleDays as $date => $day) {
        if ($day['shift'] === 'OFF') {
            $status = (!empty($day['check_in']) && !empty($day['check_out'])) ? 'Worked on Off Day' : 'Off';
        } elseif ($day['shift'] === 'PH') {
            $status = (!empty($day['check_in']) && !empty($day['check_out'])) ? 'Worked on Public Holiday' : 'Public Holiday';
        } else {
            $status = $day['status'];
        }

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

    $expectedDays = max(0, $scheduledDays - count($leaveDates));
    $attendancePercent = ($expectedDays > 0) ? min(100, ($daysWorked / $expectedDays) * 100) : 0;

    return [
        'scheduled_days'     => $scheduledDays,
        'days_worked'        => $daysWorked,
        'hours_worked'       => round($totalHours, 2),
        'leave_days'         => count($leaveDates),
        'absent_days'        => $absentDays,
        'attendance_percent' => round($attendancePercent, 2),
        'late_count'         => $lateCount,
        'incomplete_count'   => $incompleteCount
    ];
}

// ----------------------------------------------------
// PHASE 1: PROCESS POST SUBMISSIONS FIRST
// ----------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_summaries'])) {
    $syncCount = 0;
    $overrides = $_POST['surcharges_override'] ?? [];

    try {
        $columnCheck = $conn->query("SHOW COLUMNS FROM attendance_monthly_summaries LIKE 'surcharges'");
        if ($columnCheck && $columnCheck->num_rows === 0) {
            $conn->query("ALTER TABLE attendance_monthly_summaries ADD COLUMN surcharges DECIMAL(10,2) DEFAULT 0.00");
        }
    } catch (Exception $e) {
        // Silence schema exceptions
    }

    $employees = $conn->query("SELECT id FROM employees");
    $empIds = [];
    while ($e = $employees->fetch_assoc()) {
        $empIds[] = $e['id'];
    }

    $stmt = $conn->prepare("
        INSERT INTO attendance_monthly_summaries 
            (payroll_month, payroll_year, employee_id, scheduled_days, days_worked, hours_worked, leave_days, absent_days, attendance_percent, surcharges) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE 
            scheduled_days     = VALUES(scheduled_days),
            days_worked        = VALUES(days_worked),
            hours_worked       = VALUES(hours_worked),
            leave_days         = VALUES(leave_days),
            absent_days        = VALUES(absent_days),
            attendance_percent = VALUES(attendance_percent),
            surcharges         = VALUES(surcharges)
    ");

    foreach ($empIds as $employeeId) {
        // Use identical logic calculation function
        $calc = calculateEmployeeAttendance($conn, $employeeId, $monthStart, $monthEnd, $todayStr);

        $finalSurcharge = isset($overrides[$employeeId]) ? floatval($overrides[$employeeId]) : 0.00;

        $stmt->bind_param(
            "iiiiidiidd", 
            $month, $year, $employeeId, 
            $calc['scheduled_days'], $calc['days_worked'], 
            $calc['hours_worked'], $calc['leave_days'], 
            $calc['absent_days'], $calc['attendance_percent'], 
            $finalSurcharge
        );
        $stmt->execute();
        $syncCount++;
    }

    $stmt->close();

    header("Location: " . $_SERVER['PHP_SELF'] . "?month=$month&year=$year&save_success=" . $syncCount);
    exit;
}

// ----------------------------------------------------
// PHASE 2: RENDERING
// ----------------------------------------------------
$records = [];
$employees = $conn->query("
    SELECT e.id, e.name, d.name department
    FROM employees e
    LEFT JOIN departments d ON d.id = e.department_id
    ORDER BY e.name
");

$surchargeQuery = $conn->prepare("
    SELECT surcharges FROM attendance_monthly_summaries 
    WHERE employee_id = ? AND payroll_month = ? AND payroll_year = ? 
    LIMIT 1
");

while ($emp = $employees->fetch_assoc()) {
    $employeeId = $emp['id'];

    // Use identical logic calculation function
    $calc = calculateEmployeeAttendance($conn, $employeeId, $monthStart, $monthEnd, $todayStr);

    $savedSurcharge = 0;
    try {
        if ($surchargeQuery) {
            $surchargeQuery->bind_param("iii", $employeeId, $month, $year);
            $surchargeQuery->execute();
            $surchargeRes = $surchargeQuery->get_result()->fetch_assoc();
            if ($surchargeRes) {
                $savedSurcharge = floatval($surchargeRes['surcharges']);
            }
        }
    } catch (Exception $e) {
        $savedSurcharge = 0;
    }

    $records[] = array_merge([
        'employee_id' => $employeeId,
        'name'        => $emp['name'],
        'department'  => $emp['department'],
        'surcharges'  => $savedSurcharge
    ], $calc);
}

$surchargeQuery->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Attendance Records & Surcharges</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:wght@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-slate-50 min-h-screen text-slate-800 antialiased font-sans">

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

        <div id="main-content" class="flex-1 min-w-0 md:pl-60 transition-all duration-300 min-h-screen flex flex-col">
            <header class="sticky top-0 bg-white/80 backdrop-blur-md border-b border-slate-200/60 h-14 flex items-center justify-between px-4 sm:px-6 z-30 shadow-xs">
                <div class="flex items-center gap-3">
                    <button onclick="toggleSidebar()" class="p-1.5 rounded-lg text-slate-500 hover:bg-slate-100 transition active:scale-95 flex items-center justify-center">
                        <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-900">Summary Matrix</h1>
                        <p class="text-[10px] text-slate-400 font-medium">Monthly Payroll Verification Logs</p>
                    </div>
                </div>
            </header>

            <main class="flex-1 p-4 sm:p-6 max-w-7xl w-full mx-auto space-y-4">
                <?php if (isset($_GET['save_success'])): ?>
                <div class="bg-emerald-50 border border-emerald-200 text-emerald-800 p-3.5 rounded-xl text-xs font-semibold shadow-xs flex items-center gap-2.5">
                    <span>🎉</span>
                    <span>Successfully updated dynamic processing arrays and committed values for <?= intval($_GET['save_success']) ?> profiles directly.</span>
                </div>
                <?php endif; ?>

                <div class="bg-white border border-slate-200/80 rounded-xl p-4 shadow-xs flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
                    <form method="GET" class="grid grid-cols-1 sm:grid-cols-3 gap-3 flex-1">
                        <div>
                            <select name="month" class="w-full border border-slate-200 bg-slate-50 px-3 py-2 rounded-lg text-xs text-slate-700 font-bold">
                                <?php for($m=1; $m<=12; $m++): ?>
                                    <option value="<?= $m ?>" <?= $month == $m ? 'selected' : '' ?>>
                                        <?= date('F', mktime(0, 0, 0, $m, 1)) ?>
                                    </option>
                                <?php endfor; ?>
                            </select>
                        </div>
                        <div>
                            <input type="number" name="year" value="<?= $year ?>" placeholder="Year" class="w-full border border-slate-200 bg-slate-50 px-3 py-2 rounded-lg text-xs text-slate-700 font-mono">
                        </div>
                        <div>
                            <button type="submit" class="w-full bg-slate-900 hover:bg-slate-800 text-white rounded-lg font-bold py-2 text-xs border border-slate-950 transition active:scale-95">
                                Load Parameters
                            </button>
                        </div>
                    </form>

                    <div class="flex flex-col sm:flex-row items-center gap-3 w-full lg:w-auto">
                        <div class="w-full sm:w-56 relative">
                            <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-slate-400 text-xs">🔍</span>
                            <input type="text" id="dashboardSearch" onkeyup="filterDashboardTable()" placeholder="Filter name or dept..." class="w-full border border-slate-200 bg-slate-50 pl-8 pr-3 py-2 rounded-lg text-xs text-slate-700">
                        </div>
                        
                        <form method="POST" id="saveSummariesForm" class="w-full sm:w-auto" onsubmit="return confirm('Commit adjustments and surcharge exceptions directly into system matrix database?');">
                            <div id="hiddenOverridesContainer">
                                <?php foreach($records as $row): ?>
                                    <input type="hidden" name="surcharges_override[<?= $row['employee_id'] ?>]" id="surcharge_input_<?= $row['employee_id'] ?>" value="<?= $row['surcharges'] ?>">
                                <?php endforeach; ?>
                            </div>
                            <button type="submit" name="save_summaries" class="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold px-4 py-2 rounded-lg text-xs transition active:scale-95 border border-indigo-700 flex items-center justify-center gap-2 whitespace-nowrap">
                                💾 Commit Processing Ledger
                            </button>
                        </form>
                    </div>
                </div>

                <div class="bg-white border border-slate-200 rounded-xl shadow-xs overflow-hidden">
                    <div class="overflow-x-auto w-full">
                        <table class="w-full min-w-[850px] border-collapse" id="employeeTable">
                            <thead>
                                <tr class="bg-slate-50 text-slate-400 uppercase text-[9px] font-black tracking-wider border-b border-slate-150">
                                    <th class="p-3 text-left w-[240px]">Employee Profile</th>
                                    <th class="p-3 text-center">Scheduled</th>
                                    <th class="p-3 text-center">Worked</th>
                                    <th class="p-3 text-center">Absent</th>
                                    <th class="p-3 text-center">Leave</th>
                                    <th class="p-3 text-center">Hours Worked</th>
                                    <th class="p-3 text-center">Attendance %</th>
                                    <th class="p-3 text-center">Surcharges</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100 text-xs text-slate-700">
                                <?php foreach($records as $row): ?>
                                    <tr class="hover:bg-slate-50/50 transition table-row-item">
                                        <td class="p-3 whitespace-nowrap">
                                            <div class="flex items-center gap-3">
                                                <div class="w-8 h-8 rounded-lg bg-slate-100 border border-slate-200 text-slate-600 flex items-center justify-center font-black text-xs">
                                                    <?= strtoupper(substr($row['name'], 0, 1)) ?>
                                                </div>
                                                <div>
                                                    <a href="summary_attendance.php?employee_id=<?= $row['employee_id'] ?>&type=monthly&month=<?= $month ?>&year=<?= $year ?>" class="text-indigo-600 hover:text-indigo-800 font-bold hover:underline block text-xs search-name">
                                                        <?= htmlspecialchars($row['name']) ?>
                                                    </a>
                                                    <div class="text-[10px] text-slate-400 search-dept">
                                                        <?= htmlspecialchars($row['department'] ?: 'No Department Assigned') ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </td>
                                        <td class="p-3 text-center font-bold font-mono text-slate-600"><?= $row['scheduled_days'] ?></td>
                                        <td class="p-3 text-center text-emerald-600 font-black font-mono"><?= $row['days_worked'] ?></td>
                                        <td class="p-3 text-center text-rose-500 font-black font-mono"><?= $row['absent_days'] ?></td>
                                        <td class="p-3 text-center text-blue-600 font-black font-mono"><?= $row['leave_days'] ?></td>
                                        <td class="p-3 text-center font-mono font-medium text-slate-500"><?= number_format($row['hours_worked'], 2) ?></td>
                                        <td class="p-3 text-center whitespace-nowrap">
                                            <?php
                                            $pct = $row['attendance_percent'];
                                            $badgeClass = $pct >= 90 ? 'bg-emerald-50 text-emerald-700 border-emerald-100' : ($pct >= 75 ? 'bg-amber-50 text-amber-700 border-amber-100' : 'bg-rose-50 text-rose-700 border-rose-100');
                                            ?>
                                            <span class="px-2 py-0.5 text-[10px] font-bold border rounded <?= $badgeClass ?>"><?= $pct ?>%</span>
                                        </td>
                                        <td class="p-3 text-center whitespace-nowrap">
                                            <div class="flex items-center justify-center gap-2">
                                                <span id="surcharge_label_<?= $row['employee_id'] ?>" class="font-mono font-black text-xs <?= $row['surcharges'] > 0 ? 'text-rose-600 px-1.5 py-0.5 rounded bg-rose-50 border border-rose-100' : 'text-slate-400' ?>">
                                                    <?= $row['surcharges'] > 0 ? '₦' . number_format($row['surcharges'], 2) : '₦0.00' ?>
                                                </span>
                                                <button type="button" 
                                                        class="p-1 rounded bg-slate-50 border border-slate-200 text-[10px] hover:text-indigo-600 hover:border-indigo-300 transition" 
                                                        onclick="openSurchargeModal(this)"
                                                        data-employee-id="<?= $row['employee_id'] ?>"
                                                        data-name="<?= htmlspecialchars($row['name']) ?>"
                                                        data-surcharges="<?= $row['surcharges'] ?>"
                                                        data-late-count="<?= $row['late_count'] ?>"
                                                        data-incomplete-count="<?= $row['incomplete_count'] ?>"
                                                        data-absent-count="<?= $row['absent_days'] ?>">
                                                    ✏️
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                                <tr id="noResultsRow" class="hidden">
                                    <td colspan="8" class="p-12 text-center text-slate-400 font-medium">No matching employee records identified.</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </main>

            <footer class="mt-auto border-t border-slate-200/60 bg-white px-6 py-3 text-center">
                <p class="text-[9px] text-slate-400 font-mono tracking-wider">&copy; 2026 Core HR Engine • Metrics Ledger Framework.</p>
            </footer>
        </div>
    </div>

    <?php include 'surcharge_modal.php'; ?>

    <script src="../components/sidebar.js"></script>
    <script>
    function filterDashboardTable() {
        const input = document.getElementById('dashboardSearch').value.toLowerCase();
        const rows = document.getElementsByClassName('table-row-item');
        const noResultsRow = document.getElementById('noResultsRow');
        let visibleCount = 0;

        for (let i = 0; i < rows.length; i++) {
            const nameText = rows[i].querySelector('.search-name').textContent.toLowerCase();
            const deptText = rows[i].querySelector('.search-dept').textContent.toLowerCase();
            if (nameText.includes(input) || deptText.includes(input)) {
                rows[i].classList.remove('hidden');
                visibleCount++;
            } else {
                rows[i].classList.add('hidden');
            }
        }
        if (noResultsRow) {
            if (visibleCount === 0 && rows.length > 0) noResultsRow.classList.remove('hidden');
            else noResultsRow.classList.add('hidden');
        }
    }
    </script>
</body>
</html>