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

require_once 'tcpdf/tcpdf.php';

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

// Filter only APPROVED leaves and exclude SHORT leaves
$where = "WHERE la.user_id = $user_id AND la.status = 'approved' AND la.leave_type != 'short'";
if ($start_date && $end_date) {
    $where .= " AND la.start_date >= '$start_date' AND la.end_date <= '$end_date'";
}

// Get user details including designation
$sql_user = "SELECT u.full_name, u.employee_id, u.designation 
             FROM users u 
             WHERE u.id = $user_id";
$user_result = $conn->query($sql_user);
$user_data   = $user_result->fetch_assoc();

$employee_name = $user_data['full_name'];
$designation   = $user_data['designation'] ?? '';

// Get APPROVED leave applications (excluding short leaves)
$sql = "SELECT la.*, u.full_name, u.employee_id as emp_id 
        FROM leave_applications la
        JOIN users u ON la.user_id = u.id
        $where
        ORDER BY la.start_date ASC";
$result = $conn->query($sql);

// Create PDF in PORTRAIT orientation, UNICODE enabled
$pdf = new TCPDF('P', PDF_UNIT, 'A4', true, 'UTF-8', false);

$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Leave Management System');
$pdf->SetTitle('Teachers Leave Register - B100');

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

// Set margins
$pdf->SetMargins(10, 10, 10);
$pdf->SetAutoPageBreak(true, 20);

// Load Sinhala-capable TTF font (Noto Sans Sinhala)
$pdf->setFontSubsetting(true);
$fontPath = __DIR__ . '/tcpdf/fonts/NotoSansSinhala-Regular.ttf';
if (file_exists($fontPath)) {
    $fontname = TCPDF_FONTS::addTTFfont($fontPath, 'TrueTypeUnicode', '', 32);
} else {
    // fallback: use freeserif if Noto is not present
    $fontname = 'freeserif';
}
$pdf->SetFont($fontname, '', 10);

// Header function
function addPageHeader($pdf, $employee_name, $designation, $fontname) {
    // Top right corner: B100
    $pdf->SetFont('helvetica', '', 10);
    $pdf->SetXY(-30, 8);
    $pdf->Cell(20, 5, 'B100', 0, 0, 'R');

    // Title
    $pdf->SetFont('helvetica', 'B', 14);
    $pdf->SetY(12);
    $pdf->Cell(0, 8, 'TEACHERS LEAVE REGISTER', 0, 1, 'C');

    $pdf->Ln(3);

    // Employee details in Unicode font
    $pdf->SetFont($fontname, '', 10);

    $pdf->Cell(40, 5, 'Name of Employee:', 0, 0, 'L');
    $pdf->Cell(0, 5, $employee_name, 0, 1, 'L');

    $pdf->Cell(40, 5, 'Designation:', 0, 0, 'L');
    $pdf->Cell(70, 5, $designation, 0, 0, 'L');
    $pdf->Cell(50, 5, 'Date of First Appointment:', 0, 0, 'L');
    $pdf->Cell(0, 5, '________________', 0, 1, 'L');

    $pdf->Ln(3);
}

$pdf->AddPage();
addPageHeader($pdf, $employee_name, $designation, $fontname);

// Table header
$table_header = '<style>
    table {
        border-collapse: collapse;
        width: 100%;
        font-family: ' . $fontname . ';
    }
    th {
        background-color: #ffffff;
        color: #000000;
        font-weight: bold;
        text-align: center;
        padding: 4px 2px;
        border: 1px solid #000000;
        font-size: 8pt;
        line-height: 1.1;
        vertical-align: middle;
    }
    td {
        padding: 6px 2px;
        border: 1px solid #000000;
        text-align: center;
        font-size: 7.5pt;
        background-color: #ffffff;
        vertical-align: middle;
    }
    .reason-col {
        text-align: left;
        padding-left: 4px;
        font-size: 7pt;
    }
    .total-row td {
        font-weight: bold;
    }
</style>

<table border="1" cellpadding="2" cellspacing="0">
<thead>
    <tr>
        <th colspan="2" style="border-right: 2px solid #000000;">Date</th>
        <th colspan="2" style="border-right: 2px solid #000000;">Full Pay Leave</th>
        <th rowspan="2" style="border-right: 2px solid #000000;">Half<br/>Pay</th>
        <th rowspan="2" style="border-right: 2px solid #000000;">No<br/>Pay</th>
        <th rowspan="2" style="border-right: 2px solid #000000;">Reason for Leave or<br/>Nature of Sickness</th>
        <th rowspan="2">Signature</th>
    </tr>
    <tr>
        <th style="border-right: 1px solid #000000;">From</th>
        <th style="border-right: 2px solid #000000;">To</th>
        <th style="border-right: 1px solid #000000;">Casual</th>
        <th style="border-right: 2px solid #000000;">Sick</th>
    </tr>
