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

// ---------------------------
// SELECTED DATE & SEARCH
// ---------------------------
$selectedDate = $_GET['date'] ?? date('Y-m-d');
$search = $_GET['search'] ?? "";
$nextDate = date('Y-m-d', strtotime($selectedDate . ' +1 day'));

// ---------------------------
// LOAD EMPLOYEES
// ---------------------------
$employees = [];

$sql = "
    SELECT
        e.id,
        e.name,
        -- DAILY SCHEDULE FIRST
        COALESCE(ds.shift_id, e.shift_id) AS shift_id,
        s.name AS shift_name,
        s.checkin AS shift_checkin,
        s.checkout AS shift_checkout,
        s.crosses_midnight,
        s.color AS shift_color
    FROM employees e
    LEFT JOIN department_schedules ds
        ON ds.employee_id = e.id
        AND ds.schedule_date = ?
    LEFT JOIN shifts s
        ON s.id = COALESCE(ds.shift_id, e.shift_id)
    ORDER BY e.name
";

$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $selectedDate);
$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    $row['name'] = ltrim($row['name'], "'");
    $employees[$row['id']] = $row;
}
$stmt->close();

// ---------------------------
// LOAD EXCEPTIONS
// ---------------------------
$exceptions = [];
$res = $conn->query("SELECT employee_id, checkin, checkout FROM exceptions");
while ($row = $res->fetch_assoc()) {
    $exceptions[$row['employee_id']] = $row;
}

// ---------------------------
// LOAD ATTENDANCE
// ---------------------------
$rawLogs = [];

$sql = "
    SELECT a.employee_id, a.check_in, a.check_out, a.date
    FROM attendance a
    JOIN employees e ON e.id = a.employee_id
    WHERE (a.date = ? OR a.date = ?)
";

if ($search) {
    $sql .= " AND e.name LIKE ?";
}

$sql .= " ORDER BY a.date ASC, a.check_in ASC";

$stmt = $conn->prepare($sql);

if ($search) {
    $like = "%$search%";
    $stmt->bind_param("sss", $selectedDate, $nextDate, $like);
} else {
    $stmt->bind_param("ss", $selectedDate, $nextDate);
}

$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    $empId = $row['employee_id'];
    $rawLogs[$empId][] = $row;
}
$stmt->close();

// ---------------------------
// PROCESS ATTENDANCE
// ---------------------------
$attendance = [];

