<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>نقطة البيع<?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<a href="/sales" class="btn btn-outline"><i data-lucide="list" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> المبيعات</a>
<?php $__template->endSection(); ?>

<?php $__template->section('content'); ?>

<form method="POST" action="/sales" id="posForm">
    <?= csrf_field() ?>

    <div style="display:grid;grid-template-columns:1fr 400px;gap:20px;align-items:start;">

        <!-- Left Side: Items Search & Packages -->
        <div>
            <!-- Item Search -->
            <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="search" style="width:18px;height:18px;color:#0D7377;"></i>
                    <h3 style="margin:0;color:#0D7377;font-size:15px;">بحث الأصناف</h3>
                </div>
                <div style="padding:15px 20px;">
                    <input type="text" id="itemSearchInput" placeholder="ابحث بالاسم، SKU، أو الباركود..." class="form-input" style="font-size:15px;padding:12px;" autocomplete="off">
                </div>
                <div id="itemResults" style="max-height:400px;overflow-y:auto;display:none;">
                    <!-- AJAX results will appear here -->
                </div>
            </div>

            <!-- Packages Section -->
            <?php if (!empty($packages)): ?>
            <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:#D97706;"></i>
                    <h3 style="margin:0;color:#D97706;font-size:15px;">الباقات المتاحة</h3>
                </div>
                <div style="padding:15px;display:grid;grid-template-columns:repeat(auto-fill, minmax(200px, 1fr));gap:12px;">
                    <?php foreach ($packages as $pkg): ?>
                    <div style="border:1px solid #E5E7EB;border-radius:10px;padding:14px;cursor:pointer;transition:all 0.2s;"
                         class="package-card"
                         onclick="addPackageToCart(<?= (int) $pkg['id'] ?>, '<?= e(addslashes($pkg['name_ar'])) ?>', '<?= e($pkg['package_price_member']) ?>', '<?= e($pkg['package_price_nonmember']) ?>')"
                         onmouseover="this.style.borderColor='#0D7377';this.style.background='#F0FDFA'"
                         onmouseout="this.style.borderColor='#E5E7EB';this.style.background=''">
                        <div style="font-weight:700;color:#1A1A2E;margin-bottom:6px;font-size:14px;"><?= e($pkg['name_ar']) ?></div>
                        <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">كود: <?= e($pkg['code']) ?></div>
                        <div style="display:flex;justify-content:space-between;font-size:13px;margin-top:8px;">
                            <span style="color:#059669;font-weight:600;">عضو: <?= money($pkg['package_price_member']) ?></span>
                        </div>
                        <div style="font-size:12px;color:#6B7280;margin-top:2px;">غير عضو: <?= money($pkg['package_price_nonmember']) ?></div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <!-- Right Side: Cart & Checkout -->
        <div>
            <!-- Customer Section -->
            <div class="card" style="margin-bottom:15px;">
                <div style="padding:12px 20px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;gap:8px;">
                    <i data-lucide="user" style="width:18px;height:18px;color:#0D7377;"></i>
                    <h3 style="margin:0;color:#0D7377;font-size:14px;">العميل</h3>
                </div>
                <div style="padding:15px;">
                    <!-- Customer Type Tabs -->
                    <div style="display:flex;gap:0;margin-bottom:15px;border:1px solid #E5E7EB;border-radius:8px;overflow:hidden;">
                        <button type="button" class="customer-tab active" data-type="member" onclick="switchCustomerType('member')"
                                style="flex:1;padding:10px;border:none;cursor:pointer;font-weight:600;font-size:13px;font-family:inherit;background:#0D7377;color:#fff;transition:all 0.2s;">
                            عضو
                        </button>
                        <button type="button" class="customer-tab" data-type="player" onclick="switchCustomerType('player')"
                                style="flex:1;padding:10px;border:none;border-right:1px solid #E5E7EB;border-left:1px solid #E5E7EB;cursor:pointer;font-weight:600;font-size:13px;font-family:inherit;background:#fff;color:#6B7280;transition:all 0.2s;">
                            لاعب
                        </button>
                        <button type="button" class="customer-tab" data-type="guest" onclick="switchCustomerType('guest')"
                                style="flex:1;padding:10px;border:none;cursor:pointer;font-weight:600;font-size:13px;font-family:inherit;background:#fff;color:#6B7280;transition:all 0.2s;">
                            زائر
                        </button>
                    </div>
                    <input type="hidden" name="customer_type" id="customerType" value="member">
                    <input type="hidden" name="member_id" id="memberId" value="">
                    <input type="hidden" name="player_id" id="playerId" value="">

                    <!-- Member/Player Search -->
                    <div id="customerSearchSection">
                        <div style="position:relative;">
                            <input type="text" id="customerSearchInput" placeholder="ابحث بالاسم أو الرقم..." class="form-input" autocomplete="off">
                            <div id="customerResults" style="position:absolute;top:100%;right:0;left:0;z-index:10;background:#fff;border:1px solid #E5E7EB;border-radius:0 0 8px 8px;max-height:200px;overflow-y:auto;display:none;box-shadow:0 4px 12px rgba(0,0,0,0.1);"></div>
                        </div>
                        <div id="selectedCustomer" style="display:none;margin-top:10px;padding:10px;background:#F0FDF4;border-radius:8px;border:1px solid #BBF7D0;">
                            <div style="display:flex;justify-content:space-between;align-items:center;">
                                <span id="selectedCustomerName" style="font-weight:600;color:#059669;"></span>
                                <button type="button" onclick="clearCustomer()" style="background:none;border:none;color:#DC2626;cursor:pointer;font-size:12px;font-family:inherit;">
                                    <i data-lucide="x" style="width:14px;height:14px;"></i>
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Guest Fields -->
                    <div id="guestSection" style="display:none;">
                        <div style="display:grid;gap:10px;">
                            <input type="text" name="guest_name" id="guestName" placeholder="اسم الزائر" class="form-input">
                            <input type="text" name="guest_phone" id="guestPhone" placeholder="رقم الهاتف" class="form-input" style="direction:ltr;text-align:left;">
                        </div>
                    </div>
                </div>
            </div>

            <!-- Warehouse & Payment -->
            <div class="card" style="margin-bottom:15px;">
                <div style="padding:15px;">
                    <div style="display:grid;gap:10px;">
                        <div>
                            <label class="form-label" style="font-size:12px;">المخزن <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" style="font-size:12px;">طريقة الدفع</label>
                            <select name="payment_method" class="form-select">
                                <option value="cash">نقدي</option>
                                <option value="visa">فيزا</option>
                                <option value="transfer">تحويل بنكي</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Cart -->
            <div class="card" style="margin-bottom:15px;">
                <div style="padding:12px 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="shopping-cart" style="width:18px;height:18px;color:#0D7377;"></i>
                        <h3 style="margin:0;color:#0D7377;font-size:14px;">السلة</h3>
                    </div>
                    <span id="cartCount" style="background:#0D7377;color:#fff;padding:2px 8px;border-radius:10px;font-size:12px;font-weight:600;">0</span>
                </div>
                <div id="cartContainer">
                    <div id="emptyCart" style="padding:40px 20px;text-align:center;color:#9CA3AF;">
                        <i data-lucide="shopping-bag" style="width:36px;height:36px;color:#D1D5DB;margin-bottom:8px;"></i>
                        <p style="margin:0;font-size:13px;">السلة فارغة</p>
                    </div>
                    <table id="cartTable" class="data-table" style="display:none;">
                        <thead>
                            <tr>
                                <th style="font-size:12px;">الصنف</th>
                                <th style="font-size:12px;width:60px;">الكمية</th>
                                <th style="font-size:12px;width:80px;">السعر</th>
                                <th style="font-size:12px;width:80px;">الإجمالي</th>
                                <th style="width:30px;"></th>
                            </tr>
                        </thead>
                        <tbody id="cartBody"></tbody>
                    </table>
                </div>

                <!-- Hidden inputs container for form submission -->
                <div id="hiddenInputs"></div>
            </div>

            <!-- Discount -->
            <div class="card" style="margin-bottom:15px;">
                <div style="padding:15px;">
                    <div style="display:grid;grid-template-columns:1fr 2fr;gap:10px;">
                        <div>
                            <label class="form-label" style="font-size:12px;">الخصم</label>
                            <input type="number" name="discount_amount" id="discountAmount" value="0" class="form-input" step="0.01" min="0" style="direction:ltr;text-align:left;" onchange="updateTotals()">
                        </div>
                        <div>
                            <label class="form-label" style="font-size:12px;">سبب الخصم</label>
                            <input type="text" name="discount_reason" placeholder="اختياري" class="form-input">
                        </div>
                    </div>
                </div>
            </div>

            <!-- Totals -->
            <div class="card" style="margin-bottom:15px;overflow:hidden;">
                <div style="padding:15px;">
                    <div style="display:flex;justify-content:space-between;padding:6px 0;font-size:14px;color:#6B7280;">
                        <span>المجموع الفرعي</span>
                        <span id="subtotalDisplay" style="font-weight:600;direction:ltr;">0.00</span>
                    </div>
                    <div style="display:flex;justify-content:space-between;padding:6px 0;font-size:14px;color:#DC2626;">
                        <span>الخصم</span>
                        <span id="discountDisplay" style="font-weight:600;direction:ltr;">- 0.00</span>
                    </div>
                    <div style="display:flex;justify-content:space-between;padding:6px 0;font-size:14px;color:#D97706;">
                        <span>الضريبة</span>
                        <span id="taxDisplay" style="font-weight:600;direction:ltr;">0.00</span>
                    </div>
                    <div style="border-top:2px solid #E5E7EB;margin-top:8px;padding-top:10px;display:flex;justify-content:space-between;font-size:20px;font-weight:800;color:#0D7377;">
                        <span>الإجمالي</span>
                        <span id="totalDisplay" style="direction:ltr;">0.00</span>
                    </div>
                </div>
            </div>

            <!-- Notes -->
            <div style="margin-bottom:15px;">
                <textarea name="notes" placeholder="ملاحظات..." class="form-input" rows="2" style="font-size:13px;"></textarea>
            </div>

            <!-- Submit -->
            <button type="submit" id="submitBtn" class="btn btn-primary" style="width:100%;padding:16px;font-size:18px;font-weight:700;border-radius:12px;" disabled>
                <i data-lucide="credit-card" style="width:20px;height:20px;vertical-align:middle;margin-left:6px;"></i>
                إتمام البيع
            </button>
        </div>
    </div>
