<?php
$statusBadge = ['ORDERED' => 'badge-blue', 'PARTIALLY_RECEIVED' => 'badge-gold', 'RECEIVED' => 'badge-green', 'CANCELLED' => 'badge-red'];
$rangeLabel = ($dateFrom && $dateTo) ? date('d M Y', strtotime($dateFrom)) . ' – ' . date('d M Y', strtotime($dateTo)) : 'All time';
?>
<div class="stock-header" style="background: linear-gradient(120deg, #4C3FB0 0%, #2E2470 100%);">
    <div class="sth-icon"><i class="fa-solid fa-cart-shopping"></i></div>
    <div class="sth-text">
        <h2>Purchases</h2>
        <div class="sth-sub">
            <?= e($rangeLabel) ?> · <?= (int) $summary['order_count'] ?> orders · Total: <?= formatMoney((float) $summary['total_purchased']) ?>
        </div>
    </div>
    <div class="sth-actions">
        <?php if (Auth::can('purchasing', 'add')): ?>
        <button type="button" class="btn sth-btn" onclick="rmsOpenModal('rmsCreatePoModal')"><i class="fa-solid fa-plus"></i> New Purchase</button>
        <?php endif; ?>
        <button type="button" class="btn sth-btn" onclick="window.print()"><i class="fa-solid fa-print"></i> Print</button>
    </div>
</div>

<div class="stat-mini-grid">
    <div class="stat-mini sm-blue"><div class="sm-value"><?= formatMoney((float) $summary['total_purchased']) ?></div><div class="sm-label">Total Purchased (<?= (int) $summary['order_count'] ?>)</div></div>
    <div class="stat-mini sm-green"><div class="sm-value"><?= formatMoney((float) $summary['total_paid']) ?></div><div class="sm-label">Paid to Suppliers</div></div>
    <div class="stat-mini sm-red"><div class="sm-value"><?= formatMoney((float) $summary['total_purchased'] - (float) $summary['total_paid']) ?></div><div class="sm-label">Outstanding Balance</div></div>
    <div class="stat-mini sm-gold"><div class="sm-value"><?= $paymentRate ?>%</div><div class="sm-label">Payment Rate</div></div>
</div>

<form method="GET" action="<?= Router::url('purchasing') ?>" class="filter-bar">
    <input type="hidden" name="status" value="<?= e($activeStatus) ?>">
    <input type="date" name="date_from" class="form-control" style="width:auto;" value="<?= e($dateFrom) ?>">
    <span style="color:var(--color-text-muted);font-size:12px;">to</span>
    <input type="date" name="date_to" class="form-control" style="width:auto;" value="<?= e($dateTo) ?>">
    <div class="fb-search" style="flex:1;min-width:160px;"><i class="fa-solid fa-magnifying-glass"></i><input type="text" name="search" placeholder="Invoice no, supplier..." value="<?= e($search) ?>"></div>
    <select name="status" class="form-control" style="width:auto;" onchange="this.form.submit()">
        <?php foreach (['ALL' => 'All Status', 'ORDERED' => 'Ordered', 'PARTIALLY_RECEIVED' => 'Partially Received', 'RECEIVED' => 'Received', 'CANCELLED' => 'Cancelled'] as $key => $label): ?>
        <option value="<?= $key ?>" <?= $activeStatus === $key ? 'selected' : '' ?>><?= e($label) ?></option>
        <?php endforeach; ?>
    </select>
    <button type="submit" class="btn btn-secondary"><i class="fa-solid fa-filter"></i> Filter</button>
    <a href="<?= Router::url('purchasing') ?>" class="btn btn-secondary"><i class="fa-solid fa-xmark"></i></a>
</form>
<div style="display:flex;gap:6px;margin-bottom:16px;flex-wrap:wrap;">
    <a href="<?= Router::url('purchasing?date_from=' . date('Y-m-d') . '&date_to=' . date('Y-m-d')) ?>" class="btn <?= $dateFrom === date('Y-m-d') && $dateTo === date('Y-m-d') ? 'btn-primary' : 'btn-secondary' ?>" style="padding:6px 14px;font-size:12px;">Today</a>
    <a href="<?= Router::url('purchasing?date_from=' . date('Y-m-d', strtotime('monday this week')) . '&date_to=' . date('Y-m-d')) ?>" class="btn btn-secondary" style="padding:6px 14px;font-size:12px;">This Week</a>
    <a href="<?= Router::url('purchasing?date_from=' . date('Y-m-01') . '&date_to=' . date('Y-m-d')) ?>" class="btn btn-secondary" style="padding:6px 14px;font-size:12px;">This Month</a>
    <a href="<?= Router::url('purchasing?date_from=' . date('Y-m-01', strtotime('first day of last month')) . '&date_to=' . date('Y-m-t', strtotime('last day of last month'))) ?>" class="btn btn-secondary" style="padding:6px 14px;font-size:12px;">Last Month</a>
