<?php $isEdit = $item !== null; ?>
<a href="<?= Router::url('menu') ?>" style="font-size:13px;color:var(--color-text-muted);"><i class="fa-solid fa-arrow-left"></i> Back to Menu</a>

<div style="display:grid;grid-template-columns:1fr 360px;gap:18px;margin-top:14px;align-items:start;">
    <div class="panel">
        <h3 style="margin-bottom:14px;"><i class="fa-solid fa-utensils" style="color:var(--color-accent);margin-right:6px;"></i><?= $isEdit ? 'Edit' : 'Add' ?> Menu Item</h3>
        <form method="POST" action="<?= Router::url($isEdit ? 'menu/items/update' : 'menu/items/store') ?>" enctype="multipart/form-data">
            <?= $csrf ?>
            <?php if ($isEdit): ?><input type="hidden" name="id" value="<?= $item['id'] ?>"><?php endif; ?>

            <div class="form-group">
                <label>Item Image (optional)</label>
                <?php if ($isEdit && !empty($item['image_path'])): ?>
                <div class="item-image-preview">
                    <img src="<?= BASE_URL ?>/<?= e($item['image_path']) ?>" alt="<?= e($item['item_name']) ?>">
                    <label class="remove-image-check">
                        <input type="checkbox" name="remove_image" value="1"> Remove current image
                    </label>
                </div>
                <?php endif; ?>
                <input type="file" name="image" class="form-control" accept="image/jpeg,image/png,image/webp">
                <div style="font-size:11px;color:var(--color-text-muted);margin-top:4px;">JPG, PNG or WEBP — max 3MB.</div>
            </div>

            <div class="form-group">
                <label>Item Name</label>
                <input type="text" name="item_name" class="form-control" value="<?= e($item['item_name'] ?? '') ?>" required>
            </div>

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                <div class="form-group">
                    <label>Category</label>
                    <select name="category_id" class="form-control" required>
                        <option value="">— Select —</option>
                        <?php foreach ($categories as $c): ?>
                        <option value="<?= $c['id'] ?>" <?= (isset($item['category_id']) && $item['category_id'] == $c['id']) ? 'selected' : '' ?>><?= e($c['category_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Base Price (Rs.)</label>
                    <input type="number" step="0.01" name="base_price" class="form-control" value="<?= e((string) ($item['base_price'] ?? '0.00')) ?>" required>
                </div>
            </div>

            <div class="form-group">
                <label>Description (optional)</label>
                <textarea name="description" class="form-control" rows="2"><?= e($item['description'] ?? '') ?></textarea>
            </div>

            <div style="display:flex;gap:24px;margin-bottom:18px;">
                <label style="display:flex;align-items:center;gap:8px;font-size:13px;font-weight:600;">
                    <input type="checkbox" name="is_available" value="1" <?= (!$isEdit || $item['is_available']) ? 'checked' : '' ?>>
                    Available on order screen
                </label>
                <label style="display:flex;align-items:center;gap:8px;font-size:13px;font-weight:600;">
                    <input type="checkbox" name="track_stock" value="1" <?= (isset($item['track_stock']) && $item['track_stock']) ? 'checked' : '' ?>>
                    <i class="fa-solid fa-box" style="color:var(--color-accent);"></i> Track raw-material stock
                </label>
            </div>

            <button type="submit" class="btn btn-primary"><i class="fa-solid fa-floppy-disk"></i> <?= $isEdit ? 'Save Changes' : 'Create Item' ?></button>
            <a href="<?= Router::url('menu') ?>" class="btn btn-secondary"><i class="fa-solid fa-xmark"></i> Cancel</a>
        </form>

        <?php if (!empty($item['track_stock']) && $isEdit): ?>
        <div class="alert alert-success" style="margin-top:16px;">
            <i class="fa-solid fa-circle-info"></i> Stock tracking is on — link this dish's ingredients in the <strong>Recipe</strong> panel on the right so stock auto-deducts on every sale.
        </div>
        <?php elseif (!empty($item['track_stock'])): ?>
        <div class="alert alert-success" style="margin-top:16px;">
            <i class="fa-solid fa-circle-info"></i> Save the item first, then come back to link its Recipe (raw materials per unit).
        </div>
        <?php endif; ?>
    </div>

    <div>
        <?php if ($isEdit): ?>
        <div class="panel">
            <h3 style="margin-bottom:12px;"><i class="fa-solid fa-list" style="color:var(--color-teal);margin-right:6px;"></i>Variants</h3>
            <div style="font-size:11.5px;color:var(--color-text-muted);margin-bottom:12px;">e.g. "Large", "2 Curries" — price adjustment adds/subtracts from the base price.</div>

            <?php foreach ($variants as $v): ?>
            <div style="display:flex;align-items:center;justify-content:space-between;padding:8px 0;border-bottom:1px solid var(--color-border);font-size:12.5px;">
                <div>
                    <?= e($v['variant_name']) ?>
                    <span style="color:var(--color-text-muted);">(<?= $v['price_adjustment'] >= 0 ? '+' : '' ?><?= formatMoney((float) $v['price_adjustment']) ?>)</span>
                </div>
                <form method="POST" action="<?= Router::url('menu/variants/delete') ?>" onsubmit="return confirm('Remove this variant?');">
                    <?= $csrf ?>
                    <input type="hidden" name="id" value="<?= $v['id'] ?>">
                    <input type="hidden" name="menu_item_id" value="<?= $item['id'] ?>">
                    <button type="submit" class="btn btn-danger" style="padding:4px 8px;font-size:11px;"><i class="fa-solid fa-trash"></i></button>
                </form>
            </div>
            <?php endforeach; ?>
            <?php if (empty($variants)): ?>
            <div style="text-align:center;color:var(--color-text-muted);font-size:12px;padding:10px 0;">No variants — item uses base price only.</div>
            <?php endif; ?>

            <form method="POST" action="<?= Router::url('menu/variants/store') ?>" style="margin-top:14px;">
                <?= $csrf ?>
                <input type="hidden" name="menu_item_id" value="<?= $item['id'] ?>">
                <div style="display:grid;grid-template-columns:1fr 100px;gap:8px;margin-bottom:8px;">
                    <input type="text" name="variant_name" class="form-control" placeholder="Variant name" required>
                    <input type="number" step="0.01" name="price_adjustment" class="form-control" placeholder="+/- Rs." required>
                </div>
                <button type="submit" class="btn btn-secondary" style="width:100%;"><i class="fa-solid fa-plus"></i> Add Variant</button>
            </form>
        </div>
        <?php else: ?>
        <div class="panel" style="text-align:center;color:var(--color-text-muted);font-size:12.5px;padding:24px 16px;">
            <i class="fa-solid fa-circle-info" style="font-size:18px;margin-bottom:8px;display:block;"></i>
            Save the item first, then come back here to add size/portion variants.
        </div>
        <?php endif; ?>

        <?php if ($isEdit && !empty($item['track_stock'])): ?>
        <div class="panel">
            <h3 style="margin-bottom:12px;"><i class="fa-solid fa-flask" style="color:var(--color-teal);margin-right:6px;"></i>Recipe</h3>
            <div style="font-size:11.5px;color:var(--color-text-muted);margin-bottom:12px;">Raw materials consumed per <strong>1 unit sold</strong> — stock auto-deducts using these ratios on every order.</div>

            <?php if (empty($materials)): ?>
            <div style="text-align:center;color:var(--color-text-muted);font-size:12px;padding:10px 0;">
                No raw materials yet. <a href="<?= Router::url('stock') ?>" style="color:var(--color-teal);">Add some in Stock Management</a> first.
            </div>
            <?php endif; ?>

            <?php foreach ($recipe as $r):
                $displayQty = (float) $r['quantity_required'];
                $displayUnit = $r['unit'];
                if ($r['unit'] === 'kg') { $displayQty *= 1000; $displayUnit = 'g'; }
                elseif ($r['unit'] === 'l') { $displayQty *= 1000; $displayUnit = 'ml'; }
            ?>
            <div style="display:flex;align-items:center;justify-content:space-between;padding:8px 0;border-bottom:1px solid var(--color-border);font-size:12.5px;">
                <div>
                    <?= e($r['material_name']) ?>
                    <span style="color:var(--color-text-muted);">— <?= number_format($displayQty, $displayUnit === $r['unit'] ? 3 : 0) ?> <?= e($displayUnit) ?> / unit</span>
                </div>
                <form method="POST" action="<?= Router::url('menu/recipe/delete') ?>" onsubmit="return confirm('Remove this ingredient from the recipe?');">
                    <?= $csrf ?>
                    <input type="hidden" name="id" value="<?= $r['id'] ?>">
                    <input type="hidden" name="menu_item_id" value="<?= $item['id'] ?>">
                    <button type="submit" class="btn btn-danger" style="padding:4px 8px;font-size:11px;"><i class="fa-solid fa-trash"></i></button>
                </form>
            </div>
            <?php endforeach; ?>
            <?php if (empty($recipe)): ?>
            <div style="text-align:center;color:var(--color-text-muted);font-size:12px;padding:10px 0;">No ingredients linked yet — stock won't deduct until you add some below.</div>
            <?php endif; ?>

            <?php if (!empty($materials)): ?>
            <form method="POST" action="<?= Router::url('menu/recipe/store') ?>" style="margin-top:14px;" id="rmsRecipeForm">
                <?= $csrf ?>
                <input type="hidden" name="menu_item_id" value="<?= $item['id'] ?>">
                <input type="hidden" name="quantity_required" id="rmsRecipeQtyHidden">
                <div style="display:grid;grid-template-columns:1.4fr 1fr;gap:8px;margin-bottom:6px;">
                    <select name="raw_material_id" id="rmsRecipeMaterialSelect" class="form-control" onchange="rmsUpdateRecipeUnitLabel()" required>
                        <option value="">— Select material —</option>
                        <?php foreach ($materials as $m): ?>
                        <option value="<?= $m['id'] ?>" data-unit="<?= e($m['unit']) ?>"><?= e($m['material_name']) ?> (<?= e($m['unit']) ?>)</option>
                        <?php endforeach; ?>
                    </select>
                    <input type="number" step="0.001" id="rmsRecipeQtyInput" class="form-control" placeholder="Qty per unit" required>
                </div>
                <div id="rmsRecipeUnitHint" style="font-size:11px;color:var(--color-text-muted);margin-bottom:10px;">Select a material to see its unit.</div>
                <button type="submit" class="btn btn-secondary" style="width:100%;"><i class="fa-solid fa-plus"></i> Add / Update Ingredient</button>
            </form>

            <script>
            function rmsUpdateRecipeUnitLabel() {
                const sel = document.getElementById('rmsRecipeMaterialSelect');
                const qtyInput = document.getElementById('rmsRecipeQtyInput');
                const hint = document.getElementById('rmsRecipeUnitHint');
                const unit = sel.options[sel.selectedIndex] ? sel.options[sel.selectedIndex].dataset.unit : '';

                if (unit === 'kg') {
                    qtyInput.placeholder = 'Qty in grams (g)';
                    hint.innerHTML = '<i class="fa-solid fa-circle-info"></i> This material is stocked in <strong>kg</strong> — enter the amount in <strong>grams</strong> here, it will convert automatically (e.g. 200 = 0.2kg).';
                } else if (unit === 'l') {
                    qtyInput.placeholder = 'Qty in millilitres (ml)';
                    hint.innerHTML = '<i class="fa-solid fa-circle-info"></i> This material is stocked in <strong>litres</strong> — enter the amount in <strong>ml</strong> here, it will convert automatically (e.g. 250 = 0.25l).';
                } else if (unit) {
                    qtyInput.placeholder = 'Qty in ' + unit;
                    hint.innerHTML = 'Enter the quantity in <strong>' + unit + '</strong> (this material\'s own unit — no conversion needed).';
                } else {
                    qtyInput.placeholder = 'Qty per unit';
                    hint.textContent = 'Select a material to see its unit.';
                }
            }

            document.getElementById('rmsRecipeForm').addEventListener('submit', function (e) {
                const sel = document.getElementById('rmsRecipeMaterialSelect');
                const unit = sel.options[sel.selectedIndex] ? sel.options[sel.selectedIndex].dataset.unit : '';
                const entered = parseFloat(document.getElementById('rmsRecipeQtyInput').value || 0);
                let converted = entered;
                if (unit === 'kg') converted = entered / 1000;   // grams -> kg
                if (unit === 'l') converted = entered / 1000;    // ml -> litres
                document.getElementById('rmsRecipeQtyHidden').value = converted;
            });
            </script>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<style>
.item-image-preview {
    display: flex; align-items: center; gap: 12px; margin-bottom: 10px;
    padding: 10px; border: 1px solid var(--color-border); border-radius: 8px; background: var(--color-bg);
}
.item-image-preview img { width: 64px; height: 64px; object-fit: cover; border-radius: 8px; flex-shrink: 0; }
.item-image-preview .remove-image-check { font-size: 12px; color: var(--color-danger); display: flex; align-items: center; gap: 6px; }
</style>