<div class="stock-header" style="background: linear-gradient(120deg, #B0651E 0%, #7A3F0F 100%);">
    <div class="sth-icon"><i class="fa-solid fa-kitchen-set"></i></div>
    <div class="sth-text">
        <h2>Daily Kitchen Issuance</h2>
        <div class="sth-sub">
            <?= (int) $stats['today_count'] ?> issues today · <?= number_format((float) $stats['today_qty'], 1) ?> units issued · Est. value <?= formatMoney((float) $stats['today_value']) ?>
        </div>
    </div>
    <div class="sth-actions">
        <?php if (Auth::can('stock', 'edit')): ?>
        <button type="button" class="btn sth-btn" onclick="rmsOpenModal('rmsIssueModal')"><i class="fa-solid fa-plus"></i> New Kitchen Issue</button>
        <?php if ($lastIssue): ?>
        <button type="button" class="btn sth-btn" onclick="rmsRepeatLastIssue()"><i class="fa-solid fa-clock-rotate-left"></i> Repeat Last Issue</button>
        <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

<div class="stat-mini-grid">
    <div class="stat-mini sm-blue"><div class="sm-value"><?= (int) $stats['today_count'] ?></div><div class="sm-label">Issues Today</div></div>
    <div class="stat-mini sm-gold"><div class="sm-value"><?= number_format((float) $stats['today_qty'], 1) ?></div><div class="sm-label">Units Issued Today</div></div>
    <div class="stat-mini sm-green"><div class="sm-value"><?= formatMoney((float) $stats['today_value']) ?></div><div class="sm-label">Est. Value Today</div></div>
    <div class="stat-mini sm-blue"><div class="sm-value"><?= (int) $stats['week_count'] ?></div><div class="sm-label">Issues This Week</div></div>
</div>

<div class="quick-actions">
    <a href="<?= Router::url('stock') ?>" class="qa-btn"><i class="fa-solid fa-boxes-stacked"></i> Stock Management</a>
    <a href="<?= Router::url('purchasing') ?>" class="qa-btn"><i class="fa-solid fa-file-invoice-dollar"></i> Purchasing</a>
    <a href="<?= Router::url('reports?tab=stock') ?>" class="qa-btn"><i class="fa-solid fa-chart-line"></i> Stock Report</a>
</div>

<div class="dark-table-panel">
    <div class="dtp-head">
        <span><i class="fa-solid fa-kitchen-set"></i> Issuance Log</span>
        <span class="dtp-count"><?= count($issues) ?> records</span>
    </div>
    <div style="overflow-x:auto;">
    <table class="data-table">
    <thead><tr><th>#</th><th>Date</th><th>Items</th><th>Est. Value</th><th>Notes</th><th>Issued By</th><th></th></tr></thead>
    <tbody>
    <?php foreach ($issues as $i => $iss): ?>
    <tr>
        <td><?= $i + 1 ?></td>
        <td><?= date('d M Y, h:i A', strtotime($iss['created_at'])) ?></td>
        <td><span class="badge badge-blue"><?= (int) $iss['item_count'] ?> items</span></td>
        <td><?= formatMoney((float) $iss['est_value']) ?></td>
        <td><?= e($iss['notes'] ?? '—') ?></td>
        <td><?= e($iss['created_by_name'] ?? 'System') ?></td>
        <td>
            <button type="button" class="icon-btn icon-btn-teal" onclick="rmsOpenModal('rmsViewIssue<?= $iss['id'] ?>')" title="View"><i class="fa-solid fa-eye"></i></button>
            <?php if (Auth::can('stock', 'edit')): ?>
            <button type="button" class="icon-btn icon-btn-gold" onclick="rmsOpenEditIssue(<?= $iss['id'] ?>)" title="Edit"><i class="fa-solid fa-pen"></i></button>
            <?php endif; ?>
        </td>
    </tr>
    <?php endforeach; ?>
    <?php if (empty($issues)): ?>
    <tr><td colspan="7" style="text-align:center;color:var(--color-text-muted);padding:30px;">No kitchen issues logged yet.</td></tr>
    <?php endif; ?>
    </tbody>
    </table>
    </div>