</div>

<div class="dark-table-panel">
    <div class="dtp-head">
        <span><i class="fa-solid fa-table-list"></i> Purchase Orders</span>
        <span class="dtp-count"><?= count($orders) ?> total</span>
    </div>
    <div style="overflow-x:auto;">
    <table class="data-table">
    <thead><tr><th>#</th><th>Invoice No</th><th>Supplier</th><th>Date</th><th>Total</th><th>Paid</th><th>Balance</th><th>Pmt Status</th><th>Actions</th></tr></thead>
    <tbody>
    <?php foreach ($orders as $i => $po):
        $due = (float) $po['subtotal'] - (float) $po['paid_amount'];
        $pmtStatus = $due <= 0 ? '<span class="badge badge-green">Paid</span>' : ((float) $po['paid_amount'] > 0 ? '<span class="badge badge-gold">Partial</span>' : '<span class="badge badge-red">Unpaid</span>');
    ?>
    <tr>
        <td><?= $i + 1 ?></td>
        <td><strong><?= e($po['po_number']) ?></strong></td>
        <td><?= e($po['supplier_name']) ?></td>
        <td><?= date('d M Y', strtotime($po['order_date'])) ?></td>
        <td><?= formatMoney((float) $po['subtotal']) ?></td>
        <td><?= formatMoney((float) $po['paid_amount']) ?></td>
        <td style="color:<?= $due > 0 ? 'var(--color-danger)' : 'var(--color-success)' ?>;font-weight:700;"><?= formatMoney($due) ?></td>
        <td><?= $pmtStatus ?></td>
        <td><a href="<?= Router::url('purchasing/show?id=' . $po['id']) ?>" class="icon-btn icon-btn-teal" title="View"><i class="fa-solid fa-eye"></i></a></td>
    </tr>
    <?php endforeach; ?>
    <?php if (empty($orders)): ?>
    <tr><td colspan="9" style="text-align:center;color:var(--color-text-muted);padding:40px;"><i class="fa-solid fa-cart-shopping" style="font-size:22px;display:block;margin-bottom:8px;opacity:0.4;"></i>No purchases found.</td></tr>
    <?php endif; ?>
    </tbody>
    </table>
    </div>
</div>

