<?php
require_once 'config.php';
require_once 'auth_functions.php';
requireAdmin();

$startDate = $_GET['start_date'] ?? null;
$endDate   = $_GET['end_date'] ?? null;

if (!$startDate || !$endDate) {
    echo '<div class="alert alert-danger">Start and end dates are required.</div>';
    exit;
}

try {
    $start = new DateTime($startDate);
    $end   = new DateTime($endDate);
} catch (Exception $e) {
    echo '<div class="alert alert-danger">Invalid date format.</div>';
    exit;
}

// End date (filter) should NOT be considered as a leave day
$end->modify('-1 day');
if ($end < $start) {
    echo '<div class="alert alert-warning">End date must be after start date.</div>';
    exit;
}

// Build list of working dates for header (Mon–Fri), inclusive
$dateHeaders = [];
$cursor = clone $start;
$endInclusive = clone $end;

while ($cursor <= $endInclusive) {
    $dayOfWeek = (int)$cursor->format('N'); // 1=Mon ... 7=Sun
    if ($dayOfWeek < 6) { // Mon–Fri only
        $dateHeaders[] = $cursor->format('Y-m-d');
    }
    $cursor->modify('+1 day');
}

if (empty($dateHeaders)) {
    echo '<div class="alert alert-info">No working days in this period.</div>';
    exit;
}

// Get approved leaves + employee info
$startDateSql  = $conn->real_escape_string($startDate);
$endPlusOne    = (clone $end)->modify('+1 day')->format('Y-m-d');
$endPlusOneSql = $conn->real_escape_string($endPlusOne);

$sqlLeaves = "
    SELECT la.user_id,
           la.start_date,
           la.end_date,
           la.leave_type,
           la.is_half_day,
           la.half_day_session,
           la.short_leave_time,
           u.full_name,
           u.employee_id
    FROM leave_applications la
    INNER JOIN users u ON la.user_id = u.id
    WHERE la.status = 'approved'
      AND la.start_date < '$endPlusOneSql'
      AND la.end_date > '$startDateSql'
      AND u.role = 'employee'
    ORDER BY u.full_name
";
$resLeaves = $conn->query($sqlLeaves);
if (!$resLeaves) {
    echo '<div class="alert alert-danger">Leave query error: ' . htmlspecialchars($conn->error) . '</div>';
    exit;
}

// Build matrix and employees list with symbols
// Symbols: F = Full day, H1 = Half (first), H2 = Half (second), S = Short leave
$cellMap   = []; // [user_id][date] = symbol
$employees = []; // [user_id] = ['name' => ..., 'emp_id' => ...]
while ($row = $resLeaves->fetch_assoc()) {
    $userId = $row['user_id'];

    if (!isset($employees[$userId])) {
        $employees[$userId] = [
            'name'   => $row['full_name'],
            'emp_id' => $row['employee_id']
        ];
    }

    $leaveStart = new DateTime($row['start_date']);
    $leaveEnd   = new DateTime($row['end_date']);

    // Do NOT count DB end_date itself as leave day
    $leaveEnd->modify('-1 day');

    // Clamp to selected range
    if ($leaveStart < $start) $leaveStart = clone $start;
    if ($leaveEnd > $end)     $leaveEnd   = clone $end;
    if ($leaveEnd < $leaveStart) {
        continue;
    }

    // Determine base symbol
    $symbol = 'F';
    if ((int)$row['is_half_day'] === 1) {
        if ($row['half_day_session'] === 'first_half') {
            $symbol = 'H1';
        } elseif ($row['half_day_session'] === 'second_half') {
            $symbol = 'H2';
        } else {
            $symbol = 'H';
        }
    } elseif ($row['leave_type'] === 'short') {
        $symbol = 'S';
    }

    // Fill days (skip weekends)
    $p = new DatePeriod($leaveStart, new DateInterval('P1D'), (clone $leaveEnd)->modify('+1 day'));
    foreach ($p as $d) {
        $dayOfWeek = (int)$d->format('N');
        if ($dayOfWeek >= 6) {
            continue; // skip Sat/Sun
        }
        $dateKey = $d->format('Y-m-d');
        if (!in_array($dateKey, $dateHeaders, true)) {
            continue;
        }

        if (isset($cellMap[$userId][$dateKey])) {
            $existing = $cellMap[$userId][$dateKey];
            // Priority: S > H1/H2/H > F
            $priority = ['F' => 1, 'H' => 2, 'H1' => 2, 'H2' => 2, 'S' => 3];
            if ($priority[$symbol] > $priority[$existing]) {
                $cellMap[$userId][$dateKey] = $symbol;
            }
        } else {
            $cellMap[$userId][$dateKey] = $symbol;
        }
    }
}

if (empty($employees)) {
    echo '<div class="alert alert-info">No employees with approved leaves in this period.</div>';
    exit;
}

// Render table
echo '<table class="table table-bordered table-sm">';
echo '<thead><tr>';
echo '<th>Employee</th>';
foreach ($dateHeaders as $d) {
    $label = (new DateTime($d))->format('d-m');
    echo '<th class="text-center">'.htmlspecialchars($label).'</th>';
}
echo '<th class="text-center">Total Days</th>';
echo '</tr></thead><tbody>';

foreach ($employees as $id => $info) {
    echo '<tr>';
    echo '<td>'.htmlspecialchars($info['name'] . ' (' . $info['emp_id'] . ')').'</td>';
    $totalDays = 0.0;

    foreach ($dateHeaders as $d) {
        if (isset($cellMap[$id][$d])) {
            $sym = $cellMap[$id][$d];
            if ($sym === 'F') {
                $totalDays += 1.0;
            } elseif ($sym === 'H' || $sym === 'H1' || $sym === 'H2' || $sym === 'S') {
                $totalDays += 0.5;
            }
            echo '<td class="text-center fw-bold">'.htmlspecialchars($sym).'</td>';
        } else {
            echo '<td></td>';
        }
    }

    echo '<td class="text-center">'.rtrim(rtrim(number_format($totalDays, 1), '0'), '.').'</td>';
    echo '</tr>';
}

echo '</tbody></table>';

echo '<div class="mt-2 small">';
echo '<strong>Legend:</strong> F = Full day, H1 = Half (first half), H2 = Half (second half), S = Short leave (Sat/Sun excluded)';
echo '</div>';
