<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>استرجاع مبيعة <?= e($sale['invoice_number'] ?? '') ?><?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<a href="/sales/<?= (int) $sale['id'] ?>" 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'); ?>

<!-- Sale Summary -->
<div class="card" style="margin-bottom:20px;background:linear-gradient(135deg, #FFF7ED10, #FFF7ED30);">
    <div style="padding:15px 20px;display:flex;align-items:center;gap:15px;flex-wrap:wrap;">
        <div>
            <div style="font-size:12px;color:#6B7280;">رقم الفاتورة</div>
            <div style="font-weight:700;font-family:monospace;color:#1e3a5f;font-size:16px;"><?= e($sale['invoice_number'] ?? '') ?></div>
        </div>
        <div style="width:1px;height:35px;background:#E5E7EB;"></div>
        <div>
            <div style="font-size:12px;color:#6B7280;">الإجمالي</div>
            <div style="font-weight:700;font-size:16px;color:#059669;direction:ltr;text-align:left;"><?= money($sale['total_amount'] ?? 0) ?></div>
        </div>
        <?php if ((float) ($sale['amount_refunded'] ?? 0) > 0): ?>
        <div style="width:1px;height:35px;background:#E5E7EB;"></div>
        <div>
            <div style="font-size:12px;color:#6B7280;">المسترجع سابقًا</div>
            <div style="font-weight:700;font-size:16px;color:#DC2626;direction:ltr;text-align:left;"><?= money($sale['amount_refunded'] ?? 0) ?></div>
        </div>
        <?php endif; ?>
    </div>
</div>

<form method="POST" action="/sales/<?= (int) $sale['id'] ?>/refund" id="refundForm">
    <?= csrf_field() ?>

    <!-- Items to Refund -->
    <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" 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 style="width:40px;">
                            <input type="checkbox" id="selectAll" onchange="toggleAll()" style="width:16px;height:16px;accent-color:#1e3a5f;">
                        </th>
                        <th>الصنف</th>
                        <th>الكمية المباعة</th>
                        <th>المسترجع سابقًا</th>
                        <th>المتاح للاسترجاع</th>
                        <th style="width:100px;">كمية الاسترجاع</th>
                        <th>سعر الوحدة</th>
                        <th>إجمالي الاسترجاع</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($items as $i => $item): ?>
                    <?php
                    $qty = (float) ($item['quantity'] ?? 0);
                    $refundedQty = (float) ($item['refunded_quantity'] ?? 0);
                    $available = $qty - $refundedQty;
                    $unitPrice = (float) ($item['unit_price'] ?? 0);
                    ?>
                    <tr id="itemRow_<?= $i ?>" style="<?= $available <= 0 ? 'opacity:0.4;' : '' ?>">
                        <td>
                            <?php if ($available > 0): ?>
                            <input type="checkbox" class="item-check" data-index="<?= $i ?>" onchange="recalcRefund()" style="width:16px;height:16px;accent-color:#1e3a5f;">
                            <input type="hidden" name="sale_item_ids[]" value="<?= (int) $item['id'] ?>" disabled>
                            <?php endif; ?>
                        </td>
                        <td style="font-weight:600;">
                            <?= e($item['item_name_ar'] ?? '') ?>
                            <?php if (!empty($item['sku'])): ?>
                            <div style="font-size:11px;color:#9CA3AF;font-family:monospace;"><?= e($item['sku']) ?></div>
                            <?php endif; ?>
                        </td>
                        <td style="font-weight:600;"><?= number_format($qty, 0) ?></td>
                        <td style="color:#D97706;font-weight:600;"><?= number_format($refundedQty, 0) ?></td>
                        <td style="font-weight:700;color:<?= $available > 0 ? '#059669' : '#DC2626' ?>;"><?= number_format($available, 0) ?></td>
                        <td>
                            <?php if ($available > 0): ?>
                            <input type="number" name="refund_quantities[]" class="refund-qty form-input" data-index="<?= $i ?>"
                                   value="0" min="0" max="<?= (int) $available ?>" step="1"
                                   style="width:80px;padding:6px;text-align:center;font-size:13px;" onchange="recalcRefund()" disabled>
                            <?php else: ?>
                            <span style="color:#9CA3AF;">—</span>
                            <?php endif; ?>
                        </td>
                        <td style="direction:ltr;text-align:left;"><?= money($unitPrice) ?></td>
                        <td>
                            <span class="line-refund-total" data-index="<?= $i ?>" style="font-weight:700;direction:ltr;display:inline-block;">0.00</span>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Refund Details -->
    <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="settings" 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 2fr;gap:20px;">
                <div class="form-group">
                    <label class="form-label">مبلغ الاسترجاع <span style="color:#DC2626;">*</span></label>
                    <input type="number" name="refund_amount" id="refundAmountInput" class="form-input" step="0.01" min="0" value="0" required style="direction:ltr;text-align:left;font-size:16px;font-weight:700;">
                    <div style="font-size:11px;color:#9CA3AF;margin-top:4px;">يتم حسابه تلقائيًا، ويمكنك تعديله يدويًا</div>
                </div>
                <div class="form-group">
                    <label class="form-label">سبب الاسترجاع <span style="color:#DC2626;">*</span></label>
                    <textarea name="reason" class="form-input" rows="2" required placeholder="أدخل سبب الاسترجاع..."><?= e(old('reason', '')) ?></textarea>
                </div>
            </div>
            <div style="margin-top:15px;">
                <label style="display:flex;align-items:center;gap:8px;cursor:pointer;padding:12px 16px;border:1px solid #E5E7EB;border-radius:8px;width:fit-content;">
                    <input type="hidden" name="return_to_stock" value="0">
                    <input type="checkbox" name="return_to_stock" value="1" checked style="width:18px;height:18px;accent-color:#1e3a5f;">
                    <div>
                        <div style="font-size:13px;font-weight:600;color:#1A1A2E;">إرجاع الكميات للمخزون</div>
                        <div style="font-size:11px;color:#9CA3AF;">سيتم إرجاع الكميات المسترجعة إلى المخزن تلقائيًا</div>
                    </div>
                </label>
            </div>
        </div>
    </div>

    <!-- Submit -->
    <div style="display:flex;gap:10px;justify-content:flex-start;">
        <button type="submit" class="btn" style="background:#D97706;color:#fff;padding:12px 30px;font-size:15px;border:none;border-radius:8px;cursor:pointer;font-weight:600;font-family:inherit;">
            <i data-lucide="rotate-ccw" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i>
            تأكيد الاسترجاع
        </button>
        <a href="/sales/<?= (int) $sale['id'] ?>" class="btn btn-outline" style="padding:12px 30px;font-size:15px;">إلغاء</a>
    </div>