<?php if (Auth::can('purchasing', 'add')): ?>
<div class="rms-modal-overlay" id="rmsCreatePoModal">
    <div class="rms-modal" style="max-width:600px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-file-invoice-dollar" style="color:var(--color-teal);margin-right:6px;"></i>New Purchase Order</h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsCreatePoModal')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="<?= Router::url('purchasing/store') ?>" id="rmsPoForm">
            <?= $csrf ?>
            <input type="hidden" name="cart_json" id="rmsPoCartJson">

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                <div class="form-group">
                    <label>Supplier</label>
                    <select name="supplier_id" class="form-control" required>
                        <option value="">— Select —</option>
                        <?php foreach ($suppliers as $s): ?>
                        <option value="<?= $s['id'] ?>"><?= e($s['supplier_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Expected Date (optional)</label>
                    <input type="date" name="expected_date" class="form-control">
                </div>
            </div>

            <label style="font-size:12.5px;font-weight:700;display:block;margin-bottom:8px;">Items</label>
            <div style="display:grid;grid-template-columns:2fr 1fr 1fr auto;gap:8px;margin-bottom:8px;">
                <select id="rmsPoMaterialSelect" class="form-control">
                    <option value="">— Select material —</option>
                    <?php foreach ($materials as $m): ?>
                    <option value="<?= $m['id'] ?>" data-name="<?= e($m['material_name']) ?>" data-unit="<?= e($m['unit']) ?>" data-cost="<?= $m['unit_cost'] ?>"><?= e($m['material_name']) ?> (<?= e($m['unit']) ?>)</option>
                    <?php endforeach; ?>
                </select>
                <input type="number" step="0.001" id="rmsPoQty" class="form-control" placeholder="Qty">
                <input type="number" step="0.01" id="rmsPoCost" class="form-control" placeholder="Unit cost">
                <button type="button" class="btn btn-secondary" onclick="rmsAddPoLine()"><i class="fa-solid fa-plus"></i></button>
            </div>

            <div id="rmsPoCartList" style="margin-bottom:10px;"></div>
            <div style="text-align:right;font-size:14px;font-weight:700;margin-bottom:16px;">Total: <span id="rmsPoTotal">Rs. 0.00</span></div>

            <div class="form-group">
                <label>Notes</label>
                <input type="text" name="notes" class="form-control" placeholder="Optional notes">
            </div>

            <button type="submit" class="btn btn-primary" style="width:100%;" id="rmsPoSubmitBtn" disabled><i class="fa-solid fa-check"></i> Create Purchase Order</button>
        </form>
    </div>
</div>
<?php endif; ?>

<script>
let rmsPoCart = [];
function rmsAddPoLine() {
    const sel = document.getElementById('rmsPoMaterialSelect');
    const qtyInput = document.getElementById('rmsPoQty');
    const costInput = document.getElementById('rmsPoCost');
    if (!sel.value || !qtyInput.value || !costInput.value) { alert('Select material, quantity, and unit cost.'); return; }

    const opt = sel.options[sel.selectedIndex];
    rmsPoCart.push({
        raw_material_id: parseInt(sel.value),
        name: opt.dataset.name,
        unit: opt.dataset.unit,
        quantity: parseFloat(qtyInput.value),
        unit_cost: parseFloat(costInput.value)
    });
    qtyInput.value = ''; costInput.value = ''; sel.value = '';
    rmsRenderPoCart();
}
function rmsRemovePoLine(index) {
    rmsPoCart.splice(index, 1);
    rmsRenderPoCart();
}
function rmsRenderPoCart() {
    const list = document.getElementById('rmsPoCartList');
    list.innerHTML = '';
    let total = 0;
    rmsPoCart.forEach((line, i) => {
        const lineTotal = line.quantity * line.unit_cost;
        total += lineTotal;
        const row = document.createElement('div');
        row.style.cssText = 'display:flex;justify-content:space-between;align-items:center;padding:6px 0;border-bottom:1px solid var(--color-border);font-size:12.5px;';
        row.innerHTML = `<span>${line.name} — ${line.quantity} ${line.unit} × Rs.${line.unit_cost.toFixed(2)}</span>
            <span style="display:flex;align-items:center;gap:8px;"><strong>Rs.${lineTotal.toFixed(2)}</strong>
            <span style="color:var(--color-danger);cursor:pointer;" onclick="rmsRemovePoLine(${i})"><i class="fa-solid fa-trash"></i></span></span>`;
        list.appendChild(row);
    });
    document.getElementById('rmsPoTotal').textContent = 'Rs. ' + total.toFixed(2);
    document.getElementById('rmsPoSubmitBtn').disabled = rmsPoCart.length === 0;
}
document.getElementById('rmsPoForm').addEventListener('submit', function (e) {
    document.getElementById('rmsPoCartJson').value = JSON.stringify(rmsPoCart);
    if (rmsPoCart.length === 0) { e.preventDefault(); alert('Add at least one item.'); }
});

// Quick Reorder deep-link from the Stock page: ?reorder_id=X&reorder_qty=Y
(function () {
    const params = new URLSearchParams(window.location.search);
    const reorderId = params.get('reorder_id');
    const reorderQty = params.get('reorder_qty');
    const supplierId = params.get('supplier_id');

    if (supplierId) {
        const supplierSel = document.querySelector('select[name="supplier_id"]');
        if (supplierSel) {
            supplierSel.value = supplierId;
            rmsOpenModal('rmsCreatePoModal');
        }
    }

    if (reorderId) {
        const sel = document.getElementById('rmsPoMaterialSelect');
        const opt = sel.querySelector('option[value="' + reorderId + '"]');
        if (opt) {
            sel.value = reorderId;
            document.getElementById('rmsPoQty').value = reorderQty || 1;
            document.getElementById('rmsPoCost').value = opt.dataset.cost || '';
            rmsOpenModal('rmsCreatePoModal');
        }
    }
})();
</script>