</form>

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

var cart = [];
var currentCustomerType = 'member';
var searchTimeout = null;

// --- Item Search ---
document.getElementById('itemSearchInput').addEventListener('input', function() {
    var q = this.value.trim();
    clearTimeout(searchTimeout);
    if (q.length < 2) {
        document.getElementById('itemResults').style.display = 'none';
        return;
    }
    searchTimeout = setTimeout(function() { searchItems(q); }, 300);
});

function searchItems(q) {
    fetch('/sales/search-items?q=' + encodeURIComponent(q))
        .then(function(r) { return r.json(); })
        .then(function(data) {
            var container = document.getElementById('itemResults');
            if (!data.results || data.results.length === 0) {
                container.innerHTML = '<div style="padding:20px;text-align:center;color:#9CA3AF;font-size:13px;">لا توجد نتائج</div>';
                container.style.display = 'block';
                return;
            }
            var html = '';
            data.results.forEach(function(item) {
                var priceLabel = currentCustomerType === 'member' ? item.sale_price_member :
                                 (currentCustomerType === 'player' && item.sale_price_player ? item.sale_price_player : item.sale_price_nonmember);
                html += '<div style="padding:12px 20px;border-bottom:1px solid #F3F4F6;cursor:pointer;display:flex;justify-content:space-between;align-items:center;transition:background 0.1s;" ' +
                        'onmouseover="this.style.background=\'#F0FDFA\'" onmouseout="this.style.background=\'\'" ' +
                        'onclick="addItemToCart(' + item.id + ', \'' + escapeHtml(item.name_ar) + '\', \'' + priceLabel + '\', \'' + (item.cost_price || '0') + '\', \'' + (item.tax_rate || '0') + '\')">' +
                        '<div><div style="font-weight:600;font-size:14px;">' + escapeHtml(item.name_ar) + '</div>' +
                        '<div style="font-size:11px;color:#9CA3AF;font-family:monospace;">' + escapeHtml(item.sku || '') + '</div></div>' +
                        '<div style="font-weight:700;color:#059669;direction:ltr;">' + parseFloat(priceLabel || 0).toFixed(2) + '</div></div>';
            });
            container.innerHTML = html;
            container.style.display = 'block';
        });
}

