<?php
 // super-admin-guard.php
session_start();

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'super_admin') {
    die("Access denied");
}
?>

<?php
require 'includes/config.php';
require 'PDFvendor/autoload.php';

use Dompdf\Dompdf;
use Dompdf\Options;

$ref = $_GET['ref'] ?? '';
if ($ref === '') {
    die("Invalid reference");
}

/* =========================
   FETCH PAYMENT + COMPANY
========================= */
$stmt = $conn->prepare("
    SELECT 
        p.*,
        c.company_name,
        c.company_email
    FROM payments p
    JOIN company c ON c.id = p.company_id
    WHERE p.reference = ?
    LIMIT 1
");
$stmt->bind_param("s", $ref);
$stmt->execute();
$payment = $stmt->get_result()->fetch_assoc();

if (!$payment) {
    die("Receipt not found");
}

/* =========================
   BUILD HTML
========================= */
ob_start();
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Receipt <?= htmlspecialchars($payment['reference']) ?></title>

<style>
body {
    font-family: DejaVu Sans, sans-serif;
    font-size: 12px;
}

.container {
    border: 1px solid #ddd;
    padding: 20px;
}

h2 {
    margin-bottom: 20px;
}

.table {
    width: 100%;
    border-collapse: collapse;
}

.table td {
    padding: 8px;
}

.label {
    font-weight: bold;
    width: 40%;
}

.footer {
    margin-top: 30px;
    font-size: 11px;
    color: #666;
    text-align: center;
}
</style>

</head>
<body>

<div class="container">

<h2>Payment Receipt</h2>

<table class="table">
<tr>
    <td class="label">Company</td>
    <td><?= htmlspecialchars($payment['company_name']) ?></td>
</tr>
<tr>
    <td class="label">Email</td>
    <td><?= htmlspecialchars($payment['company_email']) ?></td>
</tr>
<tr>
    <td class="label">Reference</td>
    <td><?= htmlspecialchars($payment['reference']) ?></td>
</tr>
<tr>
    <td class="label">Amount</td>
    <td><?= $payment['currency'] ?> <?= number_format($payment['amount'], 2) ?></td>
</tr>
<tr>
    <td class="label">Gateway</td>
    <td><?= ucfirst($payment['gateway']) ?></td>
</tr>
<tr>
    <td class="label">Status</td>
    <td><?= ucfirst($payment['status']) ?></td>
</tr>
<tr>
    <td class="label">Paid At</td>
    <td><?= date('d M Y H:i', strtotime($payment['paid_at'])) ?></td>
</tr>
</table>

<div class="footer">
    This receipt was generated electronically by Finvoicer.<br>
    No signature required.
</div>

</div>

</body>
</html>

<?php
$html = ob_get_clean();

/* =========================
   DOMPDF RENDER
========================= */
$options = new Options();
$options->set('defaultFont', 'DejaVu Sans');
$options->set('isRemoteEnabled', true);

$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();

/* =========================
   DOWNLOAD
========================= */
$dompdf->stream(
    "Receipt-{$payment['reference']}.pdf",
    ["Attachment" => true]
);
exit;

?>