<?php
session_start();

require_once '../../config/database.php';
require_once '../../includes/auth.php';

$db = (new Database())->connect();

$basePath = '../../';
include '../../includes/header.php';

/*
    Tables
*/
$stmt = $db->prepare("
    SELECT id, table_name
    FROM tables
    ORDER BY table_name
");
$stmt->execute();

$tables = $stmt->fetchAll(PDO::FETCH_ASSOC);

/*
    Quick favorite items
*/
$stmt = $db->prepare("
    SELECT id, name
    FROM items
    ORDER BY name ASC
    LIMIT 12
");
$stmt->execute();

$favorites = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container-fluid mt-3">

    <div class="row">

        <!-- LEFT PANEL -->
        <div class="col-md-7">

            <!-- SEARCH -->
            <div class="card shadow-sm mb-3">
                <div class="card-body">

                    <input type="text" id="item-search" class="form-control form-control-lg"
                        placeholder="Search item / barcode / 2*tea / 3*101" autocomplete="off" autofocus>

                    <small class="text-muted">
                        F1 Search | Enter Add | ESC Clear
                    </small>

                    <div id="search-results" class="list-group mt-2" style="max-height:300px; overflow-y:auto;"></div>

                </div>
            </div>

            <!-- FAVORITES -->
            <div class="card shadow-sm mb-3">
                <div class="card-header bg-dark text-white">
                    Quick Items
                </div>

                <div class="card-body">

                    <div class="d-flex flex-wrap gap-2">

                        <?php foreach ($favorites as $fav): ?>
                        <button class="btn btn-outline-primary quick-item" data-id="<?= $fav['id'] ?>">
                            <?= htmlspecialchars($fav['name']) ?>
                        </button>
                        <?php endforeach; ?>

                    </div>

                </div>
            </div>

        </div>

        <!-- RIGHT PANEL -->
        <div class="col-md-5">

            <!-- CART -->
            <div class="card shadow-sm">

                <div class="card-header bg-success text-white">
                    Current Bill
                </div>

                <div class="card-body" id="cart-container">
                    Loading cart...
                </div>

            </div>

            <!-- ACTION BUTTONS -->
            <div class="mt-3 d-flex flex-wrap gap-2">

                <button class="btn btn-secondary" onclick="holdBill()">
                    F2 Hold
                </button>

                <button class="btn btn-primary" onclick="resumeBill()">
                    F3 Resume
                </button>

                <button class="btn btn-success" onclick="checkoutBill()">
                    F4 Checkout
                </button>

                <button class="btn btn-info" onclick="printKOT()">
                    F6 KOT
                </button>

                <button class="btn btn-danger" onclick="cancelBill()">
                    F8 Cancel
                </button>

                <button class="btn btn-dark" onclick="clearSearch()">
                    ESC Clear
                </button>

            </div>

        </div>

    </div>

</div>
<script>
function updateCartQty(itemId, change) {
    fetch('update_cart_qty.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: 'item_id=' + itemId +
                '&change=' + change
        })
        .then(res => res.text())
        .then(() => {
            loadCart();
        });
}

function removeCartItem(itemId) {
    fetch('remove_from_cart.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: 'item_id=' + itemId
        })
        .then(res => res.text())
        .then(() => {
            loadCart();
        });
}
</script>
<script>
let selectedIndex = -1;

document.addEventListener('DOMContentLoaded', function() {
    loadCart();
});

function loadCart() {
    fetch('load_cart.php')
        .then(res => res.text())
        .then(data => {
            document.getElementById('cart-container').innerHTML = data;
        });
}

function clearSearch() {
    document.getElementById('item-search').value = '';
    document.getElementById('search-results').innerHTML = '';
    selectedIndex = -1;
}

function searchItems(query) {

    if (query.trim() === '') {
        clearSearch();
        return;
    }

    fetch('search_items.php?q=' + encodeURIComponent(query))
        .then(res => res.text())
        .then(data => {
            document.getElementById('search-results').innerHTML = data;
            selectedIndex = -1;
        });
}