</thead>
<tbody>';

$table_footer = '</tbody></table>';

// Totals
$total_casual = 0;
$total_sick   = 0;
$total_half   = 0;
$total_nopay  = 0;

$table_rows = '';

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $from_date  = date('Y-m-d', strtotime($row['start_date']));
        $to_date    = date('Y-m-d', strtotime($row['end_date']));
        $leave_type = strtolower($row['leave_type']);
        $days       = (float)$row['number_of_days'];
        $reason     = htmlspecialchars($row['reason'], ENT_QUOTES, 'UTF-8');

        $casual_days = '';
        $sick_days   = '';
        $half_pay    = '';
        $no_pay      = '';

        if ($leave_type === 'casual') {
            $casual_days   = $days;
            $total_casual += $days;
        } elseif ($leave_type === 'medical') {
            $sick_days   = $days;
            $total_sick += $days;
        } elseif ($leave_type === 'duty') {
            $half_pay   = $days;
            $total_half += $days;
        } elseif ($leave_type === 'nopay' || $leave_type === 'no_pay') {
            $no_pay     = $days;
            $total_nopay += $days;
        }

        $table_rows .= '<tr>
            <td style="border-right: 1px solid #000000;">' . $from_date . '</td>
            <td style="border-right: 2px solid #000000;">' . $to_date . '</td>
            <td style="border-right: 1px solid #000000;">' . $casual_days . '</td>
            <td style="border-right: 2px solid #000000;">' . $sick_days . '</td>
            <td style="border-right: 2px solid #000000;">' . $half_pay . '</td>
            <td style="border-right: 2px solid #000000;">' . $no_pay . '</td>
            <td class="reason-col" style="border-right: 2px solid #000000;">' . $reason . '</td>
            <td>&nbsp;</td>
        </tr>';
    }
} else {
    for ($i = 0; $i < 20; $i++) {
        $table_rows .= '<tr>
            <td style="border-right: 1px solid #000000;">&nbsp;</td>
            <td style="border-right: 2px solid #000000;">&nbsp;</td>
            <td style="border-right: 1px solid #000000;">&nbsp;</td>
            <td style="border-right: 2px solid #000000;">&nbsp;</td>
            <td style="border-right: 2px solid #000000;">&nbsp;</td>
            <td style="border-right: 2px solid #000000;">&nbsp;</td>
            <td style="border-right: 2px solid #000000;">&nbsp;</td>
            <td>&nbsp;</td>
        </tr>';
    }
}

// Total row
$table_rows .= '<tr class="total-row">
    <td colspan="2" style="border-right: 2px solid #000000; text-align:right;">Total</td>
    <td style="border-right: 1px solid #000000;">' . $total_casual . '</td>
    <td style="border-right: 2px solid #000000;">' . $total_sick . '</td>
    <td style="border-right: 2px solid #000000;">' . $total_half . '</td>
    <td style="border-right: 2px solid #000000;">' . $total_nopay . '</td>
    <td colspan="2">&nbsp;</td>
</tr>';

$complete_table = $table_header . $table_rows . $table_footer;

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

// Notes text
$pdf->Ln(4);
$pdf->SetFont($fontname, '', 9);

$note = "N.B.- At the end of each year the Head Teacher should total the leave taken by each Teacher.\n\n"
      
      . "
I certify that the above leave details are a true copy extracted from page number ..............of the Educational Leave Register for the year ............... maintained at B/Passara Central College.";

$pdf->MultiCell(0, 5, $note, 0, 'L', false, 1);

$pdf->Ln(10);

// Bottom signature block
$pdf->SetFont($fontname, '', 10);

// Left: prepared by
$pdf->Cell(40, 6, 'Preapared by', 0, 0, 'L');
$pdf->Cell(60, 6, '_________________________', 0, 0, 'L');

// Right: blank line for Principal signature ABOVE the text
$pdf->Cell(40, 6, '', 0, 0); // spacer
$pdf->Cell(45, 6, '____________________', 0, 1, 'R'); // blank line

// Next line: principal text under the line
$pdf->Cell(40, 6, '', 0, 0, 'L');
$pdf->Cell(60, 6, '', 0, 0, 'L');
$pdf->Cell(40, 6, '', 0, 0);
$pdf->Cell(45, 6, 'Principal', 0, 1, 'R');

$pdf->Ln(6);

// Under "සකස් කලේ": checked by
$pdf->Cell(40, 6, 'Checked By', 0, 0, 'L');
$pdf->Cell(60, 6, '_________________________', 0, 0, 'L');

$pdf->Ln(4);

// Output PDF
$filename = 'B100_Leave_Register_Approved_' . $user_data['employee_id'] . '_' . date('Ymd') . '.pdf';
$pdf->Output($filename, 'D');
?>
