<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>إنشاء أمر شراء جديد<?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<a href="/inventory/purchase-orders" class="btn btn-outline"><i data-lucide="arrow-right" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> العودة للقائمة</a>
<?php $__template->endSection(); ?>

<?php $__template->section('content'); ?>

<form method="POST" action="/inventory/purchase-orders" id="poForm">
    <?= csrf_field() ?>

    <!-- Header Information -->
    <div class="card" style="margin-bottom:20px;">
        <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;gap:8px;">
            <i data-lucide="file-text" style="width:18px;height:18px;color:#0D7377;"></i>
            <h3 style="margin:0;color:#0D7377;font-size:15px;">بيانات أمر الشراء</h3>
        </div>
        <div style="padding:20px;">
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:20px;">
                <div class="form-group">
                    <label class="form-label">المورد <span style="color:#DC2626;">*</span></label>
                    <select name="supplier_id" class="form-select" required>
                        <option value="">-- اختر المورد --</option>
                        <?php foreach ($suppliers as $sup): ?>
                        <option value="<?= (int) $sup['id'] ?>" <?= (int) old('supplier_id', '') === (int) $sup['id'] && old('supplier_id', '') !== '' ? 'selected' : '' ?>><?= e($sup['name_ar']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">المستودع <span style="color:#DC2626;">*</span></label>
                    <select name="warehouse_id" class="form-select" required>
                        <option value="">-- اختر المستودع --</option>
                        <?php foreach ($warehouses as $wh): ?>
                        <option value="<?= (int) $wh['id'] ?>" <?= (int) old('warehouse_id', '') === (int) $wh['id'] && old('warehouse_id', '') !== '' ? 'selected' : '' ?>><?= e($wh['name_ar']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">تاريخ التسليم المتوقع</label>
                    <input type="date" name="expected_delivery_date" value="<?= e(old('expected_delivery_date', '')) ?>" class="form-input">
                </div>
            </div>
            <div class="form-group" style="margin-top:15px;">
                <label class="form-label">ملاحظات</label>
                <textarea name="notes" class="form-input" rows="2" placeholder="ملاحظات إضافية عن أمر الشراء..."><?= e(old('notes', '')) ?></textarea>
            </div>
        </div>
    </div>

    <!-- Items Table -->
    <div class="card" style="margin-bottom:20px;">
        <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;justify-content:space-between;">
            <div style="display:flex;align-items:center;gap:8px;">
                <i data-lucide="package" style="width:18px;height:18px;color:#D97706;"></i>
                <h3 style="margin:0;color:#D97706;font-size:15px;">الأصناف</h3>
            </div>
            <button type="button" id="addItemBtn" class="btn btn-sm" style="background:#0D7377;color:#fff;border:none;font-size:12px;padding:6px 14px;">
                <i data-lucide="plus" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> إضافة صنف
            </button>
        </div>
        <div class="table-responsive">
            <table class="data-table" id="itemsTable">
                <thead>
                    <tr>
                        <th style="min-width:250px;">الصنف <span style="color:#DC2626;">*</span></th>
                        <th style="min-width:120px;">الكمية <span style="color:#DC2626;">*</span></th>
                        <th style="min-width:140px;">سعر الوحدة <span style="color:#DC2626;">*</span></th>
                        <th style="min-width:140px;">الإجمالي</th>
                        <th style="width:60px;"></th>
                    </tr>
                </thead>
                <tbody id="itemsBody">
                    <!-- Rows added by JS -->
                </tbody>
                <tfoot>
                    <tr style="background:#F9FAFB;">
                        <td colspan="3" style="text-align:left;font-weight:700;font-size:15px;padding:12px 15px;">الإجمالي الكلي</td>
                        <td style="font-weight:800;font-size:16px;color:#0D7377;direction:ltr;text-align:left;padding:12px 15px;" id="grandTotal">0.00</td>
                        <td></td>
                    </tr>
                </tfoot>
            </table>
        </div>
        <div id="noItemsMsg" style="padding:40px 20px;text-align:center;color:#9CA3AF;font-size:14px;">
            <i data-lucide="package-open" style="width:36px;height:36px;color:#D1D5DB;margin-bottom:10px;"></i>
            <div>اضغط "إضافة صنف" لإضافة أصناف لأمر الشراء</div>
        </div>
    </div>

    <!-- Submit Buttons -->
    <div style="display:flex;gap:10px;justify-content:flex-start;">
        <button type="submit" class="btn btn-primary" style="padding:12px 30px;font-size:15px;">
            <i data-lucide="check" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i>
            إنشاء أمر الشراء
        </button>
        <a href="/inventory/purchase-orders" class="btn btn-outline" style="padding:12px 30px;font-size:15px;">إلغاء</a>
    </div>
</form>

<script>
document.addEventListener('DOMContentLoaded', function() {
    if (typeof lucide !== 'undefined') {
        lucide.createIcons();
    }

    var items = <?= json_encode($items, JSON_UNESCAPED_UNICODE) ?>;
    var rowIndex = 0;
    var tbody = document.getElementById('itemsBody');
    var noItemsMsg = document.getElementById('noItemsMsg');
    var grandTotalEl = document.getElementById('grandTotal');

    function buildItemOptions() {
        var html = '<option value="">-- اختر الصنف --</option>';
        for (var i = 0; i < items.length; i++) {
            html += '<option value="' + items[i].id + '" data-cost="' + (items[i].cost_price || 0) + '">'
                + items[i].name_ar + (items[i].sku ? ' (' + items[i].sku + ')' : '') + '</option>';
        }
        return html;
    }

    function addRow() {
        var idx = rowIndex++;
        var tr = document.createElement('tr');
        tr.setAttribute('data-row', idx);
        tr.innerHTML = '<td>'
            + '<select name="items[' + idx + '][item_id]" class="form-select item-select" required style="width:100%;">'
            + buildItemOptions()
            + '</select></td>'
            + '<td><input type="number" name="items[' + idx + '][quantity_ordered]" class="form-input item-qty" min="1" step="1" value="1" required style="direction:ltr;text-align:left;"></td>'
            + '<td><input type="number" name="items[' + idx + '][unit_price]" class="form-input item-price" min="0" step="0.01" value="0.00" required style="direction:ltr;text-align:left;"></td>'
            + '<td class="row-total" style="font-weight:700;direction:ltr;text-align:left;padding:10px 15px;">0.00</td>'
            + '<td style="text-align:center;">'
            + '<button type="button" class="btn btn-sm remove-row" style="background:#FEE2E2;color:#DC2626;border:none;padding:6px 10px;">'
            + '<i data-lucide="trash-2" style="width:14px;height:14px;vertical-align:middle;"></i></button></td>';

        tbody.appendChild(tr);
        updateVisibility();

        // Auto-fill cost price on item select
        var select = tr.querySelector('.item-select');
        var priceInput = tr.querySelector('.item-price');
        select.addEventListener('change', function() {
            var opt = this.options[this.selectedIndex];
            var cost = opt.getAttribute('data-cost') || 0;
            priceInput.value = parseFloat(cost).toFixed(2);
            calcRowTotal(tr);
        });

        tr.querySelector('.item-qty').addEventListener('input', function() { calcRowTotal(tr); });
        priceInput.addEventListener('input', function() { calcRowTotal(tr); });
        tr.querySelector('.remove-row').addEventListener('click', function() {
            tr.remove();
            calcGrandTotal();
            updateVisibility();
        });

        if (typeof lucide !== 'undefined') {
            lucide.createIcons();
        }
    }

    function calcRowTotal(tr) {
        var qty = parseFloat(tr.querySelector('.item-qty').value) || 0;
        var price = parseFloat(tr.querySelector('.item-price').value) || 0;
        var total = qty * price;
        tr.querySelector('.row-total').textContent = total.toFixed(2);
        calcGrandTotal();
    }

    function calcGrandTotal() {
        var totals = document.querySelectorAll('.row-total');
        var sum = 0;
        totals.forEach(function(el) {
            sum += parseFloat(el.textContent) || 0;
        });
        grandTotalEl.textContent = sum.toFixed(2);
    }

    function updateVisibility() {
        var hasRows = tbody.querySelectorAll('tr').length > 0;
        noItemsMsg.style.display = hasRows ? 'none' : 'block';
    }

    document.getElementById('addItemBtn').addEventListener('click', addRow);

    // Start with one row
    addRow();
});
</script>
<?php $__template->endSection(); ?>
