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

require_once 'tcpdf/tcpdf.php';

$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';

$where = "WHERE 1=1";
if ($start_date && $end_date) {
    $where .= " AND la.start_date >= '$start_date' AND la.end_date <= '$end_date'";
}

$sql = "SELECT la.*, u.full_name, u.employee_id as emp_id, u.department 
        FROM leave_applications la
        JOIN users u ON la.user_id = u.id
        $where
        ORDER BY la.apply_date DESC";

$result = $conn->query($sql);

// Create PDF
$pdf = new TCPDF('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Leave Management System');
$pdf->SetTitle('All Leaves Report');

$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);

$pdf->AddPage();

$pdf->SetFont('helvetica', 'B', 18);
$pdf->Cell(0, 10, 'All Employees Leave Applications Report', 0, 1, 'C');

if ($start_date && $end_date) {
    $pdf->SetFont('helvetica', '', 11);
    $pdf->Cell(0, 6, "Period: $start_date to $end_date", 0, 1, 'C');
}

$pdf->Ln(5);

$html = '<table border="1" cellpadding="4" style="width: 100%;">
<thead>
    <tr style="background-color: #427eea; color: white; font-weight: bold;">
        <th width="10%">Emp ID</th>
        <th width="15%">Name</th>
        <th width="12%">Department</th>
        <th width="10%">Leave Type</th>
        <th width="10%">Start Date</th>
        <th width="10%">End Date</th>
        <th width="6%">Days</th>
        <th width="17%">Reason</th>
        <th width="10%">Status</th>
    </tr>
</thead>
<tbody>';

$pdf->SetFont('helvetica', '', 8);

while ($row = $result->fetch_assoc()) {
    $status_color = $row['status'] === 'approved' ? '#28a745' : ($row['status'] === 'rejected' ? '#dc3545' : '#ffc107');
    
    $html .= '<tr>
        <td>' . htmlspecialchars($row['emp_id']) . '</td>
        <td>' . htmlspecialchars($row['full_name']) . '</td>
        <td>' . htmlspecialchars($row['department']) . '</td>
        <td>' . ucfirst($row['leave_type']) . '</td>
        <td>' . date('Y-m-d', strtotime($row['start_date'])) . '</td>
        <td>' . date('Y-m-d', strtotime($row['end_date'])) . '</td>
        <td>' . $row['number_of_days'] . '</td>
        <td>' . htmlspecialchars(substr($row['reason'], 0, 40)) . '</td>
        <td style="color: ' . $status_color . '"><b>' . ucfirst($row['status']) . '</b></td>
    </tr>';
}

$html .= '</tbody></table>';

$pdf->writeHTML($html, true, false, true, false, '');

$filename = 'all_leaves_report_' . date('Y-m-d_His') . '.pdf';
$pdf->Output($filename, 'D');
?>
