<?php
$isEdit = $package !== null;
$__template->layout('Layout.main');
?>
<?php $__template->section('title'); ?><?= $isEdit ? 'تعديل الباقة' : 'إنشاء باقة جديدة' ?><?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<?php if ($isEdit): ?>
<a href="/sales/packages/<?= (int) $package->id ?>" class="btn btn-outline"><i data-lucide="eye" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> عرض الباقة</a>
<?php endif; ?>
<a href="/sales/packages" 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="<?= $isEdit ? '/sales/packages/' . (int) $package->id : '/sales/packages' ?>" id="packageForm">
    <?= csrf_field() ?>

    <!-- Header Fields -->
    <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="gift" 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 1fr;gap:20px;">
                <div class="form-group">
                    <label class="form-label">كود الباقة <span style="color:#DC2626;">*</span></label>
                    <input type="text" name="code" value="<?= e(old('code', $package->code ?? '')) ?>" class="form-input" required placeholder="مثال: PKG-001" style="direction:ltr;text-align:left;text-transform:uppercase;">
                </div>
                <div class="form-group">
                    <label class="form-label">الاسم بالعربي <span style="color:#DC2626;">*</span></label>
                    <input type="text" name="name_ar" value="<?= e(old('name_ar', $package->name_ar ?? '')) ?>" class="form-input" required placeholder="اسم الباقة بالعربي">
                </div>
                <div class="form-group">
                    <label class="form-label">الاسم بالإنجليزي</label>
                    <input type="text" name="name_en" value="<?= e(old('name_en', $package->name_en ?? '')) ?>" class="form-input" placeholder="Package name in English" style="direction:ltr;text-align:left;">
                </div>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:20px;margin-top:15px;">
                <div class="form-group">
                    <label class="form-label">سعر الباقة (عضو) <span style="color:#DC2626;">*</span></label>
                    <input type="number" name="package_price_member" value="<?= e(old('package_price_member', $package->package_price_member ?? '0.00')) ?>" class="form-input" step="0.01" min="0" required style="direction:ltr;text-align:left;">
                </div>
                <div class="form-group">
                    <label class="form-label">سعر الباقة (غير عضو) <span style="color:#DC2626;">*</span></label>
                    <input type="number" name="package_price_nonmember" value="<?= e(old('package_price_nonmember', $package->package_price_nonmember ?? '0.00')) ?>" class="form-input" step="0.01" min="0" required style="direction:ltr;text-align:left;">
                </div>
                <div class="form-group">
                    <label class="form-label">فعّال من</label>
                    <input type="date" name="active_from" value="<?= e(old('active_from', $package->active_from ?? '')) ?>" class="form-input">
                </div>
                <div class="form-group">
                    <label class="form-label">فعّال حتى</label>
                    <input type="date" name="active_to" value="<?= e(old('active_to', $package->active_to ?? '')) ?>" class="form-input">
                </div>
            </div>
            <div class="form-group" style="margin-top:15px;">
                <label class="form-label">ملاحظات</label>
                <textarea name="notes" class="form-input" rows="2" placeholder="ملاحظات إضافية..."><?= e(old('notes', $package->notes ?? '')) ?></textarea>
            </div>
        </div>
    </div>

    <!-- Package Items (Dynamic) -->
    <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:#059669;"></i>
                <h3 style="margin:0;color:#059669;font-size:15px;">أصناف الباقة</h3>
            </div>
            <button type="button" onclick="addItemRow()" class="btn btn-sm btn-primary" style="font-size:12px;padding:6px 14px;">
                <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="itemsTable">
                <thead>
                    <tr>
                        <th>الصنف <span style="color:#DC2626;">*</span></th>
                        <th style="width:120px;">الكمية <span style="color:#DC2626;">*</span></th>
                        <th style="width:130px;">سعر الوحدة (عضو)</th>
                        <th style="width:130px;">الإجمالي</th>
                        <th style="width:50px;"></th>
                    </tr>
                </thead>
                <tbody id="itemsBody">
                    <!-- JS will populate -->
                </tbody>
                <tfoot>
                    <tr style="background:#F9FAFB;">
                        <td colspan="3" style="font-weight:700;padding:12px 15px;">إجمالي قيمة الأصناف</td>
                        <td id="itemsTotalDisplay" style="font-weight:800;font-size:16px;color:#059669;direction:ltr;text-align:left;padding:12px 15px;">0.00</td>
                        <td></td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>

    <!-- Submit Buttons -->
    <div style="display:flex;gap:10px;justify-content:flex-start;">
        <button type="submit" class="btn btn-primary" style="padding:12px 30px;font-size:15px;">
            <i data-lucide="check" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i>
            <?= $isEdit ? 'حفظ التعديلات' : 'إنشاء الباقة' ?>
        </button>
        <a href="/sales/packages" 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();
    initItems();
});

