@extends('layouts.app')

@section('title', 'Create Price - Harshana Systems')
@section('page-title', 'Create Price')

@section('content')
    <div class="d-flex justify-content-between mb-3">
        <h1 class="h3 mb-0 page-title-theme">Create Price</h1>
        <a href="{{ route('prices.index') }}" class="btn btn-outline-secondary">Back to Prices</a>
    </div>

    <div class="card">
        <div class="card-body">
            @if ($errors->any())
                <div class="alert alert-danger">
                    <ul class="mb-0">
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif

            <form method="POST" action="{{ route('prices.store') }}">
                @csrf
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">Product</label>
                        <!-- Visible text input so user can type immediately like a normal input -->
                        <input type="text" id="product_search" class="form-control mb-2" placeholder="Type product name or code to search" autocomplete="off">
                        <!-- Hidden select used by Select2 and for form submit -->
                        <select name="product_id" class="form-select select2-product d-none" required>
                            <option value=""></option>
                            @foreach($products as $p)
                                <option value="{{ $p->id }}" data-code="{{ $p->product_code ?? '' }}" {{ old('product_id') == $p->id ? 'selected' : '' }}>{{ $p->product_name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Remark</label>
                        <input type="text" name="remark" class="form-control" value="{{ old('remark') }}">
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Selling Price</label>
                        <input type="number" step="0.01" name="selling_price" class="form-control" value="{{ old('selling_price') }}">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Last Selling Price</label>
                        <input type="number" step="0.01" name="market_price" class="form-control" value="{{ old('market_price') }}">
                    </div>

                    <div class="col-12">
                        <div class="d-flex justify-content-end gap-2">
                            <a href="{{ route('prices.index') }}" class="btn btn-outline-secondary">Cancel</a>
                            <button class="btn btn-primary">Create Price</button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
@endsection

@push('styles')
    <!-- Select2 CSS (CDN) -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <style>
        /* Ensure select2 matches form-control sizing */
        .select2-container .select2-selection--single {
            height: calc(1.5em + .75rem + 2px);
            padding: .375rem .75rem;
            border-radius: .375rem;
        }
    </style>
@endpush

@push('scripts')
    @php
        $productsJs = $products->map(function($p){
            return [
                'id' => $p->id,
                'code' => $p->product_code,
                'barcode' => $p->product_barcode,
                'name' => $p->product_name
            ];
        })->values()->all();
    @endphp
    <script>
        // Ensure a single global PRODUCTS array to avoid duplicate declaration errors
        if (typeof window.PRODUCTS === 'undefined') {
            window.PRODUCTS = @json($productsJs);
        }

        function createTypableDropdownForInput(inputEl, items, onSelect){
            let dropdown;
            inputEl.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 = (items || []).filter(p => {
                    const nameMatch = (p.name||'').toLowerCase().includes(q);
                    const codeMatch = (p.code||'').toLowerCase().includes(q);
                    const barcodeMatch = String(p.barcode||'').toLowerCase().includes(q);
                    return nameMatch || codeMatch || barcodeMatch;
                }).slice(0, 15);

                results.forEach(p => {
                    const btn = document.createElement('button');
                    btn.type = 'button';
                    btn.className = 'list-group-item list-group-item-action';
                    btn.innerText = (p.code ? '['+p.code+'] ' : '') + p.name;
                    btn.addEventListener('click', function(){
                        onSelect(p);
                        dropdown.remove();
                        try { document.removeEventListener('click', dropdown._outsideHandler); } catch(e){}
                    });
                    dropdown.appendChild(btn);
                });

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

        document.addEventListener('DOMContentLoaded', function(){
            const input = document.getElementById('product_search');
            const select = document.querySelector('select[name="product_id"]');
            if (input && select) {
                // prefill visible input with selected option text if any
                const sel = select.options[select.selectedIndex];
                if (sel && sel.text) input.value = sel.text;

                createTypableDropdownForInput(input, window.PRODUCTS, function(p){
                    select.value = p.id;
                    select.dispatchEvent(new Event('change', { bubbles: true }));
                    input.value = (p.code ? '['+p.code+'] ' : '') + p.name;
                });

                // Forward typing when user types outside inputs to the product_search input
                document.addEventListener('keydown', function (e) {
                    if (e.ctrlKey || e.metaKey || e.altKey) return;
                    const active = document.activeElement;
                    if (active && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA' || active.isContentEditable || active.tagName === 'SELECT')) return;
                    const key = e.key;
                    if ((key && key.length === 1) || key === 'Backspace') {
                        e.preventDefault();
                        input.focus();
                        // simulate typing into the input
                        const v = input.value || '';
                        if (key === 'Backspace') input.value = v.slice(0, -1);
                        else input.value = v + key;
                        input.dispatchEvent(new Event('input', { bubbles: true }));
                    }
                });
            }
        });
    </script>
@endpush
