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

// Check if session variables exist
if (!isset($_SESSION['view_pins']) || !isset($_SESSION['view_pin_term'])) {
    die('Session expired or invalid.');
}

$view_pin_term = $_SESSION['view_pin_term'];
$all_pins = $_SESSION['view_pins'];

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

$school_query = "SELECT * FROM `administratives` LIMIT 1";
$school_result = mysqli_query($connection, $school_query);
if ($school_result && mysqli_num_rows($school_result) > 0) {
    $school_data = mysqli_fetch_assoc($school_result);
    $school_name = $school_data['school_name'];
    $school_short_name = $school_data['school_short_name'];
    $school_website = $school_data['school_website'];
}

// Initialize PDF
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor($school_short_name);
$pdf->SetTitle("Unused Pins - {$view_pin_term}");
$pdf->SetMargins(10, 10, 10);
$pdf->SetAutoPageBreak(true, 15);
$pdf->AddPage();

// Title
$pdf->SetFont("Helvetica", 'B', 14);
$pdf->Cell(0, 10, "Unused Result Pins for $view_pin_term", 0, 1, 'C');
$pdf->Ln(2);

// Pin layout config
$pin_width = 90;
$pin_height = 40;
$pins_per_page = 12;

$x_start = 10;
$y = $pdf->GetY();
$count = 0;

$pdf->SetFont("Helvetica", '', 10);

foreach ($all_pins as $pin) {
    if ($count && $count % $pins_per_page == 0) {
        $pdf->AddPage();
        $pdf->SetFont("Helvetica", 'B', 14);
        $pdf->Cell(0, 10, "Unused Result Pins for $view_pin_term", 0, 1, 'C');
        $pdf->Ln(2);
        $y = $pdf->GetY();
    }

    $x = ($count % 2 == 0) ? $x_start : $x_start + $pin_width;

    // Draw each pin cell
    $pdf->SetXY($x, $y);
    $pdf->SetFont("Helvetica", 'B', 11);
    $pdf->MultiCell($pin_width, 7, "{$school_short_name} {$view_pin_term} PIN", 1, 'C');
    $pdf->SetFont("Helvetica", '', 10);
    $pdf->SetX($x);
    $pdf->MultiCell($pin_width, 6, "S/N: {$pin['serial_number']}", 1);
    $pdf->SetX($x);
    $pdf->MultiCell($pin_width, 6, "PIN: {$pin['unused_pin']}", 1);
    $pdf->SetX($x); $pdf->SetTextColor(255, 0, 0);
	$pdf->MultiCell($pin_width, 6, "NOTE: You can only Use this Pin 5 Times", 1, 'C');
    $pdf->SetX($x); $pdf->SetTextColor(0, 0, 255);
    $pdf->MultiCell($pin_width, 6, "{$school_website}", 1, 'C');
    $pdf->SetTextColor(0, 0, 0);

    if ($count % 2 == 1) {
        $y += $pin_height;
    }

    $count++;
}

ob_end_clean();
$pdf->Output("Unused_Pins_{$view_pin_term}.pdf", 'I');

