<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?><?= isset($pr) ? 'تعديل طلب شراء' : 'طلب شراء جديد' ?><?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<a href="/procurement/requisitions" 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'); ?>

<?php
$isEdit = isset($pr);
$action = $isEdit ? '/procurement/requisitions/' . (int) $pr['id'] . '/update' : '/procurement/requisitions';
?>

<form method="POST" action="<?= $action ?>" id="prForm">
    <?= csrf_field() ?>

    <!-- Header Info -->
    <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="clipboard-list" 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;gap:15px;">
                <div>
                    <label class="form-label">القسم</label>
                    <input type="text" name="department" class="form-input" value="<?= e($pr['department'] ?? '') ?>" placeholder="مثال: قسم التشغيل">
                </div>
                <div>
                    <label class="form-label">الأولوية</label>
                    <select name="urgency" class="form-select">
                        <?php foreach ($urgencies as $val => $label): ?>
                        <option value="<?= e($val) ?>" <?= ($pr['urgency'] ?? 'normal') === $val ? 'selected' : '' ?>><?= e($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="form-label">تاريخ الاحتياج</label>
                    <input type="date" name="required_date" class="form-input" value="<?= e($pr['required_date'] ?? '') ?>">
                </div>
                <div>
                    <label class="form-label">المبرر</label>
                    <input type="text" name="justification" class="form-input" value="<?= e($pr['justification'] ?? '') ?>" placeholder="سبب الطلب">
                </div>
            </div>
            <div style="margin-top:15px;">
                <label class="form-label">ملاحظات</label>
                <textarea name="notes" class="form-input" rows="2" placeholder="ملاحظات إضافية..."><?= e($pr['notes'] ?? '') ?></textarea>
            </div>
        </div>
    </div>

    <!-- Items -->
    <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" class="btn btn-sm btn-primary" onclick="addItemRow()">
                <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:200px;">الصنف</th>
                        <th>الوصف</th>
                        <th style="width:100px;">الكمية</th>
                        <th style="width:100px;">الوحدة</th>
                        <th style="width:120px;">التكلفة التقديرية</th>
                        <th style="width:120px;">الإجمالي</th>
                        <th style="width:180px;">المورد المفضل</th>
                        <th style="width:50px;"></th>
                    </tr>
                </thead>
                <tbody id="itemsBody">
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="5" style="text-align:left;font-weight:700;font-size:15px;">الإجمالي التقديري</td>
                        <td style="font-weight:800;font-size:15px;direction:ltr;text-align:left;" id="grandTotal">0.00</td>
                        <td colspan="2"></td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>

    <div style="text-align:left;">
        <button type="submit" class="btn btn-primary" style="padding:10px 30px;">
            <i data-lucide="save" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i>
            <?= $isEdit ? 'تحديث الطلب' : 'حفظ الطلب' ?>
        </button>
    </div>
</form>

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

    var inventoryItems = <?= json_encode($items ?? []) ?>;
    var suppliers = <?= json_encode($suppliers ?? []) ?>;

    window.inventoryItems = inventoryItems;
    window.suppliers = suppliers;

    <?php if ($isEdit && !empty($prItems)): ?>
    var existingItems = <?= json_encode($prItems) ?>;
    existingItems.forEach(function(item) {
        addItemRow(item);
    });
    <?php else: ?>
    addItemRow();
    <?php endif; ?>
});

var rowIndex = 0;

function addItemRow(data) {
    data = data || {};
    var idx = rowIndex++;
    var tbody = document.getElementById('itemsBody');
    var tr = document.createElement('tr');

    var itemOptions = '<option value="">-- اختر صنف --</option>';
    window.inventoryItems.forEach(function(i) {
        var sel = (data.item_id && data.item_id == i.id) ? ' selected' : '';
        itemOptions += '<option value="'+i.id+'" data-cost="'+(i.cost_price||0)+'"'+sel+'>'+i.name_ar+'</option>';
    });

    var supplierOptions = '<option value="">—</option>';
    window.suppliers.forEach(function(s) {
        var sel = (data.preferred_supplier_id && data.preferred_supplier_id == s.id) ? ' selected' : '';
        supplierOptions += '<option value="'+s.id+'"'+sel+'>'+s.name_ar+'</option>';
    });

    tr.innerHTML = ''
        + '<td><select name="items['+idx+'][item_id]" class="form-select" onchange="onItemSelect(this,'+idx+')">'+itemOptions+'</select></td>'
        + '<td><input type="text" name="items['+idx+'][description_ar]" class="form-input" value="'+(data.description_ar||'')+'" placeholder="وصف حر"></td>'
        + '<td><input type="number" name="items['+idx+'][quantity]" class="form-input" step="0.001" min="0.001" value="'+(data.quantity||'')+'" onchange="calcRow('+idx+')" required></td>'
        + '<td><input type="text" name="items['+idx+'][unit_of_measure]" class="form-input" value="'+(data.unit_of_measure||'')+'" placeholder="وحدة"></td>'
        + '<td><input type="number" name="items['+idx+'][estimated_unit_cost]" class="form-input" step="0.01" min="0" value="'+(data.estimated_unit_cost||'')+'" onchange="calcRow('+idx+')" id="cost_'+idx+'"></td>'
        + '<td style="font-weight:700;direction:ltr;text-align:left;" id="lineTotal_'+idx+'">0.00</td>'
        + '<td><select name="items['+idx+'][preferred_supplier_id]" class="form-select">'+supplierOptions+'</select></td>'
        + '<td><button type="button" onclick="this.closest(\'tr\').remove();calcGrandTotal();" style="background:none;border:none;cursor:pointer;color:#DC2626;"><i data-lucide="trash-2" style="width:16px;height:16px;"></i></button></td>';

    tbody.appendChild(tr);
    if (typeof lucide !== 'undefined') lucide.createIcons();
    calcRow(idx);
}

function onItemSelect(sel, idx) {
    var opt = sel.options[sel.selectedIndex];
    var cost = opt.getAttribute('data-cost') || '';
    document.getElementById('cost_' + idx).value = cost;
    calcRow(idx);
}

function calcRow(idx) {
    var qtyInput = document.querySelector('input[name="items['+idx+'][quantity]"]');
    var costInput = document.getElementById('cost_' + idx);
    if (!qtyInput || !costInput) return;
    var qty = parseFloat(qtyInput.value) || 0;
    var cost = parseFloat(costInput.value) || 0;
    var total = qty * cost;
    var el = document.getElementById('lineTotal_' + idx);
    if (el) el.textContent = total.toFixed(2);
    calcGrandTotal();
}

function calcGrandTotal() {
    var total = 0;
    document.querySelectorAll('[id^="lineTotal_"]').forEach(function(el) {
        total += parseFloat(el.textContent) || 0;
    });
    document.getElementById('grandTotal').textContent = total.toFixed(2);
}
</script>
<?php $__template->endSection(); ?>
