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

// FPDF (no Composer)
require_once 'fpdf/fpdf.php';

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

if (!$startDate || !$endDate) {
    die('Start and end dates are required.');
}

try {
    $start = new DateTime($startDate);
    $end   = new DateTime($endDate);
} catch (Exception $e) {
    die('Invalid date format.');
}

// End date should NOT be considered as a leave day
$end->modify('-1 day');
if ($end < $start) {
    die('End date must be after start date.');
}

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

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

// 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) {
    die('Leave query error: ' . $conn->error);
}

// Build matrix and employees list
// Symbols: F = Full, H1 = First half, H2 = Second half, S = Short
$cellMap   = [];
$employees = [];
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']);
    $leaveEnd->modify('-1 day');

    if ($leaveStart < $start) $leaveStart = clone $start;
    if ($leaveEnd > $end)     $leaveEnd   = clone $end;
    if ($leaveEnd < $leaveStart) continue;

    $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';
    }

    $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 = ['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 no data, generate styled message
if (empty($employees) || empty($dateHeaders)) {
    $pdf = new FPDF('L', 'mm', 'A4');
    $pdf->AddPage();

    $pdf->SetFillColor(102, 126, 234);
    $pdf->Rect(0, 0, 297, 40, 'F');

    $pdf->SetTextColor(255, 255, 255);
    $pdf->SetFont('Arial', 'B', 20);
    $pdf->SetY(12);
    $pdf->Cell(0, 10, 'LEAVE GRID REPORT', 0, 1, 'C');
    $pdf->SetFont('Arial', '', 12);
    $pdf->Cell(0, 8, 'Leave Management System', 0, 1, 'C');

    $pdf->SetY(60);
    $pdf->SetTextColor(100, 100, 100);
    $pdf->SetFont('Arial', 'I', 12);
    $pdf->Cell(0, 10, 'No employees with approved leaves in this period (Mon-Fri).', 0, 1, 'C');

    $filename = 'Leave_Grid_'.$start->format('Y-m-d').'_to_'.$end->format('Y-m-d').'.pdf';
    $pdf->Output('D', $filename);
    exit;
}

// Create PDF
$pdf = new FPDF('L', 'mm', 'A4');
$pdf->SetAutoPageBreak(true, 12);
$pdf->SetMargins(8, 8, 8);
$pdf->AddPage();

// Header bar
$pdf->SetFillColor(102, 126, 234);
$pdf->Rect(0, 0, 297, 30, 'F');

$pdf->SetTextColor(255, 255, 255);
$pdf->SetFont('Arial', 'B', 16);
$pdf->SetY(7);
$pdf->Cell(0, 7, 'LEAVE GRID REPORT', 0, 1, 'C');

$pdf->SetFont('Arial', '', 9);
$pdf->Cell(0, 5, 'Period: '.$start->format('d M Y').' to '.$end->format('d M Y').' (Mon-Fri)', 0, 1, 'C');
$pdf->SetFont('Arial', 'I', 8);
$pdf->Cell(0, 5, 'Generated: '.date('d M Y, h:i A'), 0, 1, 'C');

$pdf->Ln(3);

// Column widths
$pageWidth     = 297 - 16;
$empColWidth   = 55;
$totalColWidth = 15;
$available     = $pageWidth - $empColWidth - $totalColWidth;
$dateColWidth  = $available / count($dateHeaders);
if ($dateColWidth < 6) {
    $dateColWidth = 6;
}

// Header row (horizontal dates)
$tableStartY = $pdf->GetY();
$pdf->SetFont('Arial', 'B', 7);
$pdf->SetFillColor(70, 130, 180);
$pdf->SetTextColor(255, 255, 255);
$pdf->SetDrawColor(50, 50, 50);

$headerHeight = 8;

$pdf->SetXY(8, $tableStartY);
$pdf->Cell($empColWidth, $headerHeight, 'EMPLOYEE', 1, 0, 'C', true);

$currentX = 8 + $empColWidth;
foreach ($dateHeaders as $d) {
    $dt   = new DateTime($d);
    $lbl  = $dt->format('d-M'); // e.g. 23-Mar
    $pdf->SetXY($currentX, $tableStartY);
    $pdf->Cell($dateColWidth, $headerHeight, $lbl, 1, 0, 'C', true);
    $currentX += $dateColWidth;
}

$pdf->SetXY($currentX, $tableStartY);
$pdf->Cell($totalColWidth, $headerHeight, 'TOTAL', 1, 1, 'C', true);

// Data rows
$pdf->SetFont('Arial', '', 7);
$pdf->SetTextColor(0, 0, 0);
$rowNum    = 0;
$rowHeight = 6;

foreach ($employees as $id => $info) {
    $rowNum++;

    if ($rowNum % 2 === 0) {
        $pdf->SetFillColor(248, 250, 252);
    } else {
        $pdf->SetFillColor(255, 255, 255);
    }

    $currentX = 8;
    $pdf->SetXY($currentX, $pdf->GetY());
    $pdf->Cell($empColWidth, $rowHeight, substr($info['name'], 0, 28).' ('.$info['emp_id'].')', 1, 0, 'L', true);
    $currentX += $empColWidth;

    $totalDays = 0.0;

    foreach ($dateHeaders as $d) {
        if (isset($cellMap[$id][$d])) {
            $sym = $cellMap[$id][$d];

            if ($sym === 'F') {
                $totalDays += 1.0;
                $pdf->SetFillColor(144, 238, 144);
                $pdf->SetTextColor(0, 100, 0);
            } elseif ($sym === 'H1' || $sym === 'H2' || $sym === 'H') {
                $totalDays += 0.5;
                $pdf->SetFillColor(255, 255, 153);
                $pdf->SetTextColor(153, 102, 0);
            } elseif ($sym === 'S') {
                $totalDays += 0.5;
                $pdf->SetFillColor(255, 200, 150);
                $pdf->SetTextColor(204, 102, 0);
            }

            $pdf->SetFont('Arial', 'B', 7);
            $pdf->SetXY($currentX, $pdf->GetY());
            $pdf->Cell($dateColWidth, $rowHeight, $sym, 1, 0, 'C', true);
            $pdf->SetTextColor(0, 0, 0);
        } else {
            if ($rowNum % 2 === 0) {
                $pdf->SetFillColor(248, 250, 252);
            } else {
                $pdf->SetFillColor(255, 255, 255);
            }
            $pdf->SetXY($currentX, $pdf->GetY());
            $pdf->Cell($dateColWidth, $rowHeight, '', 1, 0, 'C', true);
        }
        $currentX += $dateColWidth;
    }

    $pdf->SetFillColor(230, 240, 250);
    $pdf->SetFont('Arial', 'B', 8);
    $pdf->SetXY($currentX, $pdf->GetY());
    $pdf->Cell($totalColWidth, $rowHeight, rtrim(rtrim(number_format($totalDays, 1), '0'), '.'), 1, 1, 'C', true);
    $pdf->SetFont('Arial', '', 7);
}

// Summary + Legend
$pdf->Ln(3);
$pdf->SetFont('Arial', 'B', 9);
$pdf->SetFillColor(240, 248, 255);
$pdf->SetTextColor(50, 50, 50);
$pdf->SetDrawColor(70, 130, 180);

$pdf->SetX(8);
$pdf->Cell(35, 6, 'Total Employees:', 1, 0, 'L', true);
$pdf->SetFont('Arial', '', 9);
$pdf->Cell(25, 6, count($employees), 1, 0, 'C', true);
$pdf->SetFont('Arial', 'B', 9);
$pdf->Cell(35, 6, 'Working Days:', 1, 0, 'L', true);
$pdf->SetFont('Arial', '', 9);
$pdf->Cell(25, 6, count($dateHeaders), 1, 1, 'C', true);

$pdf->Ln(2);
$pdf->SetFont('Arial', 'B', 9);
$pdf->SetTextColor(50, 50, 50);
$pdf->Cell(0, 5, 'LEGEND', 0, 1, 'L');

$legendY = $pdf->GetY();
$legendX = 8;

// F
$pdf->SetXY($legendX, $legendY);
$pdf->SetFillColor(144, 238, 144);
$pdf->SetFont('Arial', 'B', 8);
$pdf->Cell(8, 5, 'F', 1, 0, 'C', true);
$pdf->SetFont('Arial', '', 8);
$pdf->Cell(30, 5, ' Full Day (1.0)', 0, 0, 'L');

$legendX += 45;

// H1
$pdf->SetXY($legendX, $legendY);
$pdf->SetFillColor(255, 255, 153);
$pdf->SetFont('Arial', 'B', 8);
$pdf->Cell(10, 5, 'H1', 1, 0, 'C', true);
$pdf->SetFont('Arial', '', 8);
$pdf->Cell(35, 5, ' First Half (0.5)', 0, 0, 'L');

$legendX += 55;

// H2
$pdf->SetXY($legendX, $legendY);
$pdf->SetFillColor(255, 255, 153);
$pdf->SetFont('Arial', 'B', 8);
$pdf->Cell(10, 5, 'H2', 1, 0, 'C', true);
$pdf->SetFont('Arial', '', 8);
$pdf->Cell(35, 5, ' Second Half (0.5)', 0, 0, 'L');

$legendX += 55;

// S
$pdf->SetXY($legendX, $legendY);
$pdf->SetFillColor(255, 200, 150);
$pdf->SetFont('Arial', 'B', 8);
$pdf->Cell(8, 5, 'S', 1, 0, 'C', true);
$pdf->SetFont('Arial', '', 8);
$pdf->Cell(40, 5, ' Short Leave (0.5)', 0, 1, 'L');

// Note
$pdf->Ln(2);
$pdf->SetFont('Arial', 'I', 7);
$pdf->SetTextColor(100, 100, 100);
$pdf->MultiCell(0, 4, 'Note: Saturdays and Sundays are excluded from the leave count. Only working days (Monday to Friday) are considered.', 0, 'L');

// Footer
$pdf->SetY(-10);
$pdf->SetFont('Arial', 'I', 8);
$pdf->SetTextColor(150, 150, 150);
$pdf->Cell(0, 10, 'Leave Management System - Page '.$pdf->PageNo(), 0, 0, 'C');

$filename = 'Leave_Grid_'.$start->format('Y-m-d').'_to_'.$end->format('Y-m-d').'.pdf';
$pdf->Output('D', $filename);