</form>

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

var itemPrices = {};
<?php foreach ($items as $i => $item): ?>
<?php $available = (float) ($item['quantity'] ?? 0) - (float) ($item['refunded_quantity'] ?? 0); ?>
<?php if ($available > 0): ?>
itemPrices[<?= $i ?>] = <?= (float) ($item['unit_price'] ?? 0) ?>;
<?php endif; ?>
<?php endforeach; ?>

function toggleAll() {
    var checked = document.getElementById('selectAll').checked;
    document.querySelectorAll('.item-check').forEach(function(cb) {
        cb.checked = checked;
        toggleItemRow(cb);
    });
    recalcRefund();
}

document.querySelectorAll('.item-check').forEach(function(cb) {
    cb.addEventListener('change', function() {
        toggleItemRow(this);
        recalcRefund();
    });
});

function toggleItemRow(cb) {
    var index = cb.getAttribute('data-index');
    var row = document.getElementById('itemRow_' + index);
    var qtyInput = row.querySelector('.refund-qty');
    var hiddenInput = row.querySelector('input[name="sale_item_ids[]"]');
    if (cb.checked) {
        qtyInput.disabled = false;
        hiddenInput.disabled = false;
        if (parseInt(qtyInput.value) === 0) {
            qtyInput.value = qtyInput.getAttribute('max');
        }
    } else {
        qtyInput.disabled = true;
        hiddenInput.disabled = true;
        qtyInput.value = 0;
    }
}

function recalcRefund() {
    var totalRefund = 0;
    document.querySelectorAll('.item-check').forEach(function(cb) {
        var index = cb.getAttribute('data-index');
        var qtyInput = document.querySelector('.refund-qty[data-index="' + index + '"]');
        var lineDisplay = document.querySelector('.line-refund-total[data-index="' + index + '"]');
        if (cb.checked && qtyInput) {
            var qty = parseInt(qtyInput.value) || 0;
            var lineTotal = qty * (itemPrices[index] || 0);
            lineDisplay.textContent = lineTotal.toFixed(2);
            totalRefund += lineTotal;
        } else if (lineDisplay) {
            lineDisplay.textContent = '0.00';
        }
    });
    document.getElementById('refundAmountInput').value = totalRefund.toFixed(2);
}
</script>
<?php $__template->endSection(); ?>