var availableItems = <?= json_encode(array_map(function($i) {
    return [
        'id' => (int) $i['id'],
        'name' => $i['name_ar'] ?? '',
        'sku' => $i['sku'] ?? '',
        'price' => (float) ($i['sale_price_member'] ?? 0),
    ];
}, $items), JSON_UNESCAPED_UNICODE) ?>;

var rowIndex = 0;

function initItems() {
    <?php if ($isEdit && !empty($packageItems)): ?>
    var existingItems = <?= json_encode(array_map(function($pi) {
        return [
            'item_id' => (int) ($pi['item_id'] ?? 0),
            'quantity' => (float) ($pi['quantity'] ?? 1),
        ];
    }, $packageItems), JSON_UNESCAPED_UNICODE) ?>;
    existingItems.forEach(function(ei) {
        addItemRow(ei.item_id, ei.quantity);
    });
    <?php else: ?>
    addItemRow();
    <?php endif; ?>
}

function addItemRow(selectedItemId, selectedQty) {
    selectedItemId = selectedItemId || '';
    selectedQty = selectedQty || 1;
    var tbody = document.getElementById('itemsBody');
    var idx = rowIndex++;

    var options = '<option value="">-- اختر صنف --</option>';
    availableItems.forEach(function(item) {
        var sel = item.id == selectedItemId ? ' selected' : '';
        options += '<option value="' + item.id + '" data-price="' + item.price + '"' + sel + '>' + escapeHtml(item.name) + ' (' + escapeHtml(item.sku) + ')</option>';
    });

    var tr = document.createElement('tr');
    tr.id = 'itemRow_' + idx;
    tr.innerHTML =
        '<td><select name="item_ids[]" class="form-select item-select" data-idx="' + idx + '" onchange="onItemChange(' + idx + ')" required>' + options + '</select></td>' +
        '<td><input type="number" name="quantities[]" class="form-input item-qty" data-idx="' + idx + '" value="' + selectedQty + '" min="1" step="1" onchange="calcRowTotal(' + idx + ')" style="text-align:center;"></td>' +
        '<td><span class="item-unit-price" data-idx="' + idx + '" style="font-weight:600;direction:ltr;display:inline-block;">0.00</span></td>' +
        '<td><span class="item-line-total" data-idx="' + idx + '" style="font-weight:700;direction:ltr;display:inline-block;">0.00</span></td>' +
        '<td><button type="button" onclick="removeItemRow(' + idx + ')" style="background:none;border:none;color:#DC2626;cursor:pointer;padding:4px;"><i data-lucide="trash-2" style="width:14px;height:14px;"></i></button></td>';

    tbody.appendChild(tr);
    if (typeof lucide !== 'undefined') lucide.createIcons();
    onItemChange(idx);
}

function removeItemRow(idx) {
    var row = document.getElementById('itemRow_' + idx);
    if (row) row.remove();
    calcGrandTotal();
}

function onItemChange(idx) {
    var sel = document.querySelector('.item-select[data-idx="' + idx + '"]');
    var opt = sel.options[sel.selectedIndex];
    var price = parseFloat(opt.getAttribute('data-price')) || 0;
    document.querySelector('.item-unit-price[data-idx="' + idx + '"]').textContent = price.toFixed(2);
    calcRowTotal(idx);
}

function calcRowTotal(idx) {
    var sel = document.querySelector('.item-select[data-idx="' + idx + '"]');
    var opt = sel.options[sel.selectedIndex];
    var price = parseFloat(opt.getAttribute('data-price')) || 0;
    var qty = parseInt(document.querySelector('.item-qty[data-idx="' + idx + '"]').value) || 0;
    var total = price * qty;
    document.querySelector('.item-line-total[data-idx="' + idx + '"]').textContent = total.toFixed(2);
    calcGrandTotal();
}

function calcGrandTotal() {
    var sum = 0;
    document.querySelectorAll('.item-line-total').forEach(function(el) {
        sum += parseFloat(el.textContent) || 0;
    });
    document.getElementById('itemsTotalDisplay').textContent = sum.toFixed(2);
}

function escapeHtml(str) {
    var div = document.createElement('div');
    div.appendChild(document.createTextNode(str || ''));
    return div.innerHTML;
}
</script>
<?php $__template->endSection(); ?>
