<?php
require_once '../includes/auth.php';
requirePermission('purchases', 'view');
require_once '../db.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

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

$po = $conn->query("
    SELECT po.*, v.name AS vendor_name
    FROM purchase_orders po
    JOIN vendors v ON v.id = po.vendor_id
    WHERE po.id = $id AND po.company_id = $cid
")->fetch_assoc();
if (!$po) die("Purchase not found.");
?>

<div class="page-header">
    <h2><i class="fas fa-eye" style="color:var(--primary);margin-right:8px;"></i>Purchase Order</h2>
    <div style="display:flex;gap:10px;">
        <button onclick="printA4()" class="btn btn-primary">
            <i class="fas fa-file-alt"></i> Print A4
        </button>
        <button onclick="openPrintModal('purchases', <?= $id ?>, 'invoice', 'thermal')" class="btn btn-outline">
            <i class="fas fa-receipt"></i> Print Thermal
        </button>
        <a href="index.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
    </div>
</div>

<!-- Screen Info Panel -->
<div class="panel" style="margin-bottom:16px;">
    <div class="panel-header"><span class="panel-title">Order Information</span></div>
    <div class="panel-body">
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:16px;">
            <?php foreach ([
                'PO Number'       => $po['po_no'],
                'Date'            => date('d-m-Y', strtotime($po['purchase_date'])),
                'Vendor'          => $po['vendor_name'],
                'Supplier Invoice'=> $po['supplier_invoice_no'] ?: '—',
            ] as $k => $v): ?>
            <div>
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:4px;"><?= $k ?></div>
                <div style="font-size:14px;font-weight:600;"><?= htmlspecialchars($v) ?></div>
            </div>
            <?php endforeach; ?>
            <div>
                <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:4px;">Status</div>
                <span class="badge <?= $po['status'] === 'final' ? 'badge-success' : 'badge-warning' ?>"><?= ucfirst($po['status']) ?></span>
            </div>
        </div>
    </div>
</div>

<!-- A4 Preview Panel -->
<div class="panel" style="margin-bottom:16px;">
    <div class="panel-header">
        <span class="panel-title">Print Preview (A4)</span>
    </div>
    <div class="panel-body" style="padding:0;background:#e5e7eb;display:flex;justify-content:center;padding:20px;">
        <div id="poPreview" style="background:#fff;box-shadow:0 2px 16px rgba(0,0,0,.15);min-height:200px;display:flex;align-items:center;justify-content:center;">
            <span style="color:#94a3b8;font-size:13px;"><i class="fas fa-spinner fa-spin" style="margin-right:6px;"></i> Loading preview...</span>
        </div>
    </div>
</div>

<link rel="stylesheet" id="poTemplateStyle">
<script>
const poId = <?= $id ?>;

function loadA4Preview() {
    fetch(`layout_loader.php?id=${poId}`)
        .then(r => r.text())
        .then(html => {
            document.getElementById('poPreview').innerHTML = html;
            setTimeout(() => {
                const barcodeEl = document.getElementById('poPreview').querySelector('#barcode');
                if (barcodeEl && typeof JsBarcode !== 'undefined') {
                    JsBarcode(barcodeEl, barcodeEl.dataset.invoice, {
                        format:'CODE128', width:1.2, height:40, displayValue:false, margin:0
                    });
                }
            }, 100);
        })
        .catch(() => {
            document.getElementById('poPreview').innerHTML = '<div style="padding:20px;color:var(--danger);">Failed to load preview.</div>';
        });
}

function printA4() {
    const content = document.getElementById('poPreview').innerHTML;
    const w = window.open('', '_blank');
    w.document.write('<!DOCTYPE html><html><head><meta charset="utf-8"><title>Purchase Order</title></head><body style="margin:0;padding:0;">' + content + '</body></html>');
    w.document.close();
    w.focus();
    setTimeout(() => { w.print(); }, 400);
}

loadA4Preview();
</script>


<?php require_once '../includes/footer.php'; ?>
