<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>إذن استلام جديد<?php $__template->endSection(); ?>

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

    <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="package-check" style="width:18px;height:18px;color:#1e3a5f;"></i>
            <h3 style="margin:0;color:#1e3a5f;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">أمر الشراء <span style="color:#DC2626;">*</span></label>
                    <select name="purchase_order_id" class="form-select" id="poSelect" required onchange="loadPOItems()">
                        <option value="">-- اختر أمر شراء --</option>
                        <?php foreach ($openPOs as $po): ?>
                        <option value="<?= (int) $po['id'] ?>"
                                data-supplier="<?= e($po['supplier_name']) ?>"
                                data-warehouse="<?= e($po['warehouse_name']) ?>">
                            <?= e($po['po_number']) ?> — <?= e($po['supplier_name']) ?> (<?= money($po['total_amount']) ?>)
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="form-label">تاريخ الاستلام</label>
                    <input type="date" name="received_date" class="form-input" value="<?= date('Y-m-d') ?>">
                </div>
            </div>
            <div style="margin-top:15px;">
                <label class="form-label">ملاحظات</label>
                <textarea name="notes" class="form-input" rows="2" placeholder="ملاحظات إضافية..."></textarea>
            </div>
        </div>
    </div>

    <div class="card" style="margin-bottom:20px;" id="itemsCard" style="display:none;">
        <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;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>
        <div class="table-responsive">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>الصنف</th>
                        <th>المطلوب</th>
                        <th>المستلم سابقاً</th>
                        <th>المتبقي</th>
                        <th style="width:120px;">الكمية المستلمة</th>
                        <th>رقم الدفعة</th>
                        <th>تاريخ الانتهاء</th>
                    </tr>
                </thead>
                <tbody id="poItemsBody">
                    <tr><td colspan="7" style="text-align:center;color:#9CA3AF;padding:30px;">اختر أمر شراء لعرض الأصناف</td></tr>
                </tbody>
            </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> إنشاء إذن الاستلام
        </button>
    </div>
</form>

<script>
var poItemsCache = {};
<?php foreach ($openPOs as $po): ?>
poItemsCache[<?= (int) $po['id'] ?>] = null;
<?php endforeach; ?>

function loadPOItems() {
    var poId = document.getElementById('poSelect').value;
    var tbody = document.getElementById('poItemsBody');
    if (!poId) {
        tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;color:#9CA3AF;padding:30px;">اختر أمر شراء لعرض الأصناف</td></tr>';
        return;
    }

    tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;color:#9CA3AF;padding:20px;">جاري التحميل...</td></tr>';

    fetch('/inventory/purchase-orders/' + poId + '?format=json')
        .then(function(r) { return r.json(); })
        .catch(function() {
            // Fallback: reload the page with PO items embedded
            // For now, use a simple approach
            return { items: [] };
        })
        .then(function(data) {
            var items = data.items || [];
            if (items.length === 0) {
                tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;color:#9CA3AF;padding:30px;">لا توجد أصناف</td></tr>';
                return;
            }
            var html = '';
            items.forEach(function(item, idx) {
                var remaining = Math.max(0, parseFloat(item.quantity_ordered) - parseFloat(item.quantity_received));
                html += '<tr>'
                    + '<td style="font-weight:600;">' + (item.item_name || '') + '</td>'
                    + '<td style="direction:ltr;text-align:left;">' + parseFloat(item.quantity_ordered).toFixed(3) + '</td>'
                    + '<td style="direction:ltr;text-align:left;">' + parseFloat(item.quantity_received).toFixed(3) + '</td>'
                    + '<td style="direction:ltr;text-align:left;font-weight:600;">' + remaining.toFixed(3) + '</td>'
                    + '<td><input type="hidden" name="items['+idx+'][po_item_id]" value="'+item.id+'">'
                    + '<input type="number" name="items['+idx+'][quantity_received]" class="form-input" step="0.001" min="0" max="'+remaining.toFixed(3)+'" value="'+remaining.toFixed(3)+'"></td>'
                    + '<td><input type="text" name="items['+idx+'][batch_number]" class="form-input" placeholder="اختياري"></td>'
                    + '<td><input type="date" name="items['+idx+'][expiry_date]" class="form-input"></td>'
                    + '</tr>';
            });
            tbody.innerHTML = html;
        });
}

document.addEventListener('DOMContentLoaded', function() {
    if (typeof lucide !== 'undefined') lucide.createIcons();
});
</script>
<?php $__template->endSection(); ?>