</div>

<?php if (Auth::can('stock', 'edit')): ?>
<div class="rms-modal-overlay" id="rmsIssueModal">
    <div class="rms-modal" style="max-width:560px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-kitchen-set" style="color:var(--color-teal);margin-right:6px;"></i>New Kitchen Issue</h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsIssueModal')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="<?= Router::url('kitchen-issue/store') ?>" id="rmsIssueForm">
            <?= $csrf ?>
            <input type="hidden" name="cart_json" id="rmsIssueCartJson">

            <div style="display:grid;grid-template-columns:2fr 1fr auto;gap:8px;margin-bottom:8px;">
                <select id="rmsIssueMaterialSelect" 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-stock="<?= $m['current_stock'] ?>"><?= e($m['material_name']) ?> (<?= number_format((float)$m['current_stock'],2) ?> <?= e($m['unit']) ?> in stock)</option>
                    <?php endforeach; ?>
                </select>
                <input type="number" step="0.001" id="rmsIssueQty" class="form-control" placeholder="Qty">
                <button type="button" class="btn btn-secondary" onclick="rmsAddIssueLine()"><i class="fa-solid fa-plus"></i></button>
            </div>

            <div id="rmsIssueCartList" style="margin-bottom:14px;"></div>
            <div id="rmsYieldPreview" style="display:none;background:var(--color-bg);border-radius:8px;padding:12px 14px;margin-bottom:14px;">
                <div style="font-size:11px;text-transform:uppercase;letter-spacing:0.05em;color:var(--color-accent);font-weight:700;margin-bottom:6px;">
                    <i class="fa-solid fa-calculator"></i> Estimated Output
                </div>
                <div id="rmsYieldList"></div>
            </div>

            <div class="form-group">
                <label>Notes</label>
                <input type="text" name="notes" id="rmsIssueNotes" class="form-control" placeholder="e.g. Morning prep for lunch service">
            </div>

            <button type="submit" class="btn btn-primary" style="width:100%;" id="rmsIssueSubmitBtn" disabled><i class="fa-solid fa-check"></i> Issue to Kitchen</button>
        </form>
    </div>
</div>
<?php endif; ?>

