@extends('layouts.app')

@section('title', 'Create GRN')
@section('page-title', 'Create GRN')

@section('content')
    <div class="card">
        <div class="card-body">
            <form method="POST" action="{{ route('grns.store') }}" id="grnForm">
                @csrf

                <div class="row g-3 mb-3">
                    <div class="col-md-4">
                        <label class="form-label">GRN Number</label>
                        <input type="text" name="grn_number" class="form-control" value="{{ $nextGrnNumber }}" readonly required>
                        <small class="text-muted">Auto-generated GRN number</small>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Supplier</label>
                        <input type="text" id="supplier_search" class="form-control mb-2" placeholder="Type supplier name to search" autocomplete="off">
                        <select name="supplier_id" class="form-select d-none" required>
                            <option value=""></option>
                            @foreach($suppliers as $s)
                                <option value="{{ $s->id }}">{{ $s->supplier_name ?? $s->name ?? '' }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Branch</label>
                        <select name="branch_id" id="branch_select" class="form-select">
                            <option value="">-- Select branch --</option>
                            @foreach($branches as $b)
                                <option value="{{ $b->id }}">{{ $b->name }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">Barcode / Search Product</label>
                        <input type="text" id="product_search" class="form-control" placeholder="Type product name, code or barcode to search" autofocus>
                    </div>
                </div>

                <div class="table-responsive">
                    <table class="table" id="itemsTable">
                        <thead>
                            <tr><th>Product</th><th>Qty</th><th>Cost</th><th>Total</th><th></th></tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>

                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <!-- Add Manual Item button removed as not being used -->
                    </div>
                    <div>
                        <strong>Net Total: </strong><span id="netTotal">0.00</span>
                    </div>
                </div>

                <input type="hidden" name="items" id="itemsInput">

                <div class="mt-3 text-end">
                    <a href="{{ route('grns.index') }}" class="btn btn-outline-secondary">Cancel</a>
                    <button class="btn btn-primary" id="saveGrn">Save GRN</button>
                </div>
            </form>
        </div>
    </div>
@endsection

@push('scripts')
    @php
        $suppliersJs = $suppliers->map(function($s){
            return ['id' => $s->id, 'name' => $s->supplier_name ?? $s->name ?? ''];
        })->values()->all();
        $branchesJs = $branches->map(function($b){ return ['id' => $b->id, 'name' => $b->name]; })->values()->all();
    @endphp

    <script>
        if (typeof window.PRODUCTS === 'undefined') {
            window.PRODUCTS = @json($productsJs ?? []);
        }
        if (typeof window.SUPPLIERS === 'undefined') {
            window.SUPPLIERS = @json($suppliersJs ?? []);
        }
        if (typeof window.BRANCHES === 'undefined') {
            window.BRANCHES = @json($branchesJs ?? []);
        }

        try {
            if (!window.SUPPLIERS || !window.SUPPLIERS.length) {
                window.SUPPLIERS = [];
                const optList = document.querySelectorAll('select[name="supplier_id"] option');
                if (optList && optList.length) {
                    optList.forEach(o => {
                        const v = o.value;
                        const t = (o.text || '').trim();
                        if (v) window.SUPPLIERS.push({ id: v, name: t });
                    });
                }
            }
        } catch(e) {}

        // Reuse the same helper functions used by invoices (assumes they exist globally in layout). If not, we duplicate small helpers here.
        function addItemGrn(product){
            const tbody = document.querySelector('#itemsTable tbody');
            const row = document.createElement('tr');
            const qty = 1;
            // Use product's per item cost if available, otherwise default to 0.00
            const cost = product.cost ? parseFloat(product.cost).toFixed(2) : '0.00';
            const total = parseFloat(cost) * qty;
            row.innerHTML = `
                <td data-id="${product.id}">${product.name} <br><small class="text-muted">${product.code || ''}</small></td>
                <td><input class="form-control form-control-sm item-qty" value="${qty}" style="width:80px"></td>
                <td><input class="form-control form-control-sm item-cost" value="${cost}" placeholder="Enter cost" style="width:100px"></td>
                <td class="item-total">${total.toFixed(2)}</td>
                <td><button class="btn btn-sm btn-danger btn-remove">Remove</button></td>
            `;
            tbody.appendChild(row);
            attachRowEventsGrn(row);
            recalcGrn();
            
            // Lock branch dropdown after adding first product
            lockBranchDropdown();
        }

        function lockBranchDropdown(){
            const branchSelect = document.querySelector('select[name="branch_id"]');
            const tbody = document.querySelector('#itemsTable tbody');
            const hasItems = tbody && tbody.querySelectorAll('tr').length > 0;
            
            if(branchSelect){
                if(hasItems){
                    branchSelect.disabled = true;
                    branchSelect.style.opacity = '0.6';
                } else {
                    branchSelect.disabled = false;
                    branchSelect.style.opacity = '1';
                }
            }
        }

        function attachRowEventsGrn(row){
            row.querySelectorAll('.item-qty, .item-cost').forEach(el => { el.addEventListener('input', recalcGrn); });
            row.querySelector('.btn-remove').addEventListener('click', function(){ 
                row.remove(); 
                recalcGrn(); 
                // Unlock branch if all items removed
                lockBranchDropdown();
            });
        }

        function recalcGrn(){
            let total = 0;
            document.querySelectorAll('#itemsTable tbody tr').forEach(tr => {
                const qty = parseFloat(tr.querySelector('.item-qty').value) || 0;
                const costInput = tr.querySelector('.item-cost');
                const cost = parseFloat(costInput.value) || 0;
                const line = (cost * qty);
                tr.querySelector('.item-total').innerText = line.toFixed(2);
                total += line;

                // Visual indicator removed - allow 0 cost (free items, samples, etc.)
            });
            document.getElementById('netTotal').innerText = total.toFixed(2);
        }

        document.addEventListener('DOMContentLoaded', function(){
            // F1 key to focus product search input
            document.addEventListener('keydown', function(e){
                if(e.key === 'F1'){
                    e.preventDefault();
                    document.getElementById('product_search').focus();
                }
            });

            const psearch = document.getElementById('product_search');
            let dropdown;
            psearch.addEventListener('input', function(){
                // Check if branch is selected first
                const branchSelect = document.querySelector('select[name="branch_id"]');
                const selectedBranch = branchSelect?.value || '';
                
                if(!selectedBranch){
                    // Show warning if no branch selected
                    if(dropdown) { dropdown.remove(); try { document.removeEventListener('click', dropdown._outsideHandler); } catch(e){} }
                    this.style.borderColor = '#dc3545';
                    setTimeout(() => { this.style.borderColor = ''; }, 1500);
                    // Optionally show alert
                    if(this.value.length > 0){
                        alert('Please select a branch first');
                        this.value = '';
                    }
                    return;
                }

                const q = this.value.toLowerCase();
                if(dropdown) { dropdown.remove(); try { document.removeEventListener('click', dropdown._outsideHandler); } catch(e){} }
                dropdown = document.createElement('div');
                dropdown.className = 'list-group';
                dropdown.style.zIndex = 9999;
                dropdown.style.position = 'absolute';
                dropdown.style.maxHeight = '300px';
                dropdown.style.overflowY = 'auto';
                const rect = this.getBoundingClientRect();
                dropdown.style.width = rect.width + 'px';
                dropdown.style.left = (rect.left + window.scrollX) + 'px';
                dropdown.style.top = (rect.bottom + window.scrollY) + 'px';
                document.body.appendChild(dropdown);

                // Filter products by selected branch only
                // Split search query into words for flexible matching
                const searchWords = q.trim().split(/\s+/).filter(word => word.length > 0);
                
                const results = (window.PRODUCTS || []).filter(p => {
                    // Must match selected branch
                    if(String(p.branch_id || '') !== String(selectedBranch)) return false;
                    
                    const productName = (p.name || '').toLowerCase();
                    const productCode = (p.code || '').toLowerCase();
                    const productBarcode = String(p.barcode || '').toLowerCase();
                    
                    // Check if barcode or code matches exactly
                    const barcodeMatch = productBarcode.includes(q);
                    const codeMatch = productCode.includes(q);
                    
                    // Check if all search words are present in product name
                    const allWordsMatch = searchWords.every(word => 
                        productName.includes(word)
                    );
                    
                    return barcodeMatch || codeMatch || allWordsMatch;
                }).slice(0,50); // Increased limit since we have scroll
                
                results.forEach(p => {
                    const a = document.createElement('button');
                    a.className = 'list-group-item list-group-item-action';
                    a.type = 'button';
                    a.innerText = (p.code ? '['+p.code+'] ' : '') + p.name;
                    a.addEventListener('click', function(){ 
                        addItemGrn(p); 
                        dropdown.remove(); 
                        psearch.value=''; 
                        try { document.removeEventListener('click', dropdown._outsideHandler); } catch(e){} 
                    });
                    dropdown.appendChild(a);
                });

                dropdown._outsideHandler = function(ev){ if(!dropdown.contains(ev.target) && ev.target !== psearch){ dropdown.remove(); document.removeEventListener('click', dropdown._outsideHandler); } };
                setTimeout(() => document.addEventListener('click', dropdown._outsideHandler));
            });

            // Add barcode scanning functionality - Enter key to auto-add product by barcode
            psearch.addEventListener('keydown', function(e){
                if(e.key === 'Enter'){
                    e.preventDefault();
                    
                    // Check if branch is selected first
                    const branchSelect = document.querySelector('select[name="branch_id"]');
                    const selectedBranch = branchSelect?.value || '';
                    
                    if(!selectedBranch){
                        alert('Please select a branch first');
                        this.style.borderColor = '#dc3545';
                        setTimeout(() => { this.style.borderColor = ''; }, 1500);
                        return;
                    }
                    
                    const barcode = this.value.trim();
                    if(!barcode) return;

                    // Find exact barcode match within selected branch only
                    const exactMatch = (window.PRODUCTS || []).find(p => {
                        if(String(p.branch_id || '') !== String(selectedBranch)) return false;
                        return String(p.barcode || '').toLowerCase() === barcode.toLowerCase();
                    });

                    if(exactMatch){
                        addItemGrn(exactMatch);
                        this.value = '';
                        if(dropdown) { dropdown.remove(); try { document.removeEventListener('click', dropdown._outsideHandler); } catch(e){} }
                    } else {
                        // Show brief feedback that no matching barcode was found
                        this.style.borderColor = '#dc3545';
                        setTimeout(() => { this.style.borderColor = ''; }, 1000);
                    }
                }
            });

            const supplierInput = document.getElementById('supplier_search');
            const supplierSelect = document.querySelector('select[name="supplier_id"]');
            if(supplierInput && supplierSelect){
                const pre = supplierSelect.options[supplierSelect.selectedIndex];
                if(pre && pre.text) supplierInput.value = pre.text;
                // simple typable dropdown
                supplierInput.addEventListener('input', function(){
                    const q = this.value.toLowerCase();
                    if(dropdown) { dropdown.remove(); try { document.removeEventListener('click', dropdown._outsideHandler); } catch(e){} }
                    dropdown = document.createElement('div'); dropdown.className='list-group'; dropdown.style.zIndex=9999; dropdown.style.position='absolute';
                    const rect = this.getBoundingClientRect(); dropdown.style.width = rect.width + 'px'; dropdown.style.left = (rect.left + window.scrollX) + 'px'; dropdown.style.top = (rect.bottom + window.scrollY) + 'px'; document.body.appendChild(dropdown);
                    const results = (window.SUPPLIERS || []).filter(s => (s.name||'').toLowerCase().includes(q)).slice(0,15);
                    results.forEach(it => { const btn = document.createElement('button'); btn.type='button'; btn.className='list-group-item list-group-item-action'; btn.innerText = it.name; btn.addEventListener('click', function(){ supplierSelect.value = it.id; supplierInput.value = it.name; dropdown.remove(); try { document.removeEventListener('click', dropdown._outsideHandler); } catch(e){} }); dropdown.appendChild(btn); });
                    dropdown._outsideHandler = function(ev){ if(!dropdown.contains(ev.target) && ev.target !== supplierInput){ dropdown.remove(); document.removeEventListener('click', dropdown._outsideHandler); } };
                    setTimeout(() => document.addEventListener('click', dropdown._outsideHandler));
                });
            }

            // Branch dropdown is a standard <select> (visible). No typable input is used.
            const branchSelect = document.querySelector('select[name="branch_id"]');
            // optionally pre-select/display logic can be added here if needed

            document.getElementById('saveGrn').addEventListener('click', function(e){
                e.preventDefault();

                // Validate supplier
                const supplierSelect = document.querySelector('select[name="supplier_id"]');
                if (!supplierSelect.value) {
                    alert('Please select a supplier');
                    return;
                }

                // Validate branch
                const branchSelect = document.querySelector('select[name="branch_id"]');
                if (!branchSelect.value) {
                    alert('Please select a branch');
                    return;
                }

                const items = [];
                let hasErrors = false;
                document.querySelectorAll('#itemsTable tbody tr').forEach((tr, index) => {
                    const productId = tr.querySelector('td').dataset.id || null;
                    const qty = parseFloat(tr.querySelector('.item-qty').value) || 0;
                    const cost = parseFloat(tr.querySelector('.item-cost').value) || 0;

                    // Validate product
                    if (!productId) {
                        alert(`Item ${index + 1}: Please select a product`);
                        hasErrors = true;
                        return;
                    }

                    // Validate quantity
                    if (qty <= 0) {
                        alert(`Item ${index + 1}: Quantity must be greater than 0`);
                        hasErrors = true;
                        return;
                    }

                    // Cost validation removed - allow 0 or any value
                    // User can enter 0 cost for free items or adjust later

                    items.push({
                        product_id: productId,
                        qty: qty,
                        cost: cost,
                        other: null,
                        total_value: parseFloat(tr.querySelector('.item-total').innerText) || 0
                    });
                });

                if (hasErrors) return;

                if(items.length === 0){
                    alert('Add at least one item');
                    return;
                }

                document.getElementById('itemsInput').value = JSON.stringify(items);
                
                // Enable branch dropdown before submitting (disabled fields don't get submitted)
                if(branchSelect && branchSelect.disabled){
                    branchSelect.disabled = false;
                }
                
                document.getElementById('grnForm').submit();
            });
        });
    </script>
@endpush