function addItemToCart(itemId, name, price, costPrice, taxRate) {
    var existing = cart.find(function(c) { return c.item_id == itemId && !c.package_id; });
    if (existing) {
        existing.quantity++;
    } else {
        cart.push({
            item_id: itemId,
            package_id: '',
            name: name,
            quantity: 1,
            unit_price: parseFloat(price) || 0,
            cost_price: parseFloat(costPrice) || 0,
            tax_rate: parseFloat(taxRate) || 0
        });
    }
    renderCart();
    document.getElementById('itemSearchInput').value = '';
    document.getElementById('itemResults').style.display = 'none';
}

function addPackageToCart(pkgId, name, priceMember, priceNonmember) {
    var price = (currentCustomerType === 'member') ? parseFloat(priceMember) : parseFloat(priceNonmember);
    var existing = cart.find(function(c) { return c.package_id == pkgId; });
    if (existing) {
        existing.quantity++;
    } else {
        cart.push({
            item_id: '',
            package_id: pkgId,
            name: name,
            quantity: 1,
            unit_price: price || 0,
            cost_price: 0,
            tax_rate: 0
        });
    }
    renderCart();
}

function removeFromCart(index) {
    cart.splice(index, 1);
    renderCart();
}

function updateQty(index, val) {
    var qty = parseInt(val) || 1;
    if (qty < 1) qty = 1;
    cart[index].quantity = qty;
    renderCart();
}