<?php foreach ($issues as $iss): ?>
<div class="rms-modal-overlay" id="rmsViewIssue<?= $iss['id'] ?>">
    <div class="rms-modal" style="max-width:420px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-kitchen-set" style="color:var(--color-teal);margin-right:6px;"></i>Issue — <?= date('d M Y, h:i A', strtotime($iss['created_at'])) ?></h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsViewIssue<?= $iss['id'] ?>')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <?php
        $issueModel = new KitchenIssue();
        $full = $issueModel->findWithItems((int) $iss['id']);
        $yields = $issueModel->estimatedYield((int) $iss['id']);
        ?>
        <?php if ($full['notes']): ?><div style="font-size:12.5px;color:var(--color-text-muted);margin-bottom:10px;"><i class="fa-solid fa-note-sticky"></i> <?= e($full['notes']) ?></div><?php endif; ?>
        <div style="font-size:11px;text-transform:uppercase;letter-spacing:0.05em;color:var(--color-text-muted);font-weight:700;margin-bottom:6px;">Raw Materials Issued</div>
        <?php foreach ($full['items'] as $it): ?>
        <div style="display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid var(--color-border);font-size:12.5px;">
            <span><?= e($it['material_name']) ?></span>
            <strong><?= number_format((float)$it['quantity'],2) ?> <?= e($it['unit']) ?></strong>
        </div>
        <?php endforeach; ?>
        <div style="text-align:right;font-weight:700;margin-top:10px;font-size:13px;">Est. Value: <?= formatMoney((float) $iss['est_value']) ?></div>

        <?php if (!empty($yields)): ?>
        <div style="margin-top:16px;padding-top:14px;border-top:1px dashed var(--color-border);">
            <div style="font-size:11px;text-transform:uppercase;letter-spacing:0.05em;color:var(--color-accent);font-weight:700;margin-bottom:8px;">
                <i class="fa-solid fa-calculator"></i> Estimated Output (Packets Producible)
            </div>
            <?php foreach ($yields as $y): ?>
            <div style="padding:8px 0;border-bottom:1px solid var(--color-border);">
                <div style="display:flex;justify-content:space-between;font-size:12.5px;margin-bottom:6px;">
                    <strong><?= e($y['item_name']) ?></strong>
                    <strong style="color:var(--color-accent);">~<?= (int) $y['estimated_units'] ?> packets</strong>
                </div>
                <?php foreach ($y['breakdown'] as $b): $isLimiting = $b['material_name'] === $y['limiting_material']; ?>
                <div style="display:flex;justify-content:space-between;font-size:11px;color:var(--color-text-muted);padding:2px 0 2px 10px;<?= $isLimiting ? 'color:var(--color-danger);font-weight:700;' : '' ?>">
                    <span><?= $isLimiting ? '<i class="fa-solid fa-triangle-exclamation"></i> ' : '' ?><?= e($b['material_name']) ?> — <?= number_format($b['needed_per_unit'], 3) ?><?= e($b['unit']) ?>/unit</span>
                    <span>uses <?= number_format($b['issued_qty'], 2) ?><?= e($b['unit']) ?> → <?= $b['possible_units'] ?> possible</span>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endforeach; ?>
            <div style="font-size:10.5px;color:var(--color-text-muted);margin-top:8px;">
                <i class="fa-solid fa-circle" style="color:var(--color-danger);font-size:6px;"></i> Red = the ingredient that limits (bottlenecks) that dish's output.
            </div>
        </div>
        <?php else: ?>
        <div style="margin-top:14px;padding-top:12px;border-top:1px dashed var(--color-border);font-size:11px;color:var(--color-text-muted);">
            <i class="fa-solid fa-circle-info"></i> No output estimate — link a menu item's recipe (Menu → Edit Item → Track Stock) to the materials issued here to see packet estimates.
        </div>
        <?php endif; ?>
    </div>
</div>
<?php endforeach; ?>

<!-- Embedded data: issue id -> items, used by the shared Edit modal to pre-fill the cart -->
<script>
const rmsIssueItemsMap = <?php
    $issueItemsMap = [];
    $issueModelForMap = new KitchenIssue();
    foreach ($issues as $iss) {
        $fullForMap = $issueModelForMap->findWithItems((int) $iss['id']);
        $issueItemsMap[$iss['id']] = [
            'notes' => $fullForMap['notes'] ?? '',
            'items' => array_map(fn($it) => [
                'raw_material_id' => (int) $it['raw_material_id'],
                'name'            => $it['material_name'],
                'unit'            => $it['unit'],
                'quantity'        => (float) $it['quantity'],
            ], $fullForMap['items']),
        ];
    }
    echo json_encode($issueItemsMap);
?>;
</script>

<?php if (Auth::can('stock', 'edit')): ?>
<div class="rms-modal-overlay" id="rmsEditIssueModal">
    <div class="rms-modal" style="max-width:560px;">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-pen" style="color:var(--color-teal);margin-right:6px;"></i>Edit Kitchen Issue</h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsEditIssueModal')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="<?= Router::url('kitchen-issue/update') ?>" id="rmsEditIssueForm">
            <?= $csrf ?>
            <input type="hidden" name="id" id="rmsEditIssueId">
            <input type="hidden" name="cart_json" id="rmsEditIssueCartJson">

            <div style="display:grid;grid-template-columns:2fr 1fr auto;gap:8px;margin-bottom:8px;">
                <select id="rmsEditMaterialSelect" 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']) ?>"><?= e($m['material_name']) ?> (<?= e($m['unit']) ?>)</option>
                    <?php endforeach; ?>
                </select>
                <input type="number" step="0.001" id="rmsEditQty" class="form-control" placeholder="Qty">
                <button type="button" class="btn btn-secondary" onclick="rmsAddEditLine()"><i class="fa-solid fa-plus"></i></button>
            </div>

            <div id="rmsEditCartList" style="margin-bottom:14px;"></div>

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

            <div class="alert alert-success" style="font-size:11px;">
                <i class="fa-solid fa-circle-info"></i> Saving will reverse the original stock deduction and re-apply it using the updated quantities — stock levels stay accurate.
            </div>

            <button type="submit" class="btn btn-primary" style="width:100%;" id="rmsEditIssueSubmitBtn" disabled><i class="fa-solid fa-floppy-disk"></i> Save Changes</button>
        </form>
    </div>
