<?php
require('session-master.php');
require('functions.php');

/* --------------------------------------------
   HARD SAFETY: NO OUTPUT BEFORE PDF
-------------------------------------------- */
ini_set('zlib.output_compression', 'Off');
while (ob_get_level()) {
    ob_end_clean();
}

/* --------------------------------------------
   SESSION & INPUT VALIDATION
-------------------------------------------- */
if (!isset($_SESSION['company_id'])) {
    	echo "
        <script>
            alert('Company context missing. Please re-login.');
            window.location.href = 'sign-in.php';
        </script>
        ";
        exit;
}

$company_id = (int) $_SESSION['company_id'];

if (empty($_GET['id'])) {
        echo "
    <script>
        alert('Invalid ID');
        window.location.href = 'expense-download.php';
    </script>
    ";
    exit;
}

$expense_id = (int) $_GET['id'];

/* --------------------------------------------
   DB CONNECTION
-------------------------------------------- */
$mysqli = new mysqli(
    DATABASE_HOST,
    DATABASE_USER,
    DATABASE_PASS,
    DATABASE_NAME
);

if ($mysqli->connect_error) {
    die('Database error');
}

/* --------------------------------------------
   FETCH EXPENSE (COMPANY SCOPED)
-------------------------------------------- */
$stmt = $mysqli->prepare("
    SELECT *
    FROM expenses
    WHERE id = ?
      AND company_id = ?
    LIMIT 1
");
$stmt->bind_param("ii", $expense_id, $company_id);
$stmt->execute();
$expense = $stmt->get_result()->fetch_assoc();

if (!$expense) {

        echo "
    <script>
        alert('Not found or Access DENIED.');
        window.location.href = 'expense-download.php';
    </script>
    ";
    exit;
}

/* --------------------------------------------
   FETCH COMPANY
-------------------------------------------- */
$stmt = $mysqli->prepare("
    SELECT *
    FROM company
    WHERE id = ?
    LIMIT 1
");
$stmt->bind_param("i", $company_id);
$stmt->execute();
$company = $stmt->get_result()->fetch_assoc();

/* --------------------------------------------
   LOAD LOGO (ABSOLUTE PATH, BASE64)
-------------------------------------------- */
$base64_logo = '';
if (!empty($company['company_logo'])) {
    $logo_path = __DIR__ . '/images/' . $company['company_logo'];
    if (file_exists($logo_path)) {
        $type = pathinfo($logo_path, PATHINFO_EXTENSION);
        $data = file_get_contents($logo_path);
        $base64_logo = 'data:image/' . $type . ';base64,' . base64_encode($data);
    }
}

$mysqli->close();

/* --------------------------------------------
   BUILD HTML
-------------------------------------------- */
ob_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Expense <?= htmlspecialchars($expense['expense_id']) ?></title>

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

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

.header h1 {
    margin: 0;
}

.info-box {
    border: 1px solid #eee;
    margin-top: 20px;
}

.info-box td {
    padding: 10px;
    border-bottom: 1px solid #eee;
}

.info-box tr:last-child td {
    border-bottom: none;
}

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

.label1 {
    font-weight: bold;
    width: 100%;
}

.amount-box {
    margin-top: 20px;
    background: #000;
    color: #fff;
}

.amount-box td {
    padding: 12px;
    font-size: 14px;
    font-weight: bold;
}

.footer-box {
    margin-top: 30px;
    border: 1px solid #eee;
}

.footer-box1 {
    margin-top: 30px;
    margin-bottom: 15px;
    border: 1px solid #eee;
}

.footer-box td {
    padding: 20px;
    text-align: center;
}

.footer-box1 td {
    padding: 20px 0 20px 5px;
    text-align: left;
    font-size: 15px;
}

.footer-title {
    font-weight: bold;
    display: block;
    margin-bottom: 15px;
}
</style>
</head>

<body>

<!-- HEADER -->
<table class="header">
<tr>
<td width="50%">
<?php if ($base64_logo): ?>
<img src="<?= $base64_logo ?>" width="180">
<?php endif; ?>
</td>
<td width="50%" align="right">
<h1>EXPENSE VOUCHER</h1>
</td>
</tr>
</table>

<br>

<table class="footer-box1">
<tr>
<td class="label1">
Created By: <?= htmlspecialchars($expense['created_by']) ?>
</td>
<td></td>
</tr>
</table>

<br>

<!-- EXPENSE DETAILS -->
<table class="info-box">
<tr>
<td class="label">Transaction ID</td>
<td><?= htmlspecialchars($expense['expense_id']) ?></td>
</tr>
<tr>
<td class="label">Reference No</td>
<td><?= htmlspecialchars($expense['reference_no']) ?></td>
</tr>
<tr>
<td class="label">Transaction Date</td>
<td><?= date('d M Y', strtotime($expense['expense_date'])) ?></td>
</tr>
<tr>
<td class="label">Transaction Type</td>
<td><?= ucfirst(htmlspecialchars($expense['transaction_type'])) ?></td>
</tr>
<tr>
<td class="label">Transaction Mode</td>
<td><?= ucfirst(htmlspecialchars($expense['transaction_mode'])) ?></td>
</tr>
<tr>
<td class="label">Status</td>
<td><?= ucfirst(htmlspecialchars($expense['transaction_status'])) ?></td>
</tr>
<tr>
<td class="label">Description</td>
<td><?= nl2br(htmlspecialchars($expense['expense_desc'])) ?></td>
</tr>
<tr class="amount-box">
<td class="label">Amount</td>
<td><?= htmlspecialchars($company['currency']) . number_format($expense['expense_amount'], 2) ?></td>
</tr>
</table>

<!-- SIGNATURES -->
<table class="footer-box">
<tr>
<td width="50%">
<span class="footer-title">Authorised By</span>
<?= htmlspecialchars($expense['authorised_by']) ?>
</td>

<td width="50%">
<span class="footer-title">Authorised By</span>
<?= htmlspecialchars($expense['authorised_by2']) ?>
</td>
</tr>
</table>

</body>
</html>
<?php
$html = ob_get_clean();

/* --------------------------------------------
   DOMPDF (STRICT & SAFE)
-------------------------------------------- */
require './PDFvendor/autoload.php';

use Dompdf\Dompdf;
use Dompdf\Options;

$options = new Options();
$options->set('isRemoteEnabled', true);
$options->set('isHtml5ParserEnabled', true);
$options->set('isPhpEnabled', false);
$options->set('defaultFont', 'DejaVu Sans');

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

/* BINARY SAFE OUTPUT */
header('Content-Type: application/pdf');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');

$dompdf->stream(
    "Expense-{$expense['expense_id']}.pdf",
    ["Attachment" => false]
);

exit;
