<?php
chdir('../');
ob_start();
session_start();

// T07: display_errors removed for production safety
// ini_set('display_errors', 1);
// error_reporting(E_ALL);

require_once("public/connection.php");
require_once("public/functions.php");
require_once("assets/vendor/tcpdf/tcpdf.php");

// Allow remote images if ever needed
define("K_TCPDF_EXTERNAL_IMAGES", true);

$payment_id = isset($_GET['payment_id']) ? (int)$_GET['payment_id'] : 0;
if ($payment_id <= 0) {
    die("Invalid payment ID.");
}

// Fetch fee payment
$payment_query = $connection->query("SELECT * FROM fee_payment WHERE id = $payment_id");
if (!$payment_query || $payment_query->num_rows === 0) {
    die("Payment not found.");
}
$payment = $payment_query->fetch_assoc();

$amount_paid = $payment['amount_paid'];

// ✅ Get total fee from fee_structure
$fee_query = $connection->prepare("SELECT amount FROM fee_structure 
    WHERE class = ? AND term = ? AND session = ? LIMIT 1");
$fee_query->bind_param(
    "sss", 
    $payment['student_class'], 
    $payment['fee_term'], 
    $payment['fee_session']
);
$fee_query->execute();
$fee_result = $fee_query->get_result();

if ($fee_result->num_rows > 0) {
    $fee_data = $fee_result->fetch_assoc();
    $total_school_fee = $fee_data['amount'];
} else {
    $total_school_fee = $amount_paid; // fallback if no structure found
}

$balance = $total_school_fee - $amount_paid;

// Fetch school details
$school_query = $connection->query("SELECT school_name, school_motto, school_address, school_phone, school_website 
    FROM administratives LIMIT 1");
if (!$school_query || $school_query->num_rows === 0) {
    die("School details not found.");
}
$school = $school_query->fetch_assoc();

$issued_date = date('Y-m-d H:i', strtotime($payment['date_of_upload']));
$created_by = $payment['created_by'];
$status = $payment['payment_status'];

// Sanitize student name for file name
$student_name = preg_replace('/[^A-Za-z0-9\-]/', '_', $payment['student_name']);
$student_name = trim($student_name, '_');

// ========================
// Detect printer type
// ========================
$printer_type = isset($_GET['printer']) ? strtolower($_GET['printer']) : "a4";

// Page setup
if ($printer_type === "thermal") {
    $pageWidth = 80; 
    $pageHeight = 200;
    $pdf = new TCPDF('P', 'mm', array($pageWidth, $pageHeight), true, 'UTF-8', false);
    $pdf->SetMargins(5, 5, 5);
    $pdf->SetFont('helvetica', '', 9);
} else {
    // Default A4 (works on all standard printers)
    $pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
    $pdf->SetMargins(15, 15, 15);
    $pdf->SetFont('helvetica', '', 11);
}

$pdf->SetTitle('Receipt_' . $payment['id']);
$pdf->SetAutoPageBreak(TRUE, 10);
$pdf->AddPage();

// ========================
// School Info (no logo)
// ========================
$html = '<div style="text-align:center;">
    <strong style="font-size:14px;">' . htmlspecialchars($school['school_name']) . '</strong><br>
    <em>' . htmlspecialchars($school['school_motto']) . '</em><br>
    ' . htmlspecialchars($school['school_address']) . '<br>
    Tel: ' . htmlspecialchars($school['school_phone']) . '<br>
    ' . htmlspecialchars($school['school_website']) . '
</div>
<hr>
<div style="font-size:10px;">
Received By: ' . htmlspecialchars($created_by) . '<br>
Date: ' . $issued_date . '<br>
Receipt #: ' . htmlspecialchars($payment['id']) . '<br>
Student: ' . htmlspecialchars($payment['student_name']) . '<br>
Reg No: ' . htmlspecialchars($payment['reg_number']) . '<br>
Class: ' . htmlspecialchars($payment['student_class']) . '<br>
Term: ' . htmlspecialchars($payment['fee_term']) . '<br>
Session: ' . htmlspecialchars($payment['fee_session']) . '<br>
Payment Status: ' . htmlspecialchars($status) . '
</div>
<hr>';

// Fee Breakdown
$html .= '<table width="100%" cellpadding="4" style="font-size:10px;">
<tr>
    <td><b>Total School Fees</b></td>
    <td align="right"><b>' . number_format($total_school_fee, 2) . '</b></td>
</tr>
</table><hr>';

// Totals
$html .= '
<table width="100%" style="font-size:10px;">
<tr>
    <td>Amount Paid</td>
    <td align="right">' . number_format($amount_paid, 2) . '</td>
</tr>
<tr>
    <td>Balance</td>
    <td align="right">' . ($balance <= 0 ? 'Fully Paid' : number_format($balance, 2)) . '</td>
</tr>
</table>
<hr>
<div style="text-align:center;font-size:10px;">
    <em>Thank you for your payment!</em><br>
</div>';

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

// Barcode
$pdf->Ln(5);
$pdf->write1DBarcode($payment['id'], 'C128', '', '', '', 18, 0.4, array(
    'position' => 'C',
    'align' => 'C',
    'stretch' => false,
    'fitwidth' => true,
    'border' => false,
    'hpadding' => 'auto',
    'vpadding' => 'auto',
    'fgcolor' => array(0,0,0),
    'bgcolor' => false,
    'text' => true,
    'font' => 'helvetica',
    'fontsize' => 8,
    'stretchtext' => 4
), 'N');

// Auto print dialog
$pdf->IncludeJS("print(true);");

ob_end_clean();
$pdf->Output('Receipt_' . $student_name . '.pdf', 'I');
?>