</div>
<?php endif; ?>

<script>
let rmsIssueCart = [];
function rmsAddIssueLine() {
    const sel = document.getElementById('rmsIssueMaterialSelect');
    const qtyInput = document.getElementById('rmsIssueQty');
    if (!sel.value || !qtyInput.value) { alert('Select material and quantity.'); return; }
    const opt = sel.options[sel.selectedIndex];
    rmsIssueCart.push({ raw_material_id: parseInt(sel.value), name: opt.dataset.name, unit: opt.dataset.unit, quantity: parseFloat(qtyInput.value) });
    qtyInput.value = ''; sel.value = '';
    rmsRenderIssueCart();
}
function rmsRemoveIssueLine(index) {
    rmsIssueCart.splice(index, 1);
    rmsRenderIssueCart();
}
function rmsRenderIssueCart() {
    const list = document.getElementById('rmsIssueCartList');
    list.innerHTML = '';
    rmsIssueCart.forEach((line, i) => {
        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}</span><span style="display:flex;align-items:center;gap:8px;"><strong>${line.quantity} ${line.unit}</strong><span style="color:var(--color-danger);cursor:pointer;" onclick="rmsRemoveIssueLine(${i})"><i class="fa-solid fa-trash"></i></span></span>`;
        list.appendChild(row);
    });
    document.getElementById('rmsIssueSubmitBtn').disabled = rmsIssueCart.length === 0;
    rmsUpdateYieldPreview();
}

const rmsRecipesByItem = <?= json_encode($recipesByItem) ?>;

function rmsUpdateYieldPreview() {
    const preview = document.getElementById('rmsYieldPreview');
    const listEl = document.getElementById('rmsYieldList');
    listEl.innerHTML = '';

    if (rmsIssueCart.length === 0) {
        preview.style.display = 'none';
        return;
    }

    // Map of raw_material_id -> issued quantity
    const issuedMap = {};
    rmsIssueCart.forEach(l => { issuedMap[l.raw_material_id] = (issuedMap[l.raw_material_id] || 0) + l.quantity; });

    const results = [];
    Object.keys(rmsRecipesByItem).forEach(itemName => {
        const recipeRows = rmsRecipesByItem[itemName];
        let usesOnlyIssued = true;
        const breakdown = [];
        for (const r of recipeRows) {
            const have = issuedMap[r.raw_material_id];
            if (have === undefined || r.quantity_required <= 0) { usesOnlyIssued = false; break; }
            const possible = Math.floor(have / r.quantity_required);
            breakdown.push({ name: r.material_name, unit: r.unit, needed: r.quantity_required, issued: have, possible: possible });
        }
        if (usesOnlyIssued && breakdown.length > 0) {
            let limiting = breakdown[0];
            breakdown.forEach(b => { if (b.possible < limiting.possible) limiting = b; });
            results.push({ name: itemName, units: limiting.possible, limitingName: limiting.name, breakdown: breakdown });
        }
    });

    if (results.length === 0) {
        preview.style.display = 'none';
        return;
    }
    results.sort((a, b) => b.units - a.units);
    results.forEach(r => {
        const wrap = document.createElement('div');
        wrap.style.cssText = 'padding:6px 0;border-bottom:1px solid var(--color-border);';
        let breakdownHtml = '';
        r.breakdown.forEach(b => {
            const isLimiting = b.name === r.limitingName;
            breakdownHtml += `<div style="display:flex;justify-content:space-between;font-size:10.5px;padding:2px 0 2px 8px;${isLimiting ? 'color:var(--color-danger);font-weight:700;' : 'color:var(--color-text-muted);'}">
                <span>${isLimiting ? '⚠ ' : ''}${b.name} — ${b.needed}${b.unit}/unit</span>
                <span>${b.possible} possible</span>
            </div>`;
        });
        wrap.innerHTML = `<div style="display:flex;justify-content:space-between;font-size:12px;font-weight:700;"><span>${r.name}</span><span style="color:var(--color-accent);">~${r.units} packets</span></div>${breakdownHtml}`;
        listEl.appendChild(wrap);
    });
    preview.style.display = 'block';
}
document.getElementById('rmsIssueForm')?.addEventListener('submit', function (e) {
    document.getElementById('rmsIssueCartJson').value = JSON.stringify(rmsIssueCart);
    if (rmsIssueCart.length === 0) { e.preventDefault(); alert('Add at least one item.'); }
});

// Smart: Repeat Last Issue — pre-fills the cart with the same materials/quantities as the most recent issue
const rmsLastIssueItems = <?= $lastIssue ? json_encode(array_map(fn($it) => [
    'raw_material_id' => (int) $it['raw_material_id'],
    'name' => $it['material_name'],
    'unit' => $it['unit'],
    'quantity' => (float) $it['quantity'],
], $lastIssue['items'])) : '[]' ?>;

function rmsRepeatLastIssue() {
    rmsIssueCart = JSON.parse(JSON.stringify(rmsLastIssueItems));
    rmsRenderIssueCart();
    document.getElementById('rmsIssueNotes').value = 'Repeated from last issue';
    rmsOpenModal('rmsIssueModal');
}

// --- Edit Kitchen Issue ---
let rmsEditCart = [];

function rmsOpenEditIssue(issueId) {
    const data = rmsIssueItemsMap[issueId];
    if (!data) return;
    rmsEditCart = data.items.map(it => ({ ...it }));
    document.getElementById('rmsEditIssueId').value = issueId;
    document.getElementById('rmsEditIssueNotes').value = data.notes || '';
    rmsRenderEditCart();
    rmsOpenModal('rmsEditIssueModal');
}

function rmsAddEditLine() {
    const sel = document.getElementById('rmsEditMaterialSelect');
    const qtyInput = document.getElementById('rmsEditQty');
    if (!sel.value || !qtyInput.value) { alert('Select material and quantity.'); return; }
    const opt = sel.options[sel.selectedIndex];
    const materialId = parseInt(sel.value);
    const existing = rmsEditCart.find(l => l.raw_material_id === materialId);
    if (existing) {
        existing.quantity = parseFloat(qtyInput.value);
    } else {
        rmsEditCart.push({ raw_material_id: materialId, name: opt.dataset.name, unit: opt.dataset.unit, quantity: parseFloat(qtyInput.value) });
    }
    qtyInput.value = ''; sel.value = '';
    rmsRenderEditCart();
}

function rmsRemoveEditLine(index) {
    rmsEditCart.splice(index, 1);
    rmsRenderEditCart();
}

function rmsRenderEditCart() {
    const list = document.getElementById('rmsEditCartList');
    list.innerHTML = '';
    rmsEditCart.forEach((line, i) => {
        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}</span><span style="display:flex;align-items:center;gap:8px;"><strong>${line.quantity} ${line.unit}</strong><span style="color:var(--color-danger);cursor:pointer;" onclick="rmsRemoveEditLine(${i})"><i class="fa-solid fa-trash"></i></span></span>`;
        list.appendChild(row);
    });
    document.getElementById('rmsEditIssueSubmitBtn').disabled = rmsEditCart.length === 0;
}

document.getElementById('rmsEditIssueForm')?.addEventListener('submit', function (e) {
    document.getElementById('rmsEditIssueCartJson').value = JSON.stringify(rmsEditCart);
    if (rmsEditCart.length === 0) { e.preventDefault(); alert('Add at least one item.'); }
});
</script>
