@extends('layout.app')

@section('content')

<style>
#tableCard .card-body {
    height: calc(100vh - 220px);
    display: flex;
    flex-direction: column;
    min-height: 0;
}

.table-scroller {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
}

.table-fixed-body {
    flex: 1;
    min-height: 0;
    overflow-y: auto !important;
    overflow-x: hidden;
}

.container-split {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 18px;
    align-items: start;
}

.card.panel-card { 
    height: calc(100vh - 120px); 
    overflow: hidden; 
    display:flex; 
    flex-direction:column; 
}
.card-body { 
    padding: 12px; 
    flex: 1; 
    display: flex; 
    flex-direction: column; 
}

.form-fields { display: flex; flex-direction: column; gap: 10px; }
.input-row { display:flex; gap:8px; align-items:center; }
.input-row .form-control { flex: 1; }

.table-scroller { flex: 1; min-height: 0; overflow: hidden; display:flex; flex-direction:column; }
.table-fixed-body { overflow-y: auto; min-height: 0; }

.table td, .table th { padding: 6px 8px; vertical-align: middle; }

.action-btn { cursor: pointer; border: none; background: transparent; }

.table-expander {
    position: absolute;
    right: 10px;
    top: 10px;
    z-index: 50;
}
.table-expander button { position: relative; z-index: 50; }

.expanded-table-mode {
    grid-template-columns: 1fr !important;
}

.expanded-table-mode #tableCard {
    grid-column: 1 / -1;
}

.expanded-table-mode #tableCard .card-body {
    height: calc(100vh - 200px);
}

.expanded-table-mode .panel-card {
    height: auto;
}

.inline-input { width: 100%; box-sizing: border-box; padding: 4px 6px; }

