<?php
require_once __DIR__ . '/../../../core/auth.php';
require_login();
require_once __DIR__ . '/../../../libs/dompdf/vendor/autoload.php';

use Dompdf\Dompdf;
use Dompdf\Options;

$options = new Options();
$options->set('isHtml5ParserEnabled', true);
$options->set('isRemoteEnabled', true);
// خط يدعم العربي (جاهز مع Dompdf)
$options->set('defaultFont', 'DejaVu Sans');

$dompdf = new Dompdf($options);

$pdo = db();
$id = (int)($_GET['id'] ?? 0);

// رأس الفاتورة
$head = $pdo->prepare("
    SELECT r.*, b.TaxRate, br.BranchName
    FROM SalesReceipt r
    JOIN BranchSettings b ON b.BranchID = r.BranchID
    JOIN Branches br ON br.BranchID = r.BranchID
    WHERE r.ReceiptID = ?
");
$head->execute([$id]);
$h = $head->fetch();
if (!$h) exit('فاتورة غير موجودة');

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

// HTML
ob_start();
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8">
  <style>
    body { font-family: 'DejaVu Sans', sans-serif; direction: rtl; text-align: right; }
    h2, p { margin: 0; padding: 0; }
    table { width: 100%; border-collapse: collapse; margin-top: 15px; }
    th, td { border: 1px solid #000; padding: 6px; text-align: center; }
    th { background: #f0f0f0; }
  </style>
</head>
<body>
  <h2>فاتورة رقم #<?= $id ?></h2>
  <p>الفرع: <?= htmlspecialchars($h['BranchName']) ?></p>
  <p>الإجمالي: <?= number_format($h['Total'], 2) ?> جنيه</p>
  
  <table>
    <thead>
      <tr>
        <th>الصنف</th>
        <th>الكمية</th>
        <th>السعر</th>
        <th>القيمة</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($rows as $it): ?>
      <tr>
        <td><?= htmlspecialchars($it['ItemName']) ?></td>
        <td><?= $it['Qty'] ?></td>
        <td><?= number_format($it['Price'], 2) ?></td>
        <td><?= number_format($it['Value'], 2) ?></td>
      </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</body>
</html>
<?php
$html = ob_get_clean();

$dompdf->loadHtml($html, 'UTF-8');
$dompdf->setPaper('A5', 'portrait');
$dompdf->render();
$dompdf->stream("receipt-{$id}.pdf", ["Attachment" => false]);