function renderCart() {
    var tbody = document.getElementById('cartBody');
    var emptyCart = document.getElementById('emptyCart');
    var cartTable = document.getElementById('cartTable');
    var hiddenInputs = document.getElementById('hiddenInputs');

    if (cart.length === 0) {
        emptyCart.style.display = 'block';
        cartTable.style.display = 'none';
        document.getElementById('submitBtn').disabled = true;
    } else {
        emptyCart.style.display = 'none';
        cartTable.style.display = 'table';
        document.getElementById('submitBtn').disabled = false;
    }

    var html = '';
    var hiddenHtml = '';
    cart.forEach(function(item, i) {
        var lineTotal = item.quantity * item.unit_price;
        var taxAmount = lineTotal * (item.tax_rate / 100);
        html += '<tr>' +
            '<td style="font-size:13px;font-weight:600;">' + escapeHtml(item.name) + (item.package_id ? ' <span style="font-size:10px;color:#D97706;background:#FFF7ED;padding:1px 6px;border-radius:6px;">باقة</span>' : '') + '</td>' +
            '<td><input type="number" value="' + item.quantity + '" min="1" style="width:50px;padding:4px;text-align:center;border:1px solid #E5E7EB;border-radius:6px;font-size:13px;" onchange="updateQty(' + i + ', this.value)"></td>' +
            '<td style="font-size:13px;direction:ltr;text-align:left;">' + item.unit_price.toFixed(2) + '</td>' +
            '<td style="font-size:13px;font-weight:700;direction:ltr;text-align:left;">' + lineTotal.toFixed(2) + '</td>' +
            '<td><button type="button" onclick="removeFromCart(' + i + ')" style="background:none;border:none;color:#DC2626;cursor:pointer;padding:4px;"><i data-lucide="trash-2" style="width:14px;height:14px;"></i></button></td>' +
            '</tr>';
        hiddenHtml += '<input type="hidden" name="item_ids[]" value="' + (item.item_id || '') + '">' +
            '<input type="hidden" name="package_ids[]" value="' + (item.package_id || '') + '">' +
            '<input type="hidden" name="quantities[]" value="' + item.quantity + '">' +
            '<input type="hidden" name="unit_prices[]" value="' + item.unit_price.toFixed(2) + '">' +
            '<input type="hidden" name="item_names[]" value="' + escapeHtml(item.name) + '">' +
            '<input type="hidden" name="cost_prices[]" value="' + item.cost_price.toFixed(2) + '">' +
            '<input type="hidden" name="tax_amounts[]" value="' + (item.quantity * item.unit_price * (item.tax_rate / 100)).toFixed(2) + '">';
    });
    tbody.innerHTML = html;
    hiddenInputs.innerHTML = hiddenHtml;

    document.getElementById('cartCount').textContent = cart.length;
    updateTotals();

    if (typeof lucide !== 'undefined') lucide.createIcons();
}

