<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?><?= isset($rtv) ? 'تعديل مرتجع مورد' : 'مرتجع مورد جديد' ?><?php $__template->endSection(); ?>
<?php $__template->section('page_actions'); ?>
<a href="/procurement/rtv" 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($rtv); $action = $isEdit ? '/procurement/rtv/' . (int) $rtv['id'] . '/update' : '/procurement/rtv'; ?>

<form method="POST" action="<?= $action ?>">
    <?= csrf_field() ?>
    <div class="card" style="margin-bottom:20px;">
        <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;"><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="supplier_id" class="form-select" required><option value="">-- اختر --</option><?php foreach ($suppliers as $s): ?><option value="<?= (int) $s['id'] ?>" <?= ($rtv['supplier_id'] ?? '') == $s['id'] ? 'selected' : '' ?>><?= e($s['name_ar']) ?></option><?php endforeach; ?></select></div>
                <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 $w): ?><option value="<?= (int) $w['id'] ?>" <?= ($rtv['warehouse_id'] ?? '') == $w['id'] ? 'selected' : '' ?>><?= e($w['name_ar']) ?></option><?php endforeach; ?></select></div>
                <div><label class="form-label">تاريخ الإرجاع</label><input type="date" name="return_date" class="form-input" value="<?= e($rtv['return_date'] ?? date('Y-m-d')) ?>"></div>
                <div><label class="form-label">سبب الإرجاع <span style="color:#DC2626;">*</span></label><input type="text" name="reason" class="form-input" value="<?= e($rtv['reason'] ?? '') ?>" required></div>
            </div>
            <div style="margin-top:15px;"><label class="form-label">ملاحظات</label><textarea name="notes" class="form-input" rows="2"><?= e($rtv['notes'] ?? '') ?></textarea></div>
        </div>
    </div>

    <div class="card" style="margin-bottom:20px;">
        <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;display:flex;justify-content:space-between;align-items:center;">
            <h3 style="margin:0;color:#D97706;font-size:15px;">الأصناف</h3>
            <button type="button" class="btn btn-sm btn-primary" onclick="addRtvRow()"><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"><thead><tr><th>الصنف</th><th style="width:100px;">الكمية</th><th style="width:120px;">سعر الوحدة</th><th style="width:120px;">الإجمالي</th><th>السبب</th><th style="width:50px;"></th></tr></thead>
            <tbody id="rtvBody"></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="rtvTotal">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> حفظ المرتجع</button></div>
</form>

<script>
var invItems = <?= json_encode($items ?? []) ?>;
var rtvIdx = 0;
function addRtvRow(d) {
    d = d || {};
    var i = rtvIdx++;
    var opts = '<option value="">-- اختر --</option>';
    invItems.forEach(function(it) { var s = (d.item_id && d.item_id == it.id) ? ' selected' : ''; opts += '<option value="'+it.id+'" data-cost="'+(it.cost_price||0)+'"'+s+'>'+it.name_ar+'</option>'; });
    var tr = document.createElement('tr');
    tr.innerHTML = '<td><select name="items['+i+'][item_id]" class="form-select" required onchange="var o=this.options[this.selectedIndex];document.getElementById(\'rc_'+i+'\').value=o.getAttribute(\'data-cost\')||0;calcRtv('+i+');">'+opts+'</select></td>'
        +'<td><input type="number" name="items['+i+'][quantity]" class="form-input" step="0.001" min="0.001" value="'+(d.quantity||'')+'" onchange="calcRtv('+i+')" required></td>'
        +'<td><input type="number" name="items['+i+'][unit_cost]" class="form-input" step="0.01" min="0" value="'+(d.unit_cost||'')+'" id="rc_'+i+'" onchange="calcRtv('+i+')"></td>'
        +'<td style="font-weight:700;direction:ltr;text-align:left;" id="rl_'+i+'">0.00</td>'
        +'<td><input type="text" name="items['+i+'][reason]" class="form-input" value="'+(d.reason||'')+'" placeholder="سبب"></td>'
        +'<td><button type="button" onclick="this.closest(\'tr\').remove();calcRtvTotal();" style="background:none;border:none;cursor:pointer;color:#DC2626;"><i data-lucide="trash-2" style="width:16px;height:16px;"></i></button></td>';
    document.getElementById('rtvBody').appendChild(tr);
    if (typeof lucide !== 'undefined') lucide.createIcons();
    calcRtv(i);
}
function calcRtv(i) {
    var q = parseFloat(document.querySelector('[name="items['+i+'][quantity]"]').value) || 0;
    var c = parseFloat(document.getElementById('rc_'+i).value) || 0;
    document.getElementById('rl_'+i).textContent = (q*c).toFixed(2);
    calcRtvTotal();
}
function calcRtvTotal() {
    var t = 0; document.querySelectorAll('[id^="rl_"]').forEach(function(e) { t += parseFloat(e.textContent) || 0; });
    document.getElementById('rtvTotal').textContent = t.toFixed(2);
}
document.addEventListener('DOMContentLoaded', function() {
    if (typeof lucide !== 'undefined') lucide.createIcons();
    <?php if ($isEdit && !empty($rtvItems)): ?><?= json_encode($rtvItems) ?>.forEach(function(it) { addRtvRow(it); });<?php else: ?>addRtvRow();<?php endif; ?>
});
</script>
<?php $__template->endSection(); ?>
