<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>إدخال أرصدة افتتاحية<?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<a href="/inventory/opening-balances" 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/opening-balances" id="openingBalanceForm">
    <?= 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="archive" 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">المخزن <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'] ?>"><?= e($wh['name_ar']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="form-label">تاريخ الرصيد <span style="color:#DC2626;">*</span></label>
                    <input type="date" name="balance_date" class="form-input" value="<?= e(date('Y-m-d')) ?>" required>
                </div>
            </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="addBalanceRow()">
                <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="balanceTable">
                <thead>
                    <tr>
                        <th>الصنف</th>
                        <th style="width:120px;">الكمية</th>
                        <th style="width:120px;">تكلفة الوحدة</th>
                        <th style="width:120px;">الإجمالي</th>
                        <th style="width:50px;"></th>
                    </tr>
                </thead>
                <tbody id="balanceBody"></tbody>
                <tfoot>
                    <tr>
                        <td colspan="3" style="text-align:left;font-weight:700;">الإجمالي الكلي</td>
                        <td style="font-weight:800;direction:ltr;text-align:left;" id="balanceGrandTotal">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 balRowIdx = 0;
var itemsData = <?= json_encode($items) ?>;

function addBalanceRow(data) {
    data = data || {};
    var idx = balRowIdx++;
    var tr = document.createElement('tr');

    var itemOptions = '<option value="">-- اختر الصنف --</option>';
    itemsData.forEach(function(item) {
        var selected = (data.item_id && data.item_id == item.id) ? 'selected' : '';
        itemOptions += '<option value="' + item.id + '" ' + selected + '>' + item.name_ar + '</option>';
    });

    tr.innerHTML = ''
        + '<td><select name="items['+idx+'][item_id]" class="form-select" required>' + itemOptions + '</select></td>'
        + '<td><input type="number" name="items['+idx+'][quantity]" class="form-input" step="0.001" min="0.001" value="'+(data.quantity||'')+'" onchange="calcBalanceRow('+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="calcBalanceRow('+idx+')" required></td>'
        + '<td style="font-weight:700;direction:ltr;text-align:left;" id="balLine_'+idx+'">0.00</td>'
        + '<td><button type="button" onclick="this.closest(\'tr\').remove();calcBalanceGrand();" style="background:none;border:none;cursor:pointer;color:#DC2626;"><i data-lucide="trash-2" style="width:16px;height:16px;"></i></button></td>';

    document.getElementById('balanceBody').appendChild(tr);
    if (typeof lucide !== 'undefined') lucide.createIcons();
    calcBalanceRow(idx);
}

function calcBalanceRow(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 el = document.getElementById('balLine_' + idx);
    if (el) el.textContent = (q * c).toFixed(2);
    calcBalanceGrand();
}

function calcBalanceGrand() {
    var total = 0;
    document.querySelectorAll('[id^="balLine_"]').forEach(function(el) { total += parseFloat(el.textContent) || 0; });
    document.getElementById('balanceGrandTotal').textContent = total.toFixed(2);
}

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