function updateTotals() {
    var subtotal = 0;
    var totalTax = 0;
    cart.forEach(function(item) {
        var lineTotal = item.quantity * item.unit_price;
        subtotal += lineTotal;
        totalTax += lineTotal * (item.tax_rate / 100);
    });
    var discount = parseFloat(document.getElementById('discountAmount').value) || 0;
    var total = subtotal - discount + totalTax;
    if (total < 0) total = 0;

    document.getElementById('subtotalDisplay').textContent = subtotal.toFixed(2);
    document.getElementById('discountDisplay').textContent = '- ' + discount.toFixed(2);
    document.getElementById('taxDisplay').textContent = totalTax.toFixed(2);
    document.getElementById('totalDisplay').textContent = total.toFixed(2);
}

// --- Customer ---
function switchCustomerType(type) {
    currentCustomerType = type;
    document.getElementById('customerType').value = type;

    document.querySelectorAll('.customer-tab').forEach(function(btn) {
        if (btn.getAttribute('data-type') === type) {
            btn.style.background = '#0D7377';
            btn.style.color = '#fff';
        } else {
            btn.style.background = '#fff';
            btn.style.color = '#6B7280';
        }
    });

    if (type === 'guest') {
        document.getElementById('customerSearchSection').style.display = 'none';
        document.getElementById('guestSection').style.display = 'block';
    } else {
        document.getElementById('customerSearchSection').style.display = 'block';
        document.getElementById('guestSection').style.display = 'none';
    }
    clearCustomer();
}

var customerSearchTimeout = null;
document.getElementById('customerSearchInput').addEventListener('input', function() {
    var q = this.value.trim();
    clearTimeout(customerSearchTimeout);
    if (q.length < 2) {
        document.getElementById('customerResults').style.display = 'none';
        return;
    }
    customerSearchTimeout = setTimeout(function() { searchCustomers(q); }, 300);
});

function searchCustomers(q) {
    var type = currentCustomerType;
    fetch('/sales/search-customers?q=' + encodeURIComponent(q) + '&type=' + encodeURIComponent(type))
        .then(function(r) { return r.json(); })
        .then(function(data) {
            var container = document.getElementById('customerResults');
            if (!data.results || data.results.length === 0) {
                container.innerHTML = '<div style="padding:15px;text-align:center;color:#9CA3AF;font-size:13px;">لا توجد نتائج</div>';
                container.style.display = 'block';
                return;
            }
            var html = '';
            data.results.forEach(function(c) {
                var subtitle = type === 'member' ? (c.membership_number || c.form_number || '') : (c.player_code || '');
                html += '<div style="padding:10px 15px;border-bottom:1px solid #F3F4F6;cursor:pointer;transition:background 0.1s;" ' +
                    'onmouseover="this.style.background=\'#F0FDF4\'" onmouseout="this.style.background=\'\'" ' +
                    'onclick="selectCustomer(' + c.id + ', \'' + escapeHtml(c.full_name_ar) + '\')">' +
                    '<div style="font-weight:600;font-size:13px;">' + escapeHtml(c.full_name_ar) + '</div>' +
                    (subtitle ? '<div style="font-size:11px;color:#9CA3AF;">' + escapeHtml(subtitle) + '</div>' : '') +
                    '</div>';
            });
            container.innerHTML = html;
            container.style.display = 'block';
        });
}

function selectCustomer(id, name) {
    if (currentCustomerType === 'member') {
        document.getElementById('memberId').value = id;
        document.getElementById('playerId').value = '';
    } else {
        document.getElementById('playerId').value = id;
        document.getElementById('memberId').value = '';
    }
    document.getElementById('selectedCustomerName').textContent = name;
    document.getElementById('selectedCustomer').style.display = 'block';
    document.getElementById('customerResults').style.display = 'none';
    document.getElementById('customerSearchInput').value = '';
    if (typeof lucide !== 'undefined') lucide.createIcons();
}

function clearCustomer() {
    document.getElementById('memberId').value = '';
    document.getElementById('playerId').value = '';
    document.getElementById('selectedCustomer').style.display = 'none';
    document.getElementById('customerSearchInput').value = '';
    document.getElementById('customerResults').style.display = 'none';
}

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