<?php
require_once __DIR__ . '/../../../core/auth.php';
require_login();
$pdo = db();

$id = (int)($_GET['id'] ?? 0);
if(!$id) exit('Invalid');

$head = $pdo->prepare("SELECT r.*, b.TaxRate FROM SalesReceipt r
  JOIN BranchSettings b ON b.BranchID=r.BranchID WHERE r.ReceiptID=?");
$head->execute([$id]);
$h = $head->fetch();
if(!$h) exit('Not found');

$det = $pdo->prepare("SELECT * FROM SalesReceiptDetails WHERE ReceiptID=?");
$det->execute([$id]);
$rows = $det->fetchAll();

header('Content-Type: text/html; charset=utf-8');
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<title>فاتورة #<?= $id ?></title>
<style>
  body{font-family:"Tajawal",sans-serif}
  table{width:100%;border-collapse:collapse}
  th,td{border:1px dashed #444;padding:6px;text-align:center}
  @media print{ .no-print{display:none} }
</style>
</head>
<body>
<h3>فاتورة تيك أواي #<?= $id ?></h3>
<table>
  <thead><tr><th>الصنف</th><th>كمية</th><th>سعر</th><th>قيمة</th></tr></thead>
  <tbody>
    <?php foreach($rows as $r): ?>
      <tr>
        <td><?= htmlspecialchars($r['ItemName'] ?: $r['ItemID']) ?></td>
        <td><?= (float)$r['Qty'] ?></td>
        <td><?= number_format($r['Price'],2) ?></td>
        <td><?= number_format($r['Value'],2) ?></td>
      </tr>
    <?php endforeach; ?>
  </tbody>
  <tfoot>
    <tr><td colspan="3">الإجمالي قبل الخصم</td><td><?= number_format($h['SubTotal'],2) ?></td></tr>
    <tr><td colspan="3">الخصم</td><td><?= number_format($h['Discount'],2) ?></td></tr>
    <tr><td colspan="3">الضريبة (<?= (float)$h['TaxRate'] ?>%)</td><td><?= number_format($h['Tax'],2) ?></td></tr>
    <tr><td colspan="3"><strong>الإجمالي</strong></td><td><strong><?= number_format($h['Total'],2) ?></strong></td></tr>
    <tr><td colspan="3">المدفوع</td><td><?= number_format($h['PaidAmount'],2) ?></td></tr>
    <tr><td colspan="3">الباقي</td><td><?= number_format($h['ChangeDue'],2) ?></td></tr>
  </tfoot>
</table>
<p class="no-print"><button onclick="window.print()">🖨️ طباعة</button></p>
</body>
</html>