function addItem(itemId, qty = 1) {

    fetch('add_to_cart.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: 'item_id=' + itemId + '&qty=' + qty
        })
        .then(res => res.text())
        .then(() => {
            clearSearch();
            loadCart();
            document.getElementById('item-search').focus();
        });
}

async function parseQuickEntry(value) {
    if (!value.includes('*')) {
        return false;
    }

    let parts = value.split('*');

    if (parts.length !== 2) {
        return false;
    }

    let qty = parseFloat(parts[0]);
    let item = parts[1].trim();

    if (isNaN(qty) || qty <= 0) {
        return false;
    }

    try {

        let response = await fetch(
            'search_items.php?q=' +
            encodeURIComponent(item) +
            '&json=1'
        );

        let data = await response.json();

        if (data.success) {

            addItem(data.item.id, qty);

            return true;
        }

        alert('Item not found');

        return false;

    } catch (err) {

        console.error(err);

        return false;
    }
}

document.getElementById('item-search').addEventListener('keyup', async function(e) {
let value = this.value.trim();

if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
    return;
}

if (e.key === 'Enter') {


    let handled = await parseQuickEntry(value);

    if (handled) {
        return;
    }

    let selected = document.querySelector('.search-item.active');


    if (selected) {
        addItem(selected.dataset.id);
    }

    return;
}
searchItems(value);
});

function addItemFromPopup(itemId) {
    addItem(itemId);
}

function openItemDialog() {
    fetch('item_popup.php')
        .then(res => res.text())
        .then(html => {

            document.getElementById(
                'item-dialog-body'
            ).innerHTML = html;

            let dialog = document.getElementById(
                'itemDialog'
            );

            dialog.showModal();

            setTimeout(() => {

                let search = document.getElementById('search');

                if (search) {
                    search.focus();
                }

            }, 100);
        });
}

function closeItemDialog() {
    document.getElementById(
        'itemDialog'
    ).close();
}

function selectItem(itemId) {
    addItem(itemId);

    closeItemDialog();
}
document.addEventListener('keydown', function(e) {

    if (e.key === 'F1') {

        e.preventDefault();

        openItemDialog();

        return false;
    }

    if (e.key === 'F4') {
        e.preventDefault();
        checkoutBill();
    }

    if (e.key === 'F6') {
        e.preventDefault();
        printKOT();
    }

    if (e.key === 'Escape') {
        clearSearch();
    }
    /*
        F2 Hold
    */
    if (e.key === 'F2') {

        e.preventDefault();

        holdBill();

        return false;
    }

    /*
        F3 Resume
    */
    if (e.key === 'F3') {

        e.preventDefault();

        resumeBill();

        return false;
    }

    /*
        F8 Cancel
    */
    if (e.key === 'F8') {

        e.preventDefault();

        cancelBill();

        return false;
    }
    let items = document.querySelectorAll('.search-item');

    if (e.key === 'ArrowDown') {
        e.preventDefault();

        if (items.length === 0) return;

        selectedIndex++;

        if (selectedIndex >= items.length) {
            selectedIndex = 0;
        }

        highlightSelection(items);
    }

    if (e.key === 'ArrowUp') {
        e.preventDefault();

        if (items.length === 0) return;

        selectedIndex--;

        if (selectedIndex < 0) {
            selectedIndex = items.length - 1;
        }

        highlightSelection(items);
    }
});

function highlightSelection(items) {
    items.forEach(i => i.classList.remove('active'));

    if (selectedIndex >= 0 && items[selectedIndex]) {
        items[selectedIndex].classList.add('active');
    }
}

document.querySelectorAll('.quick-item').forEach(btn => {
    btn.addEventListener('click', function() {
        addItem(this.dataset.id);
    });
});

function checkoutBill() {
    window.open(
        'checkout.php',
        '_blank',
        'width=700,height=700'
    );
}

function printKOT() {
    window.open(
        'print_kot.php',
        '_blank',
        'width=500,height=700'
    );
}

function holdBill() {
    document
        .getElementById('holdDialog')
        .showModal();
}

