@extends('layouts.app')

@section('title', 'Record Damage Stock')
@section('page-title', 'Record Damage Stock')

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

                <div class="row g-3 mb-3">
                    <div class="col-md-4">
                        <label class="form-label">Date / Time</label>
                        @php
                            $dtValue = old('date_time');
                            if (empty($dtValue)) {
                                $dtValue = \Carbon\Carbon::now()->format('Y-m-d\\TH:i');
                            }
                        @endphp
                        <input type="datetime-local" name="date_time" class="form-control" value="{{ $dtValue }}" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Product</label>
                        <input type="text" id="product_search" class="form-control mb-2" placeholder="Type product code, barcode or name to search" autocomplete="off">
                        <select name="product_id" class="form-select d-none">
                            <option value=""></option>
                            @foreach($products as $p)
                                <option value="{{ $p->id }}">{{ $p->product_name }}</option>
                            @endforeach
                        </select>
                        <div class="invalid-feedback d-none" id="product_select_error">Please select a product</div>
                    </div>
                   
                </div>

                <div class="row g-3 mb-3">
                     <div class="col-md-4">
                        <label class="form-label">Qty</label>
                        <input type="number" step="0.001" name="qty" class="form-control" value="{{ old('qty',1) }}" required>
                    </div>
                    <div class="col-md-4" style="display:none;">
                        <label class="form-label">Per Item Cost</label>
                        <input type="number" step="0.01" name="per_item_cost" class="form-control" value="{{ old('per_item_cost','') }}" placeholder="Auto-calculated">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Total Cost</label>
                        <input type="number" step="0.01" name="total_cost" class="form-control" value="{{ old('total_cost',0) }}" readonly required>
                    </div>
                    
                    <div class="col-md-4">
                        <label class="form-label">Remark</label>
                        <input type="text" name="remark" class="form-control" value="{{ old('remark') }}">
                    </div>
                </div>

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