foreach ($employees as $empId => $emp) {
    $name = $emp['name'];

    // SHIFT INFO
    if (isset($exceptions[$empId])) {
        $expectedIn = $exceptions[$empId]['checkin'];
        $expectedOut = $exceptions[$empId]['checkout'];
        $shiftName = "Exception";
        $shiftColor = "#6b7280";
    } else {
        $expectedIn = $emp['shift_checkin'] ?? null;
        $expectedOut = $emp['shift_checkout'] ?? null;
        $shiftName = $emp['shift_name'] ?? 'No Shift';
        $shiftColor = $emp['shift_color'] ?? '#3490dc';
    }

    $cleanShiftName = strtoupper(trim($shiftName));
    $isPHShift = ($cleanShiftName === 'PH' || stripos($shiftName, 'Public Holiday') !== false);

    // ---------------------------
    // BUILD TIMELINE
    // ---------------------------
    $timeline = [];

    if (!empty($rawLogs[$empId])) {
        foreach ($rawLogs[$empId] as $log) {
            if (!empty($log['check_in'])) {
                $timeline[] = [
                    'type' => 'IN',
                    'datetime' => strtotime($log['date'] . ' ' . $log['check_in'])
                ];
            }
            if (!empty($log['check_out'])) {
                $timeline[] = [
                    'type' => 'OUT',
                    'datetime' => strtotime($log['date'] . ' ' . $log['check_out'])
                ];
            }
        }
    }

    // SORT TIMELINE
    usort($timeline, fn($a, $b) => $a['datetime'] <=> $b['datetime']);

    // ---------------------------
    // PAIR SHIFTS
    // ---------------------------
    $shifts = [];
    $currentIn = null;
    $totalHours = 0;

    foreach ($timeline as $event) {
        if ($event['type'] === 'IN') {
            if ($currentIn !== null) {
                $shifts[] = [
                    'check_in' => date('H:i:s', $currentIn),
                    'check_out' => null,
                    'hours' => 0
                ];
            }
            $currentIn = $event['datetime'];
        } 
        elseif ($event['type'] === 'OUT') {
            if ($currentIn !== null) {
                $hours = ($event['datetime'] - $currentIn) / 3600;

                $actualIn  = date('H:i:s', $currentIn);
                $actualOut = date('H:i:s', $event['datetime']);

                $late = false;
                $early = false;

                if ($expectedIn && strtotime($actualIn) > strtotime($expectedIn)) {
                    $late = true;
                }
                if ($expectedOut && strtotime($actualOut) < strtotime($expectedOut)) {
                    $early = true;
                }

                $shifts[] = [
                    'check_in'  => $actualIn,
                    'check_out' => $actualOut,
                    'hours'     => round($hours, 2),
                    'start_date'=> date('Y-m-d', $currentIn),
                    'late'      => $late,
                    'early'     => $early,
                    'worked_ph' => $isPHShift
                ];
                $totalHours += $hours;
                $currentIn = null;
            }
        }
    }

    // FINAL OPEN SHIFT
    if ($currentIn !== null) {
        $actualIn = date('H:i:s', $currentIn);
        $late = false;

        if ($expectedIn && strtotime($actualIn) > strtotime($expectedIn)) {
            $late = true;
        }

        $shifts[] = [
            'check_in'  => $actualIn,
            'check_out' => null,
            'hours'     => 0,
            'start_date'=> date('Y-m-d', $currentIn),
            'late'      => $late,
            'early'     => false,
            'worked_ph' => $isPHShift
        ];
    }

    // FILTER ONLY SELECTED DAY SHIFTS
    $filteredShifts = [];
    foreach ($shifts as $s) {
        if (($s['start_date'] ?? null) === $selectedDate) {
            $filteredShifts[] = $s;
        }
    }

    // --------------------------------------------------
    // LEAVE CHECK
    // --------------------------------------------------
    $leaveStatus = null;
    $leavePending = false;

    $leaveQuery = $conn->prepare("
        SELECT lt.name, lr.manager_status, lr.hr_status
        FROM leave_requests lr
        LEFT JOIN leave_types lt ON lt.id = lr.leave_type_id
        WHERE lr.employee_id = ? AND ? BETWEEN lr.start_date AND lr.end_date
        LIMIT 1
    ");
    $leaveQuery->bind_param("is", $empId, $selectedDate);
    $leaveQuery->execute();

    $managerStatus = '';
    $hrStatus = '';
    $leaveQuery->bind_result($leaveStatus, $managerStatus, $hrStatus);

    if ($leaveQuery->fetch()) {
        if ($managerStatus !== 'Approved' || $hrStatus !== 'Approved') {
            $leavePending = true;
            $leaveStatus = null;
        }
    }
    $leaveQuery->close();

    // --------------------------------------------------
    // HOLIDAY CHECK
    // --------------------------------------------------
    $isHoliday = false;
    $holidayName = '';

    $holidayQuery = $conn->prepare("
        SELECT holiday_name FROM public_holidays WHERE holiday_date = ? LIMIT 1
    ");
    $holidayQuery->bind_param("s", $selectedDate);
    $holidayQuery->execute();
    $holidayQuery->bind_result($holidayName);
    if($holidayQuery->fetch()){
        $isHoliday = true;
    }
    $holidayQuery->close();

    // --------------------------------------------------
    // NO ATTENDANCE (UPDATED FOR PH SHIFTS, OFF-DAYS & UPCOMING SHIFTS)
    // --------------------------------------------------
    if (empty($filteredShifts)) {
        $isOffDay = (stripos($shiftName, 'off') !== false || $shiftName === 'No Shift');
        
        $isNotResumedYet = false;
        $today = date('Y-m-d');

        if (!$isOffDay && !$isPHShift && $selectedDate === $today && !empty($expectedIn)) {
            $currentTimeString = date('H:i:s');
            $cutoffTime = strtotime($expectedIn) + 3600; 
            
            if (strtotime($currentTimeString) < $cutoffTime) {
                $isNotResumedYet = true;
            }
        }

        $filteredShifts[] = [
            'check_in'      => null,
            'check_out'     => null,
            'hours'         => 0,
            'late'          => false,
            'early'         => false,
            'absent'        => !$leaveStatus && !$isHoliday && !$isPHShift && !$isOffDay && !$isNotResumedYet,
            'off_day'       => $isOffDay && !$leaveStatus && !$isHoliday && !$isPHShift,
            'not_resumed'   => $isNotResumedYet && !$leaveStatus && !$isHoliday && !$isPHShift,
            'leave'         => $leaveStatus,
            'holiday'       => $isHoliday || $isPHShift,
            'holiday_name'  => $isHoliday ? $holidayName : ($isPHShift ? 'Public Holiday' : ''),
            'leave_pending' => $leavePending
        ];
    }

    // ---------------------------
    // STORE RESULT
    // ---------------------------
    $attendance[$name] = [
        'shifts'            => $filteredShifts,
        'total_hours'       => round($totalHours, 2),
        'expected_checkin'  => $expectedIn,
        'expected_checkout' => $expectedOut,
        'shift_name'        => $shiftName,
        'shift_color'       => $shiftColor
    ];
}

//$conn->close();
?>