function closeHoldDialog() {
    document
        .getElementById('holdDialog')
        .close();
}

function resumeBill() {
    window.location.href = 'resume_orders.php';
}

function cancelBill() {
    if (!confirm('Cancel current bill?')) {
        return;
    }

    fetch('clear_cart.php', {
            method: 'POST'
        })
        .then(res => res.text())
        .then(() => {

            loadCart();

            clearSearch();

            alert('Bill cancelled');
        });
}
</script>

<dialog id="itemDialog" style="
        width: 90%;
        max-width: 1000px;
        border: none;
        border-radius: 10px;
        padding: 0;
    ">

    <div id="item-dialog-body" style="padding:0;">
        Loading...
    </div>

</dialog>
<dialog id="holdDialog" style="width:500px;">

    <form id="holdForm" method="POST" action="hold_order.php">

        <h4>Hold Current Bill</h4>

        <div class="mb-3">

            <label class="form-label">
                Select Table
            </label>

            <select name="table_id" class="form-select" required>

                <option value="">
                    Select Table
                </option>

                <?php foreach ($tables as $table): ?>

                <option value="<?= $table['id'] ?>">
                    <?= htmlspecialchars($table['table_name']) ?>
                </option>

                <?php endforeach; ?>

            </select>

        </div>

        <div class="mb-3">

            <label class="form-label">
                Customer Name
            </label>

            <input type="text" name="customer_name" class="form-control">

        </div>

        <div class="d-flex justify-content-end gap-2">

            <button type="button" class="btn btn-secondary" onclick="closeHoldDialog()">
                Cancel
            </button>

            <button type="submit" class="btn btn-primary">
                Hold Bill
            </button>

        </div>

    </form>
</dialog>
<script>
function loadItems(query = '')
{
    fetch(
        'search_items.php?q=' +
        encodeURIComponent(query)
    )
    .then(res => res.text())
    .then(data => {

        let tempDiv = document.createElement('div');
        tempDiv.innerHTML = data;

        let rows = '';

        tempDiv.querySelectorAll('.search-item').forEach(btn => {

            rows += `
                <tr
                    class="item-row"
                    data-id="${btn.dataset.id}"
                    ondblclick="selectItem(${btn.dataset.id})"
                >
                 
                    <td>
                        ${btn.dataset.name}
                    </td>
                    <td>
                        ${btn.dataset.barcode || ''}
                    </td>
                    <td>
                        ₹ ${Number(btn.dataset.price).toFixed(2)}
                    </td>
                </tr>
            `;
        });

        document.getElementById('item-results').innerHTML = rows;

        selectedIndex = -1;
    });
}
function handleSearchKeyUp(e)
{
    let value = document.getElementById('search').value.trim();

    if (
        e.key !== 'ArrowDown' &&
        e.key !== 'ArrowUp' &&
        e.key !== 'Enter'
    ) {
        loadItems(value);
    }

    let rows = document.querySelectorAll('.item-row');

    if (e.key === 'ArrowDown') {

        e.preventDefault();

        if (rows.length === 0) return;

        selectedIndex++;

        if (selectedIndex >= rows.length) {
            selectedIndex = 0;
        }

        highlightRow(rows);
    }

    if (e.key === 'ArrowUp') {

        e.preventDefault();

        if (rows.length === 0) return;

        selectedIndex--;

        if (selectedIndex < 0) {
            selectedIndex = rows.length - 1;
        }

        highlightRow(rows);
    }

    if (e.key === 'Enter') {

        e.preventDefault();

        if (
            selectedIndex >= 0 &&
            rows[selectedIndex]
        ) {
            selectItem(rows[selectedIndex].dataset.id);
        }
    }
}
function highlightRow(rows)
{
    rows.forEach(r => r.classList.remove('active'));

    if (
        selectedIndex >= 0
        && rows[selectedIndex]
    ) {

        rows[selectedIndex].classList.add('active');

        rows[selectedIndex].scrollIntoView({
            block: 'nearest'
        });
    }
}



</script>
<?php include '../../includes/footer.php'; ?>