@push('scripts')
    <script>
        // Inject products array for client-side search (guarded to avoid redeclaration)
        if (typeof window.PRODUCTS === 'undefined') {
            window.PRODUCTS = @json($productsJs ?? []);
        }
    </script>
    <script>
        document.addEventListener('DOMContentLoaded', function(){
            const form = document.getElementById('damageForm');
            const productSelect = document.querySelector('select[name="product_id"]');
            const productError = document.getElementById('product_select_error');
            const psearch = document.getElementById('product_search');
            const costEl = document.querySelector('input[name="total_cost"]');
            let dropdown;

            function closeDropdown() {
                if(dropdown){ try { dropdown.remove(); document.removeEventListener('click', dropdown._outsideHandler); } catch(e){} dropdown = null; }
            }

            const qtyEl = document.querySelector('input[name="qty"]');
            const perEl = document.querySelector('input[name="per_item_cost"]');

            // If user types a barcode and presses Enter, try to auto-select the matching product
            psearch.addEventListener('keydown', function(e){
                if(e.key === 'Enter'){
                    // prevent form submit
                    e.preventDefault();
                    const q = (this.value || '').trim();
                    if(!q) return;

                    const match = (window.PRODUCTS || []).find(p => {
                        const code = (p.code||'').toString();
                        const barcode = (p.barcode||'').toString();
                        const name = (p.name||'').toString();
                        return barcode === q || code === q || name.toLowerCase() === q.toLowerCase();
                    });

                    if(match){
                        const select = document.querySelector('select[name="product_id"]');
                        select.value = match.id;
                        psearch.value = match.name || (match.code ? '['+match.code+'] ' : '') + match.name;
                        // fill per-item cost from product data
                        if(perEl){
                            try{
                                const prodQty = parseFloat(match.qty || 0);
                                const prodCost = parseFloat(match.cost || 0);
                                if(prodQty > 0){
                                    perEl.value = (prodCost / prodQty).toFixed(2);
                                } else if(prodCost){
                                    perEl.value = prodCost.toFixed(2);
                                }
                                recalcTotalFromPer();
                            }catch(err){}
                        }
                        closeDropdown();
                    } else {
                        // no exact match: open dropdown to show similar matches
                        // trigger input handler to show suggestions
                        const ev = new Event('input', { bubbles: true });
                        this.dispatchEvent(ev);
                    }
                }
            });

            function recalcPerFromTotal(){
                try{
                    const q = parseFloat(qtyEl?.value || 0);
                    const t = parseFloat(costEl?.value || 0);
                    if(perEl){
                        // if user has explicitly filled per-item, don't overwrite here
                        if(perEl.value && perEl.value !== ''){
                            return;
                        }
                        if(q > 0 && t){
                            perEl.value = (t / q).toFixed(2);
                        } else if(t && !q){
                            perEl.value = parseFloat(t).toFixed(2);
                        } else {
                            perEl.value = '';
                        }
                    }
                }catch(e){}
            }

            function recalcTotalFromPer(){
                try{
                    const q = parseFloat(qtyEl?.value || 0);
                    const p = parseFloat(perEl?.value || 0);
                    if(costEl){
                        if(!isNaN(p) && p && q){
                            costEl.value = (p * q).toFixed(2);
                        } else if(!isNaN(p) && p && !q){
                            // no qty, set total to per
                            costEl.value = p.toFixed(2);
                        } else if(!p){
                            // clear total only if both per and qty empty/zero
                            // but avoid clearing if user typed a total
                        }
                    }
                }catch(e){}
            }

            // recalc total whenever qty or per-item change (total is derived = per * qty)
            qtyEl?.addEventListener('input', function(){
                recalcTotalFromPer();
            });
            perEl?.addEventListener('input', function(){
                recalcTotalFromPer();
            });

            psearch.addEventListener('input', function(){
                const q = (this.value || '').toLowerCase().trim();
                closeDropdown();
                if(!q || q.length < 1) return; // don't show when empty

                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);

                // Match code, barcode or name
                const results = (window.PRODUCTS || []).filter(p => {
                    const code = (p.code||'').toString().toLowerCase();
                    const barcode = (p.barcode||'').toString().toLowerCase();
                    const name = (p.name||'').toString().toLowerCase();
                    return code.includes(q) || barcode.includes(q) || name.includes(q);
                }).slice(0,10);

                if(results.length === 0){
                    const none = document.createElement('div');
                    none.className = 'list-group-item';
                    none.innerText = 'No products found';
                    dropdown.appendChild(none);
                }

                results.forEach(p => {
                    const a = document.createElement('button');
                    a.className = 'list-group-item list-group-item-action d-flex justify-content-between align-items-start';
                    a.type = 'button';
                    const left = document.createElement('div');
                    left.style.textAlign = 'left';
                    const title = document.createElement('div');
                    title.style.fontWeight = '600';
                    title.innerText = (p.code ? '['+p.code+'] ' : '') + p.name;
                    const sub = document.createElement('div');
                    sub.style.fontSize = '0.85em';
                    sub.style.opacity = 0.8;
                    sub.innerText = (p.barcode ? 'Barcode: ' + p.barcode + ' • ' : '') + 'ID: ' + p.id;
                    left.appendChild(title);
                    left.appendChild(sub);

                    const right = document.createElement('div');
                    right.style.textAlign = 'right';
                    right.style.fontSize = '0.95em';
                    right.innerText = (typeof p.cost !== 'undefined' ? parseFloat(p.cost).toFixed(2) : '0.00');

                    a.appendChild(left);
                    a.appendChild(right);

                    a.addEventListener('click', function(){
                        const select = document.querySelector('select[name="product_id"]');
                        select.value = p.id;
                        psearch.value = p.name;
                        // set per-item cost based on product's stored qty and cost when available
                        if(perEl){
                            try{
                                const prodQty = parseFloat(p.qty || 0);
                                const prodCost = parseFloat(p.cost || 0);
                                if(prodQty > 0){
                                    perEl.value = (prodCost / prodQty).toFixed(2);
                                } else if(prodCost){
                                    perEl.value = prodCost.toFixed(2);
                                }
                                // recalc total immediately after filling per-item
                                try{ recalcTotalFromPer(); }catch(e){}
                            }catch(e){}
                        }
                        closeDropdown();
                    });
                    dropdown.appendChild(a);
                });

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

            // validate product selection on submit (hidden select can't use HTML required)
            form?.addEventListener('submit', function(e){
                if(!productSelect || !productSelect.value){
                    e.preventDefault();
                    // show inline message and focus product search
                    if(productError){
                        productError.classList.remove('d-none');
                        productError.classList.add('d-block');
                    }
                    psearch.focus();
                    // optionally, briefly highlight the field
                    psearch.classList.add('is-invalid');
                    setTimeout(()=> psearch.classList.remove('is-invalid'), 2000);
                }
            });
        });
    </script>
@endpush
