<?php
ob_start();
session_start();
chdir('../');
require_once('assets/vendor/tcpdf/tcpdf.php');
require_once("public/connection.php");
require_once("public/functions.php");

// Fetch school info
$school_name = '';
$school_short_name = '';
$school_website = '';

$query = "SELECT * FROM `administratives`";
$run_query = mysqli_query($connection, $query);
if ($run_query && mysqli_num_rows($run_query) > 0) {
    $result = mysqli_fetch_assoc($run_query);
    $school_name = $result['school_name'];
    $school_short_name = $result['school_short_name'];
    $school_website = $result['school_website'];
}


if (!isset($_POST['download_pdf_btn']) || empty($_POST['term'])) {
    $_SESSION['msg'] = "Invalid access to PDF generation.";
    $_SESSION['type'] = "error";
    header("Location: view_uploaded_pins");
    exit;
}

$term = $_POST['term'];
$term_table_map = [
    "First Term" => ["table" => "pin1", "column" => "first_term_pin"],
    "Second Term" => ["table" => "pin2", "column" => "second_term_pin"],
    "Third Term" => ["table" => "pin3", "column" => "third_term_pin"]
];

if (!isset($term_table_map[$term])) {
    $_SESSION['msg'] = "Invalid term selected.";
    $_SESSION['type'] = "error";
    header("Location: view_uploaded_pins");
    exit;
}

$table_name = $term_table_map[$term]['table'];
$pin_column = $term_table_map[$term]['column'];

$stmt = $connection->prepare("SELECT serial_number, `$pin_column` AS pin FROM `$table_name` WHERE term = ?");
$stmt->bind_param("s", $term);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['msg'] = "No pins found for selected term.";
    $_SESSION['type'] = "error";
    header("Location: view_uploaded_pins");
    exit;
}

// Setup PDF
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8');
$pdf->SetCreator($school_name);
$pdf->SetAuthor($school_short_name);
$pdf->SetTitle("$term Result Pins");
$pdf->SetMargins(10, 10, 10, true);
$pdf->AddPage();

// Start HTML
$html = "<h3 style='text-align:center;'>$term Result Pins</h3>";
$html .= "<table border='1' cellspacing='3' cellpadding='4' width='100%'>";

$i = 0;
while ($row = $result->fetch_assoc()) {
    if ($i % 2 == 0) $html .= "<tr>";
    $html .= "<td>
        <h4 style='text-align:center;'>{$school_short_name} Result Pin</h4>
        <strong>TERM:</strong> {$term}<br>
        <strong>S/N:</strong> {$row['serial_number']}<br>
        <strong>PIN:</strong> {$row['pin']}<br>
        <p style='font-size:10px;color:red;text-align:center;'>NOTE: You can only Use this Pin 5 Times</p>
        <p style='font-size:10px;color:blue;text-align:center;'>{$school_website}/result</p>
    </td>";
    if ($i % 2 == 1) $html .= "</tr>";
    $i++;
}
if ($i % 2 == 1) $html .= "<td></td></tr>"; // close row if odd number
$html .= "</table>";

// Output PDF
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output("{$school_short_name} {$term}_result_pins.pdf", 'I');
exit;
?>

