<?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. Please re-login.');
            window.location.href = 'voucher-list.php';
        </script>
        ";
    exit;
}

$voucher_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 VOUCHER (COMPANY SCOPED)
-------------------------------------------- */
$stmt = $mysqli->prepare("
    SELECT *
    FROM vouchers
    WHERE voucher_id = ?
      AND company_id = ?
    LIMIT 1
");
$stmt->bind_param("ii", $voucher_id, $company_id);
$stmt->execute();
$voucher = $stmt->get_result()->fetch_assoc();

if (!$voucher) {
       	echo "
        <script>
            alert('Voucher not found/Access Denied');
            window.location.href = 'voucher-list.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);
    }
}

/* --------------------------------------------
   FETCH VOUCHER ITEMS (COMPANY SCOPED)
-------------------------------------------- */
$items = [];

$itemStmt = $mysqli->prepare("
    SELECT *
    FROM voucher_items
    WHERE invoice = ?
      AND company_id = ?
    ORDER BY item_order ASC
");

$itemStmt->bind_param("ii", $voucher_id, $company_id);
$itemStmt->execute();
$resItems = $itemStmt->get_result();

while ($row = $resItems->fetch_assoc()) {
    $items[] = $row;
}

$mysqli->close();

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

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

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

.header h1 { margin:0; }

.summary-table td { padding:4px 6px; }

.info-box {
    border:1px solid #eee;
    margin-bottom:20px;
}
.info-box td {
    padding:12px;
    line-height:1.8;
    vertical-align:top;
}
.info-box td + td {
    border-left:1px solid #eee;
}

.info-label {
    font-weight:bold;
    display:inline-block;
    width:140px;
}

.items-table th,
.items-table td {
    padding:6px;
    border-bottom:1px solid #eee;
}
.items-table th {
    background:#f4f4f4;
    text-align:left;
}

.total-row td {
    font-weight:bold;
    background:#000;
    color:#fff;
}

.sign-box {
    margin-top:25px;
    border:1px solid #eee;
}
.sign-box td {
    padding:18px 10px;
    text-align:center;
    vertical-align:bottom;
    height:70px;
    font-size:11px;
}
.sign-box td + td {
    border-left:1px solid #eee;
}

.sign-title {
    font-weight:bold;
    display:block;
    margin-bottom:20px;
}
</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>PAYMENT VOUCHER</h1>
</td>
</tr>
</table>

<h2 style="text-align:center;">
<?= htmlspecialchars($voucher['short_title']) ?>
</h2>

<table class="summary-table">
<tr>
<td width="60%"></td>
<td><b>Voucher No:</b></td>
<td><?= htmlspecialchars($voucher['voucher_id']) ?></td>
</tr>
<tr>
<td></td>
<td><b>Date:</b></td>
<td><?= date('d M Y', strtotime($voucher['voucher_date'])) ?></td>
</tr>
</table>

<br>

<table class="info-box">
<tr>
<td width="50%">
<span class="info-label">Requested By:</span>
<?= htmlspecialchars($voucher['requested_by']) ?><br>

<span class="info-label">Department:</span>
<?= htmlspecialchars($voucher['voucher_dept']) ?><br>

<span class="info-label">Payment Mode:</span>
<?= htmlspecialchars($voucher['payment_mode']) ?>
</td>

<td width="50%">
<span class="info-label">Ben. Acc Name:</span>
<?= htmlspecialchars($voucher['ben_account_name']) ?><br>

<span class="info-label">Bank:</span>
<?= htmlspecialchars($voucher['bank']) ?><br>

<span class="info-label">Account No:</span>
<?= htmlspecialchars($voucher['ben_account_no']) ?>
</td>
</tr>
</table>

<table class="items-table">
<thead>
<tr>
<th>Description</th>
<th width="10%">Qty</th>
<th width="15%">Price</th>
<th width="15%">Subtotal</th>
</tr>
</thead>

<tbody>
<?php foreach ($items as $item): ?>
<tr>
<td>
<b><?= htmlspecialchars($item['product']) ?></b><br>
<span style="font-size:11px;">
<?= htmlspecialchars($item['product_description']) ?>
</span>
</td>
<td align="right"><?= $item['qty'] ?></td>
<td align="right"><?= number_format($item['price'], 2) ?></td>
<td align="right"><?= number_format($item['subtotal'], 2) ?></td>
</tr>
<?php endforeach; ?>
</tbody>

<tfoot>
<tr>
<td colspan="3" align="right"><b>Subtotal</b></td>
<td align="right"><?= number_format($voucher['subtotal'], 2) ?></td>
</tr>
<tr>
<td colspan="3" align="right"><b>Discount</b></td>
<td align="right"><?= number_format($voucher['discount'], 2) ?></td>
</tr>
<tr>
<td colspan="3" align="right"><b>VAT</b></td>
<td align="right"><?= number_format($voucher['vat'], 2) ?></td>
</tr>
<tr class="total-row">
<td colspan="3" align="right">TOTAL</td>
<td align="right"><?= number_format($voucher['total'], 2) ?></td>
</tr>
</tfoot>
</table>

<br>

<b>Notes</b>
<div style="font-size:11px;">
<?= nl2br(htmlspecialchars($voucher['notes'])) ?>
</div>

<br>

<table class="sign-box">
    <tr>
        <th>Prepared By</th>
        <th>Approved By</th>
        <th>Approved By</th>
        <th>Paid By</th>
    </tr>
    <tr>
        <td><?= htmlspecialchars($voucher['created_by'] ?? '') ?></td>
        <td><?= htmlspecialchars($voucher['approved_by'] ?? '') ?></td>
        <td><?= htmlspecialchars($voucher['approved_by2'] ?? '') ?></td>
        <td><?= htmlspecialchars($voucher['payment_by'] ?? '') ?></td>
    </tr>
</table>


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

/* --------------------------------------------
   DOMPDF (STRICT)
-------------------------------------------- */
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(
    "Voucher-{$voucher['voucher_id']}.pdf",
    ["Attachment" => false]
);

exit;
