<?php include 'auth_check.php'; ?>
<!DOCTYPE html>
<html>
<head>
    <title>Krushi Sewa Piyasa-Sale</title>
    <link rel="stylesheet" href="assets/style.css">
    <style>
        #saleProductSearch:focus,
        #received_amount:focus,
        #billTable input:focus,
        #billTable button:focus,
        #billTable td.focusable-cell:focus,
        .mode-option-btn:focus,
        .mode-close-btn:focus,
        .warning-popup-btn:focus {
            outline: 2px solid #1f7a3f;
            outline-offset: -2px;
        }
        .suggestion-item.active-suggestion { background: #dff3e5; font-weight: bold; }
        #billTable td.focusable-cell { cursor: pointer; }
        .print-frame { position: absolute; width: 0; height: 0; border: 0; visibility: hidden; }
        .sale-top-actions { display: grid; grid-template-columns: minmax(240px, 1fr) auto auto; gap: 10px; align-items: center; margin-bottom: 8px; }
        .sale-top-actions button { padding: 10px 14px; border: none; border-radius: 10px; cursor: pointer; background: #1f7a3f; color: #fff; font-size: 0.95rem; font-weight: 600; }
        .sale-top-actions button:hover { background: #186233; }
        .sale-amount-panel { margin-top: 14px; border-top: 1px solid #d9e2ea; padding-top: 14px; }
        .sale-amount-grid { display: grid; grid-template-columns: 1fr; gap: 10px; }
        .sale-amount-row { display: grid; grid-template-columns: 220px minmax(220px, 320px); gap: 12px; align-items: center; }
        .sale-amount-row label { font-size: 1.02rem; font-weight: 700; color: #222; }
        .sale-amount-row input { width: 100%; padding: 12px 14px; border: 1px solid #cfd8dc; border-radius: 10px; background: #fff; font-weight: 700; text-align: right; }
        .sale-amount-row.total-row input { color: #000000; font-size: 1.08rem; }
        .sale-amount-row.discount-row input { color: #1f4fb8; font-size: 1.08rem; }
        .sale-amount-row.net-row label, .sale-amount-row.received-row label, .sale-amount-row.balance-row label { font-size: 1.08rem; }
        .sale-amount-row.net-row input { color: #c9302c; font-size: 1.18rem; }
        .sale-amount-row.received-row input { color: #000000; font-size: 1.18rem; }
        .sale-amount-row.balance-row input { color: #1f7a3f; font-size: 1.18rem; }

        .mode-select-backdrop,
        .warning-popup-backdrop {
            position: fixed; inset: 0; background: rgba(0,0,0,0.45); display: none;
            align-items: center; justify-content: center; z-index: 9999; padding: 16px;
        }
        .mode-select-backdrop.show,
        .warning-popup-backdrop.show { display: flex; }

        .mode-select-box { width: 100%; max-width: 430px; background: #ffffff; border-radius: 18px; box-shadow: 0 16px 40px rgba(0,0,0,0.22); padding: 20px; }
        .mode-select-box h3 { margin-bottom: 8px; color: #1f7a3f; font-size: 1.15rem; }
        .mode-select-product { margin-bottom: 14px; color: #333; font-weight: 700; }
        .mode-select-grid { display: grid; gap: 12px; }
        .mode-option-btn { border: 1px solid #d4e0d8; background: #f8fbf9; border-radius: 14px; padding: 14px; text-align: left; cursor: pointer; transition: 0.15s ease; }
        .mode-option-btn:hover,
        .mode-option-btn.active-mode-option { background: #eef7f1; border-color: #1f7a3f; }
        .mode-option-title { font-weight: 700; color: #1f7a3f; margin-bottom: 4px; font-size: 1rem; }
        .mode-option-meta { color: #555; font-size: 0.92rem; line-height: 1.35; }
        .mode-close-row { margin-top: 14px; text-align: right; }
        .mode-close-btn { padding: 10px 14px; border: none; border-radius: 10px; cursor: pointer; background: #888; color: #fff; font-size: 0.92rem; font-weight: 600; }
        .mode-close-btn:hover { background: #666; }

        .warning-popup-box {
            width: 100%;
            max-width: 420px;
            background: #fff;
            border-radius: 18px;
            box-shadow: 0 16px 40px rgba(0,0,0,0.22);
            padding: 24px 20px 18px;
            text-align: center;
        }
        .warning-popup-title {
            color: #c9302c;
            font-size: 1.12rem;
            font-weight: 700;
            margin-bottom: 10px;
        }
        .warning-popup-text {
            color: #333;
            font-size: 1rem;
            margin-bottom: 16px;
            line-height: 1.4;
        }
        .warning-popup-btn {
            padding: 10px 18px;
            border: none;
            border-radius: 10px;
            background: #1f7a3f;
            color: #fff;
            font-size: 0.95rem;
            font-weight: 700;
            cursor: pointer;
        }
        .warning-popup-btn:hover { background: #186233; }

        .sale-mode-badge { display: inline-block; padding: 4px 8px; border-radius: 999px; font-size: 0.78rem; background: #e9f5ed; color: #1f7a3f; margin-top: 4px; font-weight: 700; }
        @media (max-width: 900px) { .sale-top-actions { grid-template-columns: 1fr; } .sale-amount-row { grid-template-columns: 1fr; } }
    </style>
</head>
<body>
<div class="layout">
    <?php renderSidebar('sale'); ?>
    <main class="main-content">
        <div class="topbar">Logged User: <?php echo $_SESSION['name']; ?> | <?php echo $_SESSION['user_category']; ?></div>
        <div class="form-card">
            <h2>Billing Page</h2>

            <div class="sale-top-actions">
                <input type="text" id="saleProductSearch" placeholder="Search Product Name" autocomplete="off">
                <button type="button" onclick="finalizeBill()" id="finalize_button">Finalize Bill</button>
                <button type="button" onclick="printLastBill()" id="print_last_bill_button">Print Last Bill</button>
            </div>

            <div id="saleSuggestions" class="suggestions"></div>

            <div class="bill-table-wrap">
                <table id="billTable">
                    <thead>
                        <tr><th>Product</th><th>Unit / Mode</th><th>Unit Price</th><th>Qty</th><th>Discount</th><th>Total</th><th>Action</th></tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>

            <div class="sale-amount-panel">
                <div class="sale-amount-grid">
                    <div class="sale-amount-row total-row"><label for="total_amount">Total Amount</label><input type="text" id="total_amount" readonly></div>
                    <div class="sale-amount-row discount-row"><label for="discount_amount">Discounts</label><input type="text" id="discount_amount" readonly></div>
                    <div class="sale-amount-row net-row"><label for="net_total_amount">Net Total Amount</label><input type="text" id="net_total_amount" readonly></div>
                    <div class="sale-amount-row received-row"><label for="received_amount">Received Amount</label><input type="text" id="received_amount" inputmode="decimal" autocomplete="off" placeholder="Received Amount"></div>
                    <div class="sale-amount-row balance-row"><label for="balance_amount">Balance Amount</label><input type="text" id="balance_amount" readonly></div>
                </div>
            </div>
        </div>
    </main>
</div>

<div class="mode-select-backdrop" id="modeSelectBackdrop">
    <div class="mode-select-box">
        <h3>Which selling mode do you want to use?</h3>
        <div class="mode-select-product" id="modeSelectProductName"></div>
        <div class="mode-select-grid">
            <button type="button" class="mode-option-btn" id="modeOptionOneBtn"></button>
            <button type="button" class="mode-option-btn" id="modeOptionTwoBtn"></button>
        </div>
        <div class="mode-close-row">
            <button type="button" class="mode-close-btn" id="modeCloseBtn" onclick="closeModeSelector()">Cancel</button>
        </div>
    </div>
</div>

<div class="warning-popup-backdrop" id="warningPopupBackdrop">
    <div class="warning-popup-box">
        <div class="warning-popup-title">Warning</div>
        <div class="warning-popup-text">Enter Received Amount, Cannot Proceed Bill</div>
        <button type="button" class="warning-popup-btn" id="warningPopupBtn" onclick="closeWarningPopup()">OK</button>
    </div>
</div>

<script>
let cart = [];
let activeSuggestionIndex = -1;
let lastBillNumber = <?php echo isset($_SESSION['last_bill_number']) ? json_encode($_SESSION['last_bill_number']) : 'null'; ?>;
let modeOptionIndex = 0;
let modeOptionButtons = [];

document.addEventListener('DOMContentLoaded', function () {
    focusProductSearch();
    initializeModeKeyboard();
    initializeWarningPopupKeyboard();
});

const saleProductSearch = document.getElementById('saleProductSearch');
const saleSuggestions = document.getElementById('saleSuggestions');
const billTable = document.getElementById('billTable');
const receivedAmount = document.getElementById('received_amount');

saleProductSearch.addEventListener('keyup', function(e) {
    if (['ArrowDown', 'ArrowUp', 'Enter', 'Tab', 'ArrowLeft', 'ArrowRight'].includes(e.key)) return;
    const keyword = this.value.trim();
    if (keyword.length < 1) { saleSuggestions.innerHTML = ''; activeSuggestionIndex = -1; return; }
    fetch('stock.php?ajax=1&keyword=' + encodeURIComponent(keyword))
    .then(res => res.text())
    .then(data => { saleSuggestions.innerHTML = data; activeSuggestionIndex = -1; refreshSuggestionState(); });
});

saleProductSearch.addEventListener('keydown', function(e) {
    const items = getSuggestionItems();
    if (e.key === 'ArrowDown' && items.length > 0) { e.preventDefault(); activeSuggestionIndex = (activeSuggestionIndex + 1) % items.length; refreshSuggestionState(); }
    if (e.key === 'ArrowUp' && items.length > 0) { e.preventDefault(); activeSuggestionIndex = activeSuggestionIndex <= 0 ? items.length - 1 : activeSuggestionIndex - 1; refreshSuggestionState(); }
    if (e.key === 'Enter' && items.length > 0 && activeSuggestionIndex >= 0) { e.preventDefault(); items[activeSuggestionIndex].click(); }
    if (e.key === 'Tab' && items.length > 0 && activeSuggestionIndex >= 0) { e.preventDefault(); items[activeSuggestionIndex].click(); }
    if (e.key === 'ArrowRight' && cart.length > 0) { e.preventDefault(); focusBillCell(0, 0); }
    if (e.key === 'ArrowDown' && items.length === 0 && cart.length > 0) { e.preventDefault(); focusBillCell(0, 0); }
});

receivedAmount.addEventListener('input', calculateBalance);
receivedAmount.addEventListener('keydown', function(e) {
    if (e.key === 'ArrowUp') {
        e.preventDefault();
        if (cart.length > 0) {
            focusBillCell(cart.length - 1, 6);
        } else {
            focusProductSearch();
        }
        return;
    }
    if (e.key === 'ArrowDown') {
        e.preventDefault();
        return;
    }
    if (e.key === 'ArrowLeft') {
        e.preventDefault();
        focusProductSearch();
        return;
    }
    if (e.key === 'ArrowRight') {
        e.preventDefault();
        return;
    }
    if (e.key === 'Enter' || e.key === 'Tab') { e.preventDefault(); finalizeBill(); }
});

billTable.addEventListener('keydown', function(e) {
    const target = e.target;
    const row = parseInt(target.dataset.rowIndex || '-1', 10);
    const col = parseInt(target.dataset.colIndex || '-1', 10);
    if (row < 0 || col < 0) return;
    if (e.key === 'ArrowRight') { e.preventDefault(); focusBillCell(row, col + 1); }
    if (e.key === 'ArrowLeft') { e.preventDefault(); if (col === 0) { focusProductSearch(); } else { focusBillCell(row, col - 1); } }
    if (e.key === 'ArrowDown') { e.preventDefault(); focusBillCell(row + 1, col); }
    if (e.key === 'ArrowUp') { e.preventDefault(); if (row === 0) { focusProductSearch(); } else { focusBillCell(row - 1, col); } }
    if (e.key === 'Enter' && target.classList.contains('remove-btn')) { e.preventDefault(); target.click(); }
    if (e.key === 'Tab' && target.classList.contains('remove-btn') && row === cart.length - 1) { e.preventDefault(); receivedAmount.focus(); receivedAmount.select(); }
});

function getSuggestionItems() { return Array.from(document.querySelectorAll('#saleSuggestions .suggestion-item')); }
function refreshSuggestionState() {
    const items = getSuggestionItems();
    items.forEach((item, index) => {
        if (index === activeSuggestionIndex) { item.classList.add('active-suggestion'); item.scrollIntoView({ block: 'nearest' }); }
        else { item.classList.remove('active-suggestion'); }
    });
}
function focusProductSearch() { saleProductSearch.focus(); saleProductSearch.select(); }

function selectProductForSale(element) {
    const product = {
        product_name: element.dataset.product_name || '',
        standard_price: parseFloat(element.dataset.standard_price || '0'),
        unit: element.dataset.unit || '',
        is_dual_mode: element.dataset.is_dual_mode === '1',
        dual_mode_name_1: sanitizeModeValue(element.dataset.dual_mode_name_1 || ''),
        dual_mode_qty_1: parseFloat(element.dataset.dual_mode_qty_1 || '0'),
        dual_mode_price_1: parseFloat(element.dataset.dual_mode_price_1 || '0'),
        dual_mode_name_2: sanitizeModeValue(element.dataset.dual_mode_name_2 || ''),
        dual_mode_qty_2: parseFloat(element.dataset.dual_mode_qty_2 || '0'),
        dual_mode_price_2: parseFloat(element.dataset.dual_mode_price_2 || '0')
    };

    if (!product.is_dual_mode) {
        addToBill({
            product_name: product.product_name,
            selling_price: product.standard_price,
            unit: product.unit,
            qty: 1,
            discount: 0,
            selling_mode: 'standard',
            selling_mode_label: product.unit || 'Standard',
            stock_deduct_qty_per_unit: 1,
            qty_step: 0.01
        });
        return;
    }
    openModeSelector(product);
}

function initializeModeKeyboard() {
    const backdrop = document.getElementById('modeSelectBackdrop');
    backdrop.addEventListener('keydown', function(e) {
        if (!backdrop.classList.contains('show')) return;

        if (e.key === 'ArrowDown' || e.key === 'ArrowRight') {
            e.preventDefault();
            modeOptionIndex = (modeOptionIndex + 1) % modeOptionButtons.length;
            refreshModeOptionFocus();
        }
        if (e.key === 'ArrowUp' || e.key === 'ArrowLeft') {
            e.preventDefault();
            modeOptionIndex = modeOptionIndex <= 0 ? modeOptionButtons.length - 1 : modeOptionIndex - 1;
            refreshModeOptionFocus();
        }
        if (e.key === 'Enter') {
            e.preventDefault();
            if (modeOptionButtons[modeOptionIndex]) {
                modeOptionButtons[modeOptionIndex].click();
            }
        }
        if (e.key === 'Escape') {
            e.preventDefault();
            closeModeSelector();
        }
    });
}

function initializeWarningPopupKeyboard() {
    const popup = document.getElementById('warningPopupBackdrop');
    popup.addEventListener('keydown', function(e) {
        if (!popup.classList.contains('show')) return;
        if (e.key === 'Enter' || e.key === 'Escape') {
            e.preventDefault();
            closeWarningPopup();
        }
    });
}

function openModeSelector(product) {
    document.getElementById('modeSelectProductName').textContent = product.product_name;
    const optionOneBtn = document.getElementById('modeOptionOneBtn');
    optionOneBtn.innerHTML = `
        <div class="mode-option-title">${escapeHtml(product.dual_mode_name_1)}</div>
        <div class="mode-option-meta">Qty Reduction: ${formatNumber(product.dual_mode_qty_1)} ${escapeHtml(product.unit)}<br>Selling Price: Rs. ${formatMoney(product.dual_mode_price_1)}</div>
    `;
    optionOneBtn.onclick = function() {
        addToBill({
            product_name: product.product_name,
            selling_price: product.dual_mode_price_1,
            unit: product.dual_mode_name_1,
            qty: 1,
            discount: 0,
            selling_mode: 'mode_1',
            selling_mode_label: product.dual_mode_name_1,
            stock_deduct_qty_per_unit: product.dual_mode_qty_1,
            qty_step: 1
        });
        closeModeSelector();
    };

    const optionTwoBtn = document.getElementById('modeOptionTwoBtn');
    optionTwoBtn.innerHTML = `
        <div class="mode-option-title">${escapeHtml(product.dual_mode_name_2)}</div>
        <div class="mode-option-meta">Qty Reduction: ${formatNumber(product.dual_mode_qty_2)} ${escapeHtml(product.unit)}<br>Selling Price: Rs. ${formatMoney(product.dual_mode_price_2)}</div>
    `;
    optionTwoBtn.onclick = function() {
        addToBill({
            product_name: product.product_name,
            selling_price: product.dual_mode_price_2,
            unit: product.dual_mode_name_2,
            qty: 1,
            discount: 0,
            selling_mode: 'mode_2',
            selling_mode_label: product.dual_mode_name_2,
            stock_deduct_qty_per_unit: product.dual_mode_qty_2,
            qty_step: 0.01
        });
        closeModeSelector();
    };

    modeOptionButtons = [optionOneBtn, optionTwoBtn];
    modeOptionIndex = 0;
    document.getElementById('modeSelectBackdrop').classList.add('show');
    refreshModeOptionFocus();
}
function refreshModeOptionFocus() {
    modeOptionButtons.forEach((btn, index) => {
        btn.classList.toggle('active-mode-option', index === modeOptionIndex);
    });
    if (modeOptionButtons[modeOptionIndex]) {
        modeOptionButtons[modeOptionIndex].focus();
    }
}
function closeModeSelector() {
    document.getElementById('modeSelectBackdrop').classList.remove('show');
    focusProductSearch();
}

function openWarningPopup() {
    const popup = document.getElementById('warningPopupBackdrop');
    popup.classList.add('show');
    document.getElementById('warningPopupBtn').focus();
}
function closeWarningPopup() {
    document.getElementById('warningPopupBackdrop').classList.remove('show');
    receivedAmount.focus();
    receivedAmount.select();
}

function addToBill(itemData) {
    cart.push(itemData);
    renderBill();
    saleSuggestions.innerHTML = '';
    saleProductSearch.value = '';
    activeSuggestionIndex = -1;
    focusProductSearch();
}

function renderBill() {
    let tbody = document.querySelector('#billTable tbody');
    tbody.innerHTML = '';
    let grossTotal = 0;
    let totalDiscount = 0;
    cart.forEach((item, index) => {
        const itemGross = item.selling_price * item.qty;
        const itemDiscount = item.discount;
        const lineTotal = itemGross - itemDiscount;
        const displayMode = sanitizeModeValue(item.selling_mode_label || item.unit || 'Standard');
        grossTotal += itemGross;
        totalDiscount += itemDiscount;

        tbody.innerHTML += `
            <tr>
                <td class="focusable-cell" tabindex="0" data-row-index="${index}" data-col-index="0">${escapeHtml(item.product_name)}<div class="sale-mode-badge">${escapeHtml(displayMode)}</div></td>
                <td class="focusable-cell" tabindex="0" data-row-index="${index}" data-col-index="1">${escapeHtml(displayMode)}</td>
                <td><input type="number" step="0.01" value="${item.selling_price}" min="0" data-row-index="${index}" data-col-index="2" onchange="updatePrice(${index}, this.value)"></td>
                <td><input type="number" step="${item.qty_step || 0.01}" value="${item.qty}" min="${item.qty_step === 1 ? 1 : 0.01}" data-row-index="${index}" data-col-index="3" onchange="updateQty(${index}, this.value)"></td>
                <td><input type="number" step="0.01" value="${item.discount}" min="0" data-row-index="${index}" data-col-index="4" onchange="updateDiscount(${index}, this.value)"></td>
                <td class="focusable-cell" tabindex="0" data-row-index="${index}" data-col-index="5">${lineTotal.toFixed(2)}</td>
                <td><button type="button" class="remove-btn" data-row-index="${index}" data-col-index="6" onclick="removeBillItem(${index})">Remove</button></td>
            </tr>`;
    });
    const netTotal = grossTotal - totalDiscount;
    document.getElementById('total_amount').value = grossTotal.toFixed(2);
    document.getElementById('discount_amount').value = totalDiscount.toFixed(2);
    document.getElementById('net_total_amount').value = netTotal.toFixed(2);
    calculateBalance();
}

function focusBillCell(row, col) {
    if (cart.length === 0) return;
    if (row < 0) row = 0;
    if (row >= cart.length) { receivedAmount.focus(); receivedAmount.select(); return; }
    if (col < 0) col = 0;
    if (col > 6) col = 6;
    const target = document.querySelector(`[data-row-index="${row}"][data-col-index="${col}"]`);
    if (target) { target.focus(); if (typeof target.select === 'function') target.select(); }
}

function updatePrice(index, value) { cart[index].selling_price = parseFloat(value) || 0; renderBill(); focusBillCell(index, 2); }
function updateQty(index, value) { cart[index].qty = parseFloat(value) || 0; renderBill(); focusBillCell(index, 3); }
function updateDiscount(index, value) { cart[index].discount = parseFloat(value) || 0; renderBill(); focusBillCell(index, 4); }
function removeBillItem(index) {
    cart.splice(index, 1);
    renderBill();
    if (cart.length > 0) focusBillCell(index >= cart.length ? cart.length - 1 : index, 0);
    else focusProductSearch();
}
function calculateBalance() {
    let netTotal = parseFloat(document.getElementById('net_total_amount').value || 0);
    let received = parseFloat(document.getElementById('received_amount').value || 0);
    document.getElementById('balance_amount').value = (received - netTotal).toFixed(2);
}
function silentPrintBill(billNumber) {
    if (!billNumber) { alert('No bill available to print.'); return; }
    const oldFrame = document.getElementById('print_iframe');
    if (oldFrame) oldFrame.remove();
    const iframe = document.createElement('iframe');
    iframe.id = 'print_iframe';
    iframe.className = 'print-frame';
    iframe.src = 'print_bill.php?bill_number=' + encodeURIComponent(billNumber);
    document.body.appendChild(iframe);
}
function printLastBill() {
    const localLastBill = localStorage.getItem('last_bill_number');
    const billNo = localLastBill || lastBillNumber;
    if (!billNo) { alert('No previous bill found.'); return; }
    silentPrintBill(billNo); focusProductSearch();
}
function finalizeBill() {
    if(cart.length === 0) { alert('No items in bill'); focusProductSearch(); return; }

    const receivedValue = document.getElementById('received_amount').value.trim();
    if (receivedValue === '') {
        openWarningPopup();
        return;
    }

    let payload = {
        cart: cart,
        total_amount: document.getElementById('net_total_amount').value,
        received_amount: receivedValue,
        balance_amount: document.getElementById('balance_amount').value
    };
    fetch('save_bill.php', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload) })
    .then(res => res.json())
    .then(data => {
        if(data.status === 'success') {
            lastBillNumber = data.bill_number;
            localStorage.setItem('last_bill_number', data.bill_number);
            silentPrintBill(data.bill_number);
            setTimeout(() => { location.reload(); }, 1200);
        } else {
            alert(data.message || 'Failed to save bill');
            focusProductSearch();
        }
    });
}
function sanitizeModeValue(value) {
    const cleaned = String(value ?? '').trim();
    return (cleaned === '' || cleaned === '0') ? 'Standard' : cleaned;
}
function formatMoney(value) { return (parseFloat(value) || 0).toFixed(2); }
function formatNumber(value) {
    const num = parseFloat(value) || 0;
    return Number.isInteger(num) ? String(num) : num.toFixed(2).replace(/\.0+$/, '').replace(/(\.\d*[1-9])0+$/, '$1');
}
function escapeHtml(value) {
    return String(value ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;');
}
</script>
</body>
</html>
