<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?><?= isset($invoice) ? 'تعديل فاتورة مورد' : 'فاتورة مورد جديدة' ?><?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<a href="/procurement/invoices" 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($invoice);
$action = $isEdit ? '/procurement/invoices/' . (int) $invoice['id'] . '/update' : '/procurement/invoices';
?>

<form method="POST" action="<?= $action ?>" id="invoiceForm">
    <?= 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="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:15px;">
                <div>
                    <label class="form-label">رقم فاتورة المورد <span style="color:#DC2626;">*</span></label>
                    <input type="text" name="invoice_number" class="form-input" value="<?= e($invoice['invoice_number'] ?? '') ?>" required placeholder="رقم الفاتورة من المورد">
                </div>
                <div>
                    <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'] ?>" <?= ($invoice['supplier_id'] ?? '') == $sup['id'] ? 'selected' : '' ?>><?= e($sup['name_ar']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="form-label">أمر الشراء</label>
                    <select name="purchase_order_id" class="form-select">
                        <option value="">— بدون —</option>
                        <?php foreach ($approvedPOs as $po): ?>
                        <option value="<?= (int) $po['id'] ?>" <?= ($invoice['purchase_order_id'] ?? '') == $po['id'] ? 'selected' : '' ?>><?= e($po['po_number']) ?> — <?= e($po['supplier_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="form-label">إذن الاستلام</label>
                    <select name="grn_id" class="form-select">
                        <option value="">— بدون —</option>
                        <?php foreach ($completedGRNs as $g): ?>
                        <option value="<?= (int) $g['id'] ?>" <?= ($invoice['grn_id'] ?? '') == $g['id'] ? 'selected' : '' ?>><?= e($g['grn_number']) ?> — <?= e($g['supplier_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="form-label">تاريخ الفاتورة</label>
                    <input type="date" name="invoice_date" class="form-input" value="<?= e($invoice['invoice_date'] ?? date('Y-m-d')) ?>">
                </div>
                <div>
                    <label class="form-label">تاريخ الاستحقاق</label>
                    <input type="date" name="due_date" class="form-input" value="<?= e($invoice['due_date'] ?? '') ?>">
                </div>
            </div>
            <div style="margin-top:15px;">
                <label class="form-label">ملاحظات</label>
                <textarea name="notes" class="form-input" rows="2"><?= e($invoice['notes'] ?? '') ?></textarea>
            </div>
        </div>
    </div>

    <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="addInvRow()">
                <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="invTable">
                <thead>
                    <tr>
                        <th>الوصف</th>
                        <th style="width:100px;">الكمية</th>
                        <th style="width:120px;">سعر الوحدة</th>
                        <th style="width:80px;">ضريبة %</th>
                        <th style="width:100px;">الإجمالي</th>
                        <th style="width:50px;"></th>
                    </tr>
                </thead>
                <tbody id="invBody"></tbody>
                <tfoot>
                    <tr>
                        <td colspan="4" style="text-align:left;font-weight:700;">الإجمالي</td>
                        <td style="font-weight:800;direction:ltr;text-align:left;" id="invGrandTotal">0.00</td>
                        <td></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> حفظ الفاتورة
        </button>
    </div>
</form>

<script>
var invRowIdx = 0;
function addInvRow(data) {
    data = data || {};
    var idx = invRowIdx++;
    var tr = document.createElement('tr');
    tr.innerHTML = ''
        + '<td><input type="text" name="items['+idx+'][description]" class="form-input" value="'+(data.description||'')+'" placeholder="وصف البند"></td>'
        + '<td><input type="number" name="items['+idx+'][quantity]" class="form-input" step="0.001" min="0.001" value="'+(data.quantity||'')+'" onchange="calcInvRow('+idx+')" required></td>'
        + '<td><input type="number" name="items['+idx+'][unit_cost]" class="form-input" step="0.01" min="0" value="'+(data.unit_cost||'')+'" onchange="calcInvRow('+idx+')" required></td>'
        + '<td><input type="number" name="items['+idx+'][tax_rate]" class="form-input" step="0.01" min="0" value="'+(data.tax_rate||'14')+'" onchange="calcInvRow('+idx+')"></td>'
        + '<td style="font-weight:700;direction:ltr;text-align:left;" id="invLine_'+idx+'">0.00</td>'
        + '<td><button type="button" onclick="this.closest(\'tr\').remove();calcInvGrand();" style="background:none;border:none;cursor:pointer;color:#DC2626;"><i data-lucide="trash-2" style="width:16px;height:16px;"></i></button></td>';
    document.getElementById('invBody').appendChild(tr);
    if (typeof lucide !== 'undefined') lucide.createIcons();
    calcInvRow(idx);
}
function calcInvRow(idx) {
    var q = parseFloat(document.querySelector('[name="items['+idx+'][quantity]"]').value) || 0;
    var c = parseFloat(document.querySelector('[name="items['+idx+'][unit_cost]"]').value) || 0;
    var t = parseFloat(document.querySelector('[name="items['+idx+'][tax_rate]"]').value) || 0;
    var base = q * c;
    var tax = base * (t / 100);
    var el = document.getElementById('invLine_' + idx);
    if (el) el.textContent = (base + tax).toFixed(2);
    calcInvGrand();
}
function calcInvGrand() {
    var total = 0;
    document.querySelectorAll('[id^="invLine_"]').forEach(function(el) { total += parseFloat(el.textContent) || 0; });
    document.getElementById('invGrandTotal').textContent = total.toFixed(2);
}
document.addEventListener('DOMContentLoaded', function() {
    if (typeof lucide !== 'undefined') lucide.createIcons();
    <?php if ($isEdit && !empty($invoiceItems)): ?>
    <?= json_encode($invoiceItems) ?>.forEach(function(item) { addInvRow(item); });
    <?php else: ?>
    addInvRow();
    <?php endif; ?>
});
</script>
<?php $__template->endSection(); ?>
