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

if (!isset($_GET['id']) || empty($_GET['id'])) {
    die("Invalid voucher ID");
}

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

/* --------------------------------------------
   DB CONNECTION
-------------------------------------------- */
$mysqli = new mysqli(DATABASE_HOST, DATABASE_USER, DATABASE_PASS, DATABASE_NAME);
if ($mysqli->connect_error) {
    die('DB Error: ' . $mysqli->connect_error);
}

/* --------------------------------------------
   FETCH VOUCHER
-------------------------------------------- */
$stmt = $mysqli->prepare("
    SELECT *
    FROM vouchers
    WHERE voucher_id = ?
    LIMIT 1
");
$stmt->bind_param("i", $getID);
$stmt->execute();
$voucher = $stmt->get_result()->fetch_assoc();

if (!$voucher) {
       	echo "
        <script>
            alert('Voucher not found');
            window.location.href = 'voucher-list.php';
        </script>
        ";
    exit;
}

/* --------------------------------------------
   FETCH COMPANY
-------------------------------------------- */
$company = getCompanyDetails($mysqli, $_SESSION['company_id']);
    $company_name    = $company['company_name'] ?? '';
    $currency        = $company['currency'] ?? '';
    $vat_rate        = $company['vat_rate'] ?? '';
    $invoice_prefix  = $company['invoice_prefix'] ?? '';
    $company_logo    = $company['company_logo'] ?? '';
    $target          = $company['year_target'] ?? '';
    $enable_vat      = $company['enable_vat'] ?? '';
/* --------------------------------------------
   FETCH VOUCHER ITEMS
-------------------------------------------- */
$items = [];
$itemStmt = $mysqli->prepare("
    SELECT *
    FROM voucher_items
    WHERE invoice = ?
    ORDER BY item_order ASC
");
$itemStmt->bind_param("i", $getID);
$itemStmt->execute();
$res = $itemStmt->get_result();

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

$mysqli->close();

/* --------------------------------------------
   LOAD COMPANY LOGO
-------------------------------------------- */
$base64_logo = "";
if (!empty($company['company_logo'])) {
    $logoPath = "images/" . $company['company_logo'];
    if (file_exists($logoPath)) {
        $type = pathinfo($logoPath, PATHINFO_EXTENSION);
        $data = file_get_contents($logoPath);
        $base64_logo = 'data:image/' . $type . ';base64,' . base64_encode($data);
    }
}
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="icon" type="image/png" sizes="32x32" href="app-assets/favicon/inv.png">
<link rel="icon" type="image/png" sizes="16x16" href="app-assets/favicon/inv.png">
    
<title>Voucher #<?= $voucher['voucher_id'] ?></title>
<link rel="stylesheet" type="text/css" href="assets/css/styles.css">


</head>

<body>

<div class="container">
    <div class="action-bar">
    <div class="btn-group">
        <!-- BACK -->
        <button class="btn" onclick="history.back()">← Back</button>
    </div>

    <div class="btn-group">
        <!-- DOWNLOAD -->
        <a href="voucher-download.php?id=<?= $voucher['voucher_id'] ?>" 
           class="btn btn-primary" target="_blank">
           ⬇ Download
        </a>

        
    </div>
</div>


<!-- HEADER -->
<table class="header">
<tr>
    <td width="50%">
        <img src="images/<?php echo $company_logo?>" float="left" alt="" width="150px">
    </td>
    <td width="50%" align="right">
        <h1>PAYMENT VOUCHER</h1>
    </td>
</tr>
</table>

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

<!-- SUMMARY -->
<table class="summary-table">
<tr>
    <td width="60%"></td>
    <td><b>Voucher No:</b></td>
    <td><?= $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>

<!-- INFO -->
<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>

<!-- ITEMS -->
<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>
        <small><?= htmlspecialchars($item['product_description']) ?></small>
    </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>

<!-- SIGNATURE -->
<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>


</div>
<script>
function shareVoucher() {
    const url = window.location.href;
    const title = 'Payment Voucher #<?= $voucher['voucher_id'] ?>';
    const text = 'View payment voucher';

    if (navigator.share) {
        navigator.share({
            title: title,
            text: text,
            url: url
        }).catch(err => console.log(err));
    } else {
        // Fallback: copy link
        navigator.clipboard.writeText(url).then(() => {
            alert('Voucher link copied to clipboard');
        });
    }
}
</script>

</body>
</html>