.small-muted { font-size: 12px; color: #666; }
.search-box { max-width: 320px; }
</style>

<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h4 class="fw-bold">Products — Fast Entry</h4>
        <a href="{{ route('user.dashboard') }}" class="btn btn-secondary btn-sm">
            <i class="fa fa-arrow-left me-1"></i> Back
        </a>
    </div>

    <div class="card shadow-sm border-0">
        <div class="card-body">
            <div class="container-split">

                <!-- LEFT SIDE FORM -->
                <div class="card panel-card">
                    <div class="card-body">
                        <h6 class="mb-2">Add Product Quickly</h6>

                        <form id="fastProductForm" autocomplete="off">
                            @csrf

                            <div class="form-fields">

                                <!-- PRODUCT NAME -->
                                <div class="input-row">
                                    <label class="form-label mb-0 me-2" style="width:110px">Product *</label>
                                    <input id="pName" name="product_name" class="form-control" required autofocus>
                                </div>

                                <!-- PRICE ONLY -->
                                <div class="input-row">
                                    <label class="form-label mb-0 me-2" style="width:110px">Price *</label>
                                    <input id="pPrice" name="price" type="number" min="0" step="0.01" value="0" class="form-control" required>
                                </div>

                                <div class="d-flex gap-2 align-items-center">
                                    <button id="fastSaveBtn" type="button" class="btn btn-primary px-4">
                                        <i class="fa fa-save me-1"></i> Save
                                    </button>
                                    <button id="fastClearBtn" type="button" class="btn btn-light border">Clear</button>
                                    <small class="small-muted">Press Enter to move next. Enter on Price = Save.</small>
                                </div>

                            </div>
                        </form>

                    </div>
                </div>

                <!-- RIGHT SIDE TABLE -->
                <div class="card panel-card" id="tableCard">
                    <div class="card-body" style="position:relative;">

                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <div class="d-flex gap-2 align-items-center">
                                <input id="tableSearch" class="form-control search-box" placeholder="Search products">
                                <button id="clearSearch" class="btn btn-sm btn-light border">Clear</button>
                            </div>

                            <div style="position: relative; height: 0;margin-top: -28px;">
                                <div class="table-expander">
                                    <button id="toggleExpand" class="btn btn-sm btn-outline-secondary" title="Expand table">
                                        <i id="expandIcon" class="fa fa-arrows-alt"></i>
                                    </button>
                                </div>
                            </div>

                        </div>

                        <div class="table-scroller">
                            <div class="table-fixed-body">
                                <table class="table table-bordered table-striped mb-0">
                                    <thead class="table-dark">
                                        <tr>
                                            <th style="width:50px">#</th>
                                            <th>Name</th>
                                            <th style="width:140px">Price</th>
                                            <th style="width:120px">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody id="productsTbody">
                                        @php $i = 1; @endphp
                                        @foreach($products as $product)
                                        <tr data-id="{{ $product->id }}">
                                            <td class="idx">{{ $i++ }}</td>
                                            <td class="p-name">{{ $product->product_name }}</td>
                                            <td class="p-price">{{ number_format($product->price, 2, '.', '') }}</td>
                                            <td class="text-center">
                                                <button class="action-btn btn-edit" title="Edit"><i class="fa fa-edit"></i></button>
                                            </td>
                                        </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                        </div>

                    </div>
                </div>

            </div>
        </div>
    </div>
</div>


<script>
document.addEventListener('DOMContentLoaded', () => {

    const pName = document.getElementById('pName');
    const pPrice = document.getElementById('pPrice');
    const fastSaveBtn = document.getElementById('fastSaveBtn');
    const fastClearBtn = document.getElementById('fastClearBtn');
    const productsTbody = document.getElementById('productsTbody');
    const tableSearch = document.getElementById('tableSearch');
    const clearSearch = document.getElementById('clearSearch');
    const csrfToken = document.querySelector('input[name="_token"]').value;

    let isSubmitting = false;

    // ENTER KEY FLOW → name → price → save
    const inputs = [pName, pPrice];
    inputs.forEach((el, idx) => {
        el.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                if (idx === inputs.length - 1) {
                    handleFastSubmit();
                } else {
                    inputs[idx + 1].focus();
                    inputs[idx + 1].select?.();
                }
            }
        });
    });

    fastSaveBtn.addEventListener('click', handleFastSubmit);
    fastClearBtn.addEventListener('click', clearFastForm);

    function handleFastSubmit() {
        if (isSubmitting) return;

        if (!pName.value.trim() || pPrice.value === '') {
            alert('Please enter product name and price.');
            return;
        }

        isSubmitting = true;
        fastSaveBtn.setAttribute('disabled', 'disabled');
        pPrice.setAttribute('disabled', 'disabled');

        const payload = {
            _token: csrfToken,
            product_name: pName.value.trim(),
            price: parseFloat(pPrice.value) || 0
        };

        fetch("{{ route('user.products.store') }}", {
            method: "POST",
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify(payload)
        })
        .then(async res => {
            if (!res.ok) throw new Error(await res.text());
            return res.json();
        })
        .then(data => {
            const p = data.product ?? payload;
            addRowToTable(p, true);
            clearFastForm();
            pName.focus();
        })
        .finally(() => {
            isSubmitting = false;
            fastSaveBtn.removeAttribute('disabled');
            pPrice.removeAttribute('disabled');
        });
    }

    function clearFastForm() {
        pName.value = '';
        pPrice.value = '0';
    }

    function addRowToTable(p, prepend = true) {
        const tr = document.createElement('tr');
        tr.dataset.id = p.id ?? ('tmp-' + Date.now());

        tr.innerHTML = `
            <td class="idx"></td>
            <td class="p-name">${escapeHtml(p.product_name)}</td>
            <td class="p-price">${Number(p.price).toFixed(2)}</td>
            <td class="text-center">
                <button class="action-btn btn-edit"><i class="fa fa-edit"></i></button>
            </td>
        `;

        if (prepend) productsTbody.prepend(tr);
        else productsTbody.append(tr);

        renumber();
    }

    function renumber() {
        [...productsTbody.querySelectorAll('tr')].forEach((tr, i) => {
            tr.querySelector('.idx').innerText = i + 1;
        });
    }

    function escapeHtml(text) {
        return String(text ?? '')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
    }

    // SEARCH
    tableSearch.addEventListener('input', () => {
        const q = tableSearch.value.toLowerCase();
        [...productsTbody.querySelectorAll('tr')].forEach(tr => {
            const name = tr.querySelector('.p-name').innerText.toLowerCase();
            const price = tr.querySelector('.p-price').innerText.toLowerCase();
            tr.style.display = (!q) || name.includes(q) || price.includes(q) ? '' : 'none';
        });
        renumber();
    });

    clearSearch.addEventListener('click', () => {
        tableSearch.value = '';
        tableSearch.dispatchEvent(new Event('input'));
        pName.focus();
    });

    // INLINE EDIT: ONLY NAME + PRICE
    productsTbody.addEventListener('click', (e) => {
        const editBtn = e.target.closest('.btn-edit');
        if (!editBtn) return;

        const tr = editBtn.closest('tr');
        const isEditing = editBtn.dataset.mode === 'save';

        if (!isEditing) {
            enterEditMode(tr, editBtn);
        } else {
            saveRowEdit(tr, editBtn);
        }
    });

    function enterEditMode(tr, btn) {
        const nameTd = tr.querySelector('.p-name');
        const priceTd = tr.querySelector('.p-price');

        const nameVal = nameTd.innerText;
        const priceVal = priceTd.innerText;

        nameTd.innerHTML = `<input class="inline-input edit-name" value="${escapeHtml(nameVal)}">`;
        priceTd.innerHTML = `<input type="number" class="inline-input edit-price" value="${escapeHtml(priceVal)}">`;

        btn.innerHTML = `<i class="fa fa-save"></i>`;
        btn.dataset.mode = 'save';

        tr.querySelector('.edit-name').focus();
    }

    function saveRowEdit(tr, btn) {
        btn.disabled = true;

        const id = tr.dataset.id;
        const nameVal = tr.querySelector('.edit-name').value.trim();
        const priceVal = parseFloat(tr.querySelector('.edit-price').value) || 0;

        if (!nameVal) {
            alert("Product name required.");
            btn.disabled = false;
            return;
        }

        const payload = {
            _token: csrfToken,
            product_name: nameVal,
            price: priceVal
        };

        const updateUrl = "{{ url('user/products') }}/" + id;

        fetch(updateUrl, {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify(payload)
        })
        .then(async res => {
            if (!res.ok) throw new Error(await res.text());
            return res.json();
        })
        .then(data => {
            const p = data.product ?? payload;

            tr.querySelector('.p-name').innerText = p.product_name;
            tr.querySelector('.p-price').innerText = Number(p.price).toFixed(2);

            btn.innerHTML = `<i class="fa fa-edit"></i>`;
            delete btn.dataset.mode;
        })
        .finally(() => {
            btn.disabled = false;
        });
    }

    renumber();
});
</script>


<script>
document.addEventListener('DOMContentLoaded', () => {
    const toggleExpand = document.getElementById('toggleExpand');
    const expandIcon = document.getElementById('expandIcon');
    const containerSplit = document.querySelector('.container-split');

    let isExpanded = false;

    toggleExpand.addEventListener('click', () => {
        isExpanded = !isExpanded;

        if (isExpanded) {
            containerSplit.classList.add('expanded-table-mode');
            expandIcon.classList.replace('fa-arrows-alt', 'fa-compress-arrows-alt');
        } else {
            containerSplit.classList.remove('expanded-table-mode');
            expandIcon.classList.replace('fa-compress-arrows-alt', 'fa-arrows-alt');
        }
    });
});
</script>
<script>
document.addEventListener("keydown", function(e) {

    // If user is typing inside input, textarea — ignore backspace
    const active = document.activeElement;
    const typingTags = ["INPUT", "TEXTAREA"];

    if (typingTags.includes(active.tagName)) return;

    // Backspace = go back
    if (e.key === "Backspace") {
        e.preventDefault();
        window.location.href = "{{ route('user.dashboard') }}";
    }
});
</script>
@endsection
