<?php
/**
 * @var array $categories
 * @var array $services
 * @var array $products
 * @var array $employees
 * @var array $customers
 * @var array $cart
 */
?>
<style>
.pos-wrapper { display: flex; gap: 1rem; min-height: calc(100vh - var(--navbar-height) - 80px); }
.pos-left { flex: 1; min-width: 0; display: flex; flex-direction: column; }
.pos-left .glass-card { flex: 1; display: flex; flex-direction: column; }
.pos-right { width: 420px; flex-shrink: 0; display: flex; flex-direction: column; }
.pos-right .glass-card { flex: 1; display: flex; flex-direction: column; }
@media (max-width: 992px) {
  .pos-wrapper { flex-direction: column; }
  .pos-right { width: 100%; }
}
.pos-search { position: relative; }
.pos-search .form-control { padding-left: 2.25rem; }
.pos-search .search-icon { position: absolute; left: 0.75rem; top: 50%; transform: translateY(-50%); color: var(--gold); z-index: 5; }
.nav-pills-pos .nav-link { color: var(--text-muted); border-radius: 0.5rem; padding: 0.4rem 0.9rem; font-size: 0.85rem; margin: 0.15rem; }
.nav-pills-pos .nav-link.active { background: var(--gold); color: #000; }
.nav-pills-pos .nav-link:hover:not(.active) { background: rgba(200, 164, 78, 0.15); }
.item-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 0.75rem; max-height: calc(100vh - var(--navbar-height) - 240px); overflow-y: auto; padding: 0.25rem; flex: 1; }
.item-card { background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.06); border-radius: 0.75rem; padding: 0.75rem; cursor: pointer; transition: all 0.2s; text-align: center; }
.item-card:hover { background: rgba(200,164,78,0.12); border-color: var(--gold); transform: translateY(-2px); }
.item-card .item-name { font-size: 0.85rem; font-weight: 600; margin-bottom: 0.25rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.item-card .item-price { font-size: 0.95rem; color: var(--gold); font-weight: 700; }
.item-card .item-badge { font-size: 0.65rem; padding: 0.1rem 0.4rem; border-radius: 0.25rem; background: rgba(200,164,78,0.25); color: var(--gold); }
.cart-items { max-height: calc(100vh - var(--navbar-height) - 360px); overflow-y: auto; flex: 1; }
.cart-item { background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.06); border-radius: 0.5rem; padding: 0.6rem 0.75rem; margin-bottom: 0.5rem; display: flex; align-items: center; gap: 0.5rem; }
.cart-item-info { flex: 1; min-width: 0; }
.cart-item-name { font-size: 0.85rem; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.cart-item-meta { font-size: 0.75rem; color: var(--text-muted); }
.cart-item-actions { display: flex; align-items: center; gap: 0.5rem; }
.cart-item-qty { display: flex; align-items: center; gap: 0.25rem; }
.cart-item-qty .qty-btn { width: 24px; height: 24px; padding: 0; display: flex; align-items: center; justify-content: center; font-size: 0.75rem; border-radius: 50%; }
.cart-item-qty .qty-val { width: 24px; text-align: center; font-size: 0.85rem; font-weight: 600; }
.btn-remove-item { color: #dc3545; background: none; border: none; padding: 0.25rem; cursor: pointer; font-size: 0.85rem; }
.summary-row { display: flex; justify-content: space-between; padding: 0.4rem 0; font-size: 0.9rem; }
.summary-row.total { font-size: 1.2rem; font-weight: 700; color: var(--gold); border-top: 1px solid rgba(255,255,255,0.1); margin-top: 0.5rem; padding-top: 0.75rem; }
.split-payment-entry { background: rgba(255,255,255,0.03); border-radius: 0.5rem; padding: 0.5rem; margin-bottom: 0.5rem; }
</style>

<div class="page-title mb-3">
    <h5><i class="fas fa-cash-register me-2 text-gold"></i>Point of Sale</h5>
</div>

<div class="pos-wrapper">
    <div class="pos-left">
        <div class="glass-card p-3">
            <div class="d-flex flex-wrap align-items-center gap-2 mb-3">
                <div class="pos-search flex-grow-1" style="max-width:300px;">
                    <i class="fas fa-search search-icon"></i>
                    <input type="text" class="form-control form-control-sm bg-transparent" id="posSearch"
                           placeholder="Search services or products..." oninput="filterItems(this.value)">
                </div>
                <div class="d-flex gap-1">
                    <button class="btn btn-sm btn-outline-gold active" data-type="services" onclick="switchTab(this,'services')">
                        <i class="fas fa-concierge-bell me-1"></i>Services
                    </button>
                    <button class="btn btn-sm btn-outline-gold" data-type="products" onclick="switchTab(this,'products')">
                        <i class="fas fa-box me-1"></i>Products
                    </button>
                </div>
            </div>

            <ul class="nav nav-pills nav-pills-pos mb-3" id="categoryTabs" role="tablist"></ul>

            <div class="item-grid" id="itemGrid"></div>
        </div>
    </div>

    <div class="pos-right">
        <div class="glass-card p-3">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h6 class="mb-0"><i class="fas fa-shopping-cart me-2 text-gold"></i>Cart (<span id="cartCount">0</span>)</h6>
                <button class="btn btn-sm btn-outline-danger" onclick="clearCart()"><i class="fas fa-trash me-1"></i>Clear</button>
            </div>

            <div class="mb-3">
                <select class="form-select form-select-sm bg-transparent" id="customerSelect">
                    <option value="">Walk-in Customer</option>
                    <?php foreach ($customers as $c): ?>
                        <option value="<?= $c->id ?>"><?= e($c->first_name . ' ' . $c->last_name . ' (' . ($c->phone ?? '') . ')') ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="cart-items" id="cartItems"></div>

            <div class="mt-3">
                <div class="summary-row">
                    <span>Subtotal</span>
                    <span id="subtotal"><?= APP_CURRENCY_SYMBOL ?> 0.00</span>
                </div>
                <div class="summary-row">
                    <span>
                        Discount
                        <button class="btn btn-link btn-sm text-gold p-0" onclick="$('#discountSection').toggleClass('d-none')">
                            <i class="fas fa-pen"></i>
                        </button>
                    </span>
                    <span id="discountDisplay"><?= APP_CURRENCY_SYMBOL ?> 0.00</span>
                </div>
                <div id="discountSection" class="d-none mb-2">
                    <div class="input-group input-group-sm mb-1">
                        <select class="form-select bg-transparent" id="discountType" style="max-width:100px;">
                            <option value="percentage">%</option>
                            <option value="fixed">Fixed</option>
                        </select>
                        <input type="number" class="form-control bg-transparent" id="discountValue" min="0" step="0.01"
                               placeholder="Discount" oninput="calculateTotals()">
                    </div>
                    <div class="input-group input-group-sm">
                        <input type="text" class="form-control bg-transparent" id="couponCode" placeholder="Coupon code">
                        <button class="btn btn-sm btn-gold" onclick="applyCoupon()">Apply</button>
                    </div>
                    <small class="text-success d-none" id="couponMsg"></small>
                </div>
                <div class="summary-row">
                    <span>Tax (<?= (int)APP_TAX_RATE ?>%)</span>
                    <span id="tax"><?= APP_CURRENCY_SYMBOL ?> 0.00</span>
                </div>
                <div class="summary-row total">
                    <span>Grand Total</span>
                    <span id="grandTotal"><?= APP_CURRENCY_SYMBOL ?> 0.00</span>
                </div>
            </div>

            <div class="mt-3">
                <div class="d-flex align-items-center gap-2 mb-2">
                    <h6 class="mb-0"><i class="fas fa-credit-card me-1 text-gold"></i>Payment</h6>
                    <button class="btn btn-sm btn-outline-gold" onclick="addSplitPayment()"><i class="fas fa-plus"></i></button>
                </div>
                <div id="splitPayments"></div>
                <div class="d-flex gap-2 mt-2">
                    <button class="btn btn-gold flex-grow-1" onclick="checkout()">
                        <i class="fas fa-check-circle me-1"></i>Checkout
                    </button>
                    <a href="<?= url('pos/new') ?>" class="btn btn-outline-secondary">
                        <i class="fas fa-plus"></i>
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
$appUrl = rtrim(APP_URL, '/');
$currencySymbol = APP_CURRENCY_SYMBOL;
$taxRate = (int)APP_TAX_RATE;
ob_start();
?>
var cart = {};
var services = <?= json_encode(array_values($services)) ?>;
var products = <?= json_encode(array_values($products)) ?>;
var employees = <?= json_encode(array_values($employees)) ?>;
var csrfToken = $('meta[name="csrf-token"]').attr('content');
var appUrl = '<?= $appUrl ?>';
var currencySymbol = '<?= $currencySymbol ?>';
var taxRate = <?= $taxRate ?>;
var couponDiscount = 0;
var couponCode = '';
var splitPaymentIndex = 0;

function init() {
    renderCategories();
    renderItems('services', '');
    renderCart();
    addSplitPayment();
    var urlParams = new URLSearchParams(window.location.search);
    var aptId = urlParams.get('appointment_id');
    if (aptId) {
        loadAppointment(aptId);
    }
}

function renderCategories() {
    var cats = [];
    var catNames = {};
    services.forEach(function(s) {
        if (s.category_id && cats.indexOf(s.category_id) === -1) {
            cats.push(s.category_id);
            catNames[s.category_id] = s.category_name || '';
        }
    });
    var html = '<li class="nav-item"><button class="nav-link active" data-category="" onclick="filterByCategory(this,\'\')">All</button></li>';
    cats.forEach(function(cid) {
        if (cid && catNames[cid]) {
            html += '<li class="nav-item"><button class="nav-link" data-category="'+cid+'" onclick="filterByCategory(this,'+cid+')">'+catNames[cid]+'</button></li>';
        }
    });
    document.getElementById('categoryTabs').innerHTML = html;
}

var currentTab = 'services';
var currentCategory = '';

function switchTab(btn, tab) {
    document.querySelectorAll('[data-type]').forEach(function(b) { b.classList.remove('active'); });
    btn.classList.add('active');
    currentTab = tab;
    currentCategory = '';
    document.querySelectorAll('#categoryTabs .nav-link').forEach(function(l) { l.classList.remove('active'); });
    var allBtn = document.querySelector('#categoryTabs .nav-link[data-category=""]');
    if (allBtn) allBtn.classList.add('active');
    renderItems(tab, '');
}

function filterByCategory(btn, catId) {
    document.querySelectorAll('#categoryTabs .nav-link').forEach(function(l) { l.classList.remove('active'); });
    btn.classList.add('active');
    currentCategory = catId;
    renderItems(currentTab, '');
}

function filterItems(query) {
    renderItems(currentTab, query);
}

function renderItems(tab, query) {
    var data = tab === 'services' ? services : products;
    var grid = document.getElementById('itemGrid');
    var filtered = data;
    if (currentCategory && tab === 'services') {
        filtered = filtered.filter(function(s) { return String(s.category_id) === String(currentCategory); });
    }
    if (query) {
        var q = query.toLowerCase();
        filtered = filtered.filter(function(i) { return (i.name || '').toLowerCase().includes(q); });
    }
    if (filtered.length === 0) {
        grid.innerHTML = '<div class="text-center text-muted py-5"><i class="fas fa-search fa-2x mb-2"></i><p class="mb-0">No items found</p></div>';
        return;
    }
    var html = '';
    filtered.forEach(function(item) {
        var price = tab === 'services' ? item.price : (item.unit_price || 0);
        var label = tab === 'services' ? 'Service' : 'Product';
        html += '<div class="item-card" onclick="addToCart(\''+tab+'\','+item.id+')">' +
            '<div class="item-name">'+item.name+'</div>' +
            '<div class="item-price">'+currencySymbol+' '+parseFloat(price).toFixed(2)+'</div>' +
            '<div class="item-badge">'+label+'</div>' +
            '</div>';
    });
    grid.innerHTML = html;
}

function addToCart(type, id) {
    var data = type === 'services' ? services : products;
    var item = data.find(function(i) { return String(i.id) === String(id); });
    if (!item) return;
    var key = type + '_' + id;
    if (cart[key]) {
        cart[key].quantity += 1;
    } else {
        var price = type === 'services' ? item.price : (item.unit_price || item.price || 0);
        cart[key] = {
            type: type,
            id: id,
            name: item.name,
            price: parseFloat(price),
            quantity: 1,
            employee_id: type === 'services' && employees.length > 0 ? String(employees[0].id) : ''
        };
    }
    renderCart();
    calculateTotals();
    var grid = document.getElementById('itemGrid');
    grid.style.transition = 'transform 0.1s';
    grid.style.transform = 'scale(0.99)';
    setTimeout(function() { grid.style.transform = 'scale(1)'; }, 100);
}

function removeFromCart(key) {
    delete cart[key];
    renderCart();
    calculateTotals();
}

function updateQty(key, delta) {
    if (!cart[key]) return;
    cart[key].quantity = Math.max(1, (cart[key].quantity || 1) + delta);
    renderCart();
    calculateTotals();
}

function renderCart() {
    var container = document.getElementById('cartItems');
    var keys = Object.keys(cart);
    document.getElementById('cartCount').textContent = keys.reduce(function(s, k) { return s + cart[k].quantity; }, 0);
    if (keys.length === 0) {
        container.innerHTML = '<div class="text-center text-muted py-4"><i class="fas fa-shopping-cart fa-2x mb-2"></i><p class="mb-0">Cart is empty</p></div>';
        return;
    }
    var html = '';
    keys.forEach(function(key) {
        var item = cart[key];
        var lineTotal = item.price * item.quantity;
        html += '<div class="cart-item">' +
            '<div class="cart-item-info">' +
            '<div class="cart-item-name">'+item.name+'</div>' +
            '<div class="cart-item-meta">'+currencySymbol+' '+item.price.toFixed(2)+' x '+item.quantity+' = '+currencySymbol+' '+lineTotal.toFixed(2)+'</div>';
        if (item.type === 'services') {
            html += '<select class="form-select form-select-sm bg-transparent mt-1" style="font-size:0.75rem;" onchange="cart[\''+key+'\'].employee_id=this.value">' +
                '<option value="">Select Employee</option>';
            employees.forEach(function(emp) {
                var sel = String(emp.id) === String(item.employee_id) ? ' selected' : '';
                html += '<option value="'+emp.id+'"'+sel+'>'+emp.first_name+' '+emp.last_name+'</option>';
            });
            html += '</select>';
        }
        html += '</div>' +
            '<div class="cart-item-actions">' +
            '<div class="cart-item-qty">' +
            '<button class="btn btn-sm btn-outline-gold qty-btn" onclick="updateQty(\''+key+'\',-1)"><i class="fas fa-minus"></i></button>' +
            '<span class="qty-val">'+item.quantity+'</span>' +
            '<button class="btn btn-sm btn-outline-gold qty-btn" onclick="updateQty(\''+key+'\',1)"><i class="fas fa-plus"></i></button>' +
            '</div>' +
            '<button class="btn-remove-item" onclick="removeFromCart(\''+key+'\')"><i class="fas fa-times"></i></button>' +
            '</div>' +
            '</div>';
    });
    container.innerHTML = html;
}

function calculateTotals() {
    var subtotal = 0;
    Object.keys(cart).forEach(function(k) { subtotal += cart[k].price * cart[k].quantity; });
    var discountType = document.getElementById('discountType').value;
    var discountVal = parseFloat(document.getElementById('discountValue').value) || 0;
    var discount = 0;
    if (discountType === 'percentage' && discountVal > 0) {
        discount = (subtotal * discountVal) / 100;
    } else if (discountType === 'fixed' && discountVal > 0) {
        discount = Math.min(discountVal, subtotal);
    }
    discount += couponDiscount;
    discount = Math.min(discount, subtotal);
    var tax = 0;
    if (taxRate > 0) {
        tax = ((subtotal - discount) * taxRate) / 100;
    }
    var grandTotal = Math.max(0, subtotal - discount + tax);
    document.getElementById('subtotal').textContent = currencySymbol+' '+subtotal.toFixed(2);
    document.getElementById('discountDisplay').textContent = currencySymbol+' '+discount.toFixed(2);
    document.getElementById('tax').textContent = currencySymbol+' '+tax.toFixed(2);
    document.getElementById('grandTotal').textContent = currencySymbol+' '+grandTotal.toFixed(2);
    var count = 0;
    Object.keys(cart).forEach(function(k) { count += cart[k].quantity; });
    document.getElementById('cartCount').textContent = count;
    var payTotal = 0;
    document.querySelectorAll('[id^="payAmount"]').forEach(function(inp) { payTotal += parseFloat(inp.value) || 0; });
}

function applyCoupon() {
    var code = document.getElementById('couponCode').value.trim();
    if (!code) return;
    var subtotal = 0;
    Object.keys(cart).forEach(function(k) { subtotal += cart[k].price * cart[k].quantity; });
    $.post(appUrl + '/pos/validate-coupon', {
        code: code,
        subtotal: subtotal,
        _csrf_token: csrfToken
    }, function(res) {
        if (res.success) {
            couponDiscount = res.data.discount;
            couponCode = code;
            document.getElementById('couponMsg').textContent = 'Coupon applied: -'+currencySymbol+' '+couponDiscount.toFixed(2);
            document.getElementById('couponMsg').classList.remove('d-none');
            document.getElementById('couponMsg').className = 'text-success';
            calculateTotals();
        }
    }).fail(function(xhr) {
        var resp = xhr.responseJSON;
        document.getElementById('couponMsg').textContent = resp ? resp.message : 'Invalid coupon';
        document.getElementById('couponMsg').classList.remove('d-none');
        document.getElementById('couponMsg').className = 'text-danger';
    });
}

function clearCart() {
    if (!Object.keys(cart).length) return;
    if (!confirm('Clear all items from cart?')) return;
    cart = {};
    couponDiscount = 0;
    couponCode = '';
    document.getElementById('couponCode').value = '';
    document.getElementById('couponMsg').classList.add('d-none');
    renderCart();
    calculateTotals();
}

function loadAppointment(aptId) {
    $('#loading-overlay').show();
    $.get(appUrl + '/pos/load-appointment/' + aptId, function(res) {
        if (res.success && res.data) {
            var data = res.data;
            if (data.existing_invoice_id) {
                window.location.href = appUrl + '/invoices/' + data.existing_invoice_id;
                return;
            }
            if (data.customer_id) {
                document.getElementById('customerSelect').value = data.customer_id;
            }
            cart = {};
            var hasItems = false;
            if (data.cart) {
                Object.keys(data.cart).forEach(function(k) {
                    cart[k] = data.cart[k];
                    if (data.cart[k].quantity > 0) hasItems = true;
                });
            }
            renderCart();
            calculateTotals();
            if (!hasItems) {
                alert('This appointment has no services to bill. Add items manually or close this sale.');
            }
        }
    }).fail(function(xhr) {
        var resp = xhr.responseJSON;
        alert(resp ? resp.message : 'Failed to load appointment');
    }).always(function() {
        $('#loading-overlay').hide();
    });
}

function addSplitPayment() {
    var container = document.getElementById('splitPayments');
    var idx = splitPaymentIndex++;
    var html = '<div class="split-payment-entry" id="paymentEntry'+idx+'">' +
        '<div class="row g-1 align-items-center">' +
        '<div class="col-4">' +
        '<select class="form-select form-select-sm bg-transparent" id="payMethod'+idx+'">' +
        '<option value="cash">Cash</option>' +
        '<option value="card">Card</option>' +
        '<option value="bank_transfer">Bank Transfer</option>' +
        '<option value="gift_card">Gift Card</option>' +
        '</select>' +
        '</div>' +
        '<div class="col-4">' +
        '<input type="number" class="form-control form-control-sm bg-transparent" id="payAmount'+idx+'" placeholder="Amount" min="0" step="0.01" oninput="calculateTotals()">' +
        '</div>' +
        '<div class="col-3">' +
        '<input type="text" class="form-control form-control-sm bg-transparent" id="payRef'+idx+'" placeholder="Ref">' +
        '</div>' +
        '<div class="col-1">' +
        '<button class="btn btn-sm btn-outline-danger" onclick="removeSplitPayment('+idx+')"><i class="fas fa-times"></i></button>' +
        '</div>' +
        '</div>' +
        '</div>';
    container.insertAdjacentHTML('beforeend', html);
}

function removeSplitPayment(idx) {
    var el = document.getElementById('paymentEntry'+idx);
    if (el) el.remove();
    calculateTotals();
}

function checkout() {
    var keys = Object.keys(cart);
    if (keys.length === 0) { alert('Cart is empty.'); return; }
    var payments = [];
    document.querySelectorAll('[id^="paymentEntry"]').forEach(function(el) {
        var idx = el.id.replace('paymentEntry', '');
        var method = document.getElementById('payMethod'+idx) ? document.getElementById('payMethod'+idx).value : '';
        var amount = parseFloat(document.getElementById('payAmount'+idx) ? document.getElementById('payAmount'+idx).value : 0) || 0;
        var reference = document.getElementById('payRef'+idx) ? document.getElementById('payRef'+idx).value : '';
        if (amount > 0) {
            payments.push({ method: method, amount: amount, reference: reference });
        }
    });
    if (payments.length === 0) { alert('Add at least one payment.'); return; }
    var data = {
        customer_id: document.getElementById('customerSelect').value,
        discount_type: document.getElementById('discountType').value,
        discount_value: document.getElementById('discountValue').value || 0,
        coupon_code: couponCode,
        coupon_discount: couponDiscount,
        payments: payments,
        cart_items: JSON.stringify(Object.keys(cart).map(function(k) { return cart[k]; })),
        appointment_id: new URLSearchParams(window.location.search).get('appointment_id') || '',
        _csrf_token: csrfToken
    };
    $('#loading-overlay').show();
    $.post(appUrl + '/pos/checkout', data, function(res) {
        if (res.success) {
            cart = {};
            couponDiscount = 0;
            couponCode = '';
            renderCart();
            calculateTotals();
            window.location.href = appUrl + '/pos/invoice/' + res.data.invoice_id;
        }
    }).fail(function(xhr) {
        var resp = xhr.responseJSON;
        alert(resp ? resp.message : 'Checkout failed');
    }).always(function() {
        $('#loading-overlay').hide();
    });
}

init();

// expose functions to global scope for inline onclick handlers
window.addToCart = addToCart;
window.removeFromCart = removeFromCart;
window.updateQty = updateQty;
window.renderCart = renderCart;
window.calculateTotals = calculateTotals;
window.switchTab = switchTab;
window.filterByCategory = filterByCategory;
window.filterItems = filterItems;
window.clearCart = clearCart;
window.checkout = checkout;
window.addSplitPayment = addSplitPayment;
window.removeSplitPayment = removeSplitPayment;
window.applyCoupon = applyCoupon;
window.loadAppointment = loadAppointment;
<?php $inlineScripts = ob_get_clean(); ?>
