<?php
require_once '../db.php';
require_once '../includes/company.php';

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) die("Invalid Return");

$sr     = $conn->query("SELECT * FROM sales_returns WHERE id = $id")->fetch_assoc();
if (!$sr) die("Return not found");

$inv    = $conn->query("SELECT * FROM sales_invoices WHERE id = {$sr['sales_invoice_id']}")->fetch_assoc();
$client = $conn->query("SELECT * FROM clients WHERE id = {$sr['client_id']}")->fetch_assoc();
$company = getCompany($conn, $sr['company_id']);

$items = $conn->query("
    SELECT sri.*, p.name AS product_name
    FROM sales_return_items sri
    JOIN products p ON p.id = sri.product_id
    WHERE sri.sales_return_id = $id
");

ob_start();
require 'layout_thermal_return.php';
$html = ob_get_clean();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Credit Note — <?= htmlspecialchars($sr['return_no']) ?></title>
<link rel="stylesheet" href="../sales/css/print_thermal.css">
<style>
body { background: #e5e7eb; padding: 12px; }
.thermal-wrap {
    max-width: 80mm;
    margin: 0 auto;
    background: #fff;
    box-shadow: 0 2px 12px rgba(0,0,0,.18);
    padding: 4px 0;
}
@media print {
    body { background: #fff; padding: 0; }
    .thermal-wrap { box-shadow: none; max-width: none; margin: 0; padding: 0; }
    .no-print { display: none !important; }
}
</style>
</head>
<body>

<div class="no-print" style="text-align:center;margin-bottom:10px;">
    <button onclick="window.print()" style="padding:6px 20px;background:#1e3a5f;color:#fff;border:none;border-radius:5px;cursor:pointer;font-size:13px;">
        &#128438; Print
    </button>
    <button onclick="window.close()" style="padding:6px 16px;background:#6b7280;color:#fff;border:none;border-radius:5px;cursor:pointer;font-size:13px;margin-left:8px;">
        Close
    </button>
</div>

<div class="thermal-wrap">
<?= $html ?>
</div>

<script src="../assets/js/JsBarcode.all.min.js"></script>
<script>
window.onload = function() {
    var barcodeEl = document.getElementById('barcode');
    if (barcodeEl && typeof JsBarcode !== 'undefined') {
        JsBarcode(barcodeEl, barcodeEl.dataset.invoice, {
            format: 'CODE128', width: 1.2, height: 34, displayValue: false, margin: 0
        });
        barcodeEl.removeAttribute('width');
        barcodeEl.removeAttribute('height');
    }
};
</script>
</body>
</html>
