@section('title', 'Products - Harshana Systems')
@section('page-title', 'Products')

@extends('layouts.app')

@section('content')
    <div class="d-flex justify-content-between mb-3">
        <h1 class="h3 mb-0 page-title-theme">Products</h1>
        @if(auth()->user() && auth()->user()->hasAccessTo('products.create'))
            <a href="{{ route('products.create') }}" class="btn btn-primary">Create Product</a>
        @endif
    </div>

    <div class="card">
        <div class="card-body">
            <!-- Search Form -->
            <form method="GET" action="{{ route('products.index') }}" class="mb-3">
                <div class="row">
                    <div class="col-md-6">
                        <div class="input-group">
                            <input type="text" name="search" class="form-control" placeholder="Search by product name, code or barcode..." value="{{ $search ?? '' }}">
                            <button class="btn btn-outline-secondary" type="submit">
                                <i class="fas fa-search"></i>
                            </button>
                            @if($search)
                                <a href="{{ route('products.index') }}" class="btn btn-outline-danger">
                                    <i class="fas fa-times"></i>
                                </a>
                            @endif
                        </div>
                    </div>
                </div>
            </form>

            <div class="table-responsive">
                <table class="table table-striped table-hover mb-0">
                    <thead>
                        <tr>
                            <th style="display:none">#</th>
                            <th>Code</th>
                            <th>Barcode</th>
                            <th>Name</th>
                            <th style="display:none">Category</th>
                            <th>Qty Type</th>
                            <th>Qty</th>
                            <th>Selling Price</th>
                            <th>Warranty (Months)</th>
                            <th style="display:none">Last Selling Price</th>
                            <th style="display:none">Selling Price Can change</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($products as $product)
                            <tr>
                                <td style="display:none">{{ $product->id }}</td>
                                <td>{{ $product->product_code }}</td>
                                <td>{{ $product->product_barcode ?? '-' }}</td>
                                <td>{{ $product->product_name }}</td>
                                <td style="display:none">{{ $product->category->name ?? '-' }}</td>
                                <td>{{ $product->qtyType->qty_type ?? '-' }}</td>
                                <td>{{ number_format($product->stocks_sum_qty ?? $product->getTotalQty() ?? 0, 2) }}</td>
                                <td>{{ number_format($product->selling_price, 2) }}</td>
                                <td>{{ $product->warranty_days ?? 0 }}</td>
                                <td style="display:none">{{ $product->market_price ? number_format($product->market_price, 2) : '-' }}</td>
                                <td style="display:none">{{ $product->is_active ? 'Yes' : 'No' }}</td>
                                <td>
                                    @if(auth()->user() && auth()->user()->hasAccessTo('products.view'))
                                        <a href="{{ route('products.show', $product) }}" class="btn btn-sm btn-info me-1">View</a>
                                    @endif
                                    @if(auth()->user() && auth()->user()->hasAccessTo('products.edit'))
                                        <a href="{{ route('products.edit', $product) }}" class="btn btn-sm btn-warning me-1">Edit</a>
                                    @endif
                                    @if(auth()->user() && auth()->user()->hasAccessTo('products.delete'))
                                        <form method="POST" action="{{ route('products.destroy', $product) }}" style="display:inline">
                                            @csrf
                                            @method('DELETE')
                                            <button class="btn btn-sm btn-danger" onclick="return confirm('Delete product?')">Delete</button>
                                        </form>
                                    @endif
                                        @if(auth()->user() && auth()->user()->hasAccessTo('products.view'))
                                            <button type="button" style="display:none" class="btn btn-sm btn-secondary ms-1 print-barcode-btn" 
                                                data-id="{{ $product->id }}" 
                                                data-code="{{ $product->product_code }}" 
                                                data-name="{{ $product->product_name }}">
                                                Print Barcode
                                            </button>
                                        @endif
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="10" class="text-center">No products found.</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>

            <div class="mt-3 d-flex justify-content-center">
                {{ $products->appends(request()->except('page'))->links() }}
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <!-- Modal for print barcode quantity -->
    <div class="modal fade" id="printBarcodeModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content bg-dark text-white">
                <div class="modal-header border-0">
                    <h5 class="modal-title">Print Barcode</h5>
                    <button type="button" id="pb_modal_close" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-2"><strong id="pb_product_name"></strong></div>
                    <div class="row">
                        <div class="col-md-6 mb-2">
                            <label class="form-label text-white">Quantity</label>
                            <input type="number" class="form-control bg-dark text-white border-secondary" id="pb_qty" value="1" min="1">
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="form-label text-white">Barcode Type</label>
                            <select id="pb_type" class="form-select bg-dark text-white border-secondary">
                                <option value="code128">Code128 (recommended)</option>
                                <option value="ean13">EAN13</option>
                                <option value="upc">UPC</option>
                            </select>
                        </div>
                    </div>
                    <input type="hidden" id="pb_barcode_value">
                    <input type="hidden" id="pb_product_code">
                </div>
                <div class="modal-footer border-0">
                    <button type="button" id="pb_modal_cancel" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="pb_print">Print</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        (function(){
            console.log('Print barcode script loaded');
            // Ensure Bootstrap modal available
            const modalEl = document.getElementById('printBarcodeModal');
            let bsModal = null;
            let manualBackdrop = null;
            function manualShowModal(){
                if(!modalEl) return;
                modalEl.style.display = 'block';
                modalEl.classList.add('show');
                document.body.classList.add('modal-open');
                if(!manualBackdrop){
                    manualBackdrop = document.createElement('div');
                    manualBackdrop.className = 'modal-backdrop fade show';
                    document.body.appendChild(manualBackdrop);
                    manualBackdrop.addEventListener('click', function(){ manualHideModal(); });
                }
            }
            function manualHideModal(){
                if(!modalEl) return;
                modalEl.style.display = 'none';
                modalEl.classList.remove('show');
                document.body.classList.remove('modal-open');
                if(manualBackdrop){ manualBackdrop.remove(); manualBackdrop = null; }
            }
            if(modalEl && typeof bootstrap !== 'undefined'){
                bsModal = new bootstrap.Modal(modalEl);
            } else {
                // Bootstrap not ready yet — we'll poll and attempt to load the local bundle.
                console.info('Bootstrap not available for modal (yet); polling and attempting dynamic load');
                // Poll more aggressively and also attempt to dynamically load the local bundle
                let _pollCount = 0;
                const _poll = setInterval(function(){
                    _pollCount++;
                    if(typeof bootstrap !== 'undefined' && modalEl){
                        try{ bsModal = new bootstrap.Modal(modalEl); console.log('Bootstrap detected by poll — modal initialized'); }catch(e){ console.error(e); }
                        clearInterval(_poll);
                    }
                    // if not found after a short while, try injecting the local bootstrap bundle once
                    if(_pollCount === 10){ // ~1s
                        if(!document.querySelector('script[data-bs-dyn]')){
                            try{
                                const s = document.createElement('script');
                                s.src = '/assets/bootstrap.bundle.min.js';
                                s.setAttribute('data-bs-dyn','1');
                                s.async = true;
                                s.onload = function(){ console.log('Dynamically loaded /assets/bootstrap.bundle.min.js'); };
                                s.onerror = function(){ console.warn('Dynamic bootstrap load failed'); };
                                document.head.appendChild(s);
                            }catch(e){ console.error('Error injecting bootstrap script', e); }
                        }
                    }
                    if(_pollCount > 100){ // ~10 seconds max
                        clearInterval(_poll);
                    }
                }, 100);
            }

            // If Bootstrap is loaded later (we load it async in layout), initialize when signalled
            document.addEventListener('bootstrapLoaded', function(){
                try{
                    console.log('bootstrapLoaded event received — initializing modal');
                    if(modalEl && typeof bootstrap !== 'undefined'){
                        bsModal = new bootstrap.Modal(modalEl);
                        // if a manual backdrop was shown earlier, hide it
                        if(typeof manualHideModal === 'function'){ manualHideModal(); }
                    }
                }catch(e){ console.error('Error initializing bootstrap modal', e); }
            });

            document.addEventListener('click', function(e){
                const btn = e.target.closest('.print-barcode-btn');
                if(!btn) return;
                console.log('Print barcode button clicked');
                const name = btn.getAttribute('data-name') || '';
                const code = btn.getAttribute('data-code') || '';
                document.getElementById('pb_product_name').innerText = name + ' ('+code+')';
                document.getElementById('pb_barcode_value').value = code;
                document.getElementById('pb_product_code').value = code;
                document.getElementById('pb_qty').value = 1;
                if(bsModal){
                    bsModal.show();
                } else {
                    manualShowModal();
                }
            });

            // Print handler
            document.getElementById('pb_print').addEventListener('click', function(){
                const qty = parseInt(document.getElementById('pb_qty').value) || 1;
                const value = document.getElementById('pb_product_code').value;
                const type = document.getElementById('pb_type').value || 'code128';

                if(!value){ alert('No barcode value available for this product'); return; }


                // Build printable HTML for 4 labels per page (2x2 grid)
                const win = window.open('', '_blank');
                const css = `
                    <style>
                        @page { size: 101.6mm 50.8mm; margin: 0; }
                        html, body { margin:0; padding:0; }
                        .sheet { width:101.6mm; height:50.8mm; display: flex; flex-wrap: wrap; page-break-after: always; }
                        .label {
                            width: 50.8mm; height: 25.4mm; box-sizing: border-box;
                            display: flex; flex-direction: column; align-items: center; justify-content: center;
                            text-align: center; font-family: Arial, Helvetica, sans-serif;
                            border: none;
                            position: relative;
                        }
                        /* Add dashed cut lines between labels */
                        .label:not(:nth-child(2)):not(:nth-child(4)) {
                            border-right: 1px dashed #888;
                        }
                        .label:nth-child(-n+2) {
                            border-bottom: 1px dashed #888;
                        }
                        .prod-name{ font-size:11px; margin-top:0px; font-weight:bold; }
                        .prod-code{ font-size:10px; margin-top:0px; color:#333; font-weight:bold; }
                        svg{ width:95%; height:18mm; display:block; margin-left:auto; margin-right:auto; background:white; }
                        @media print{
                            body{ margin:0; }
                            .no-print{ display:none; }
                        }
                    </style>
                `;

                const htmlStart = `<!doctype html><html><head><meta charset="utf-8"><title>Print Barcodes</title>${css}
                    <script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"><\/script>
                </head><body>`;
                const htmlEnd = `</body></html>`;

                // Group labels into sheets of 4 (2x2)
                let labels = '';
                let labelCount = 0;
                while(labelCount < qty){
                    labels += '<div class="sheet">';
                    for(let i=0;i<4 && labelCount<qty;i++,labelCount++){
                        const prodName = escapeHtml(document.getElementById('pb_product_name').innerText.split(' (')[0]);
                        const prodCode = escapeHtml(document.getElementById('pb_product_code').value);
                        labels += `<div class="label"><svg id="bc${labelCount}"></svg><div class="prod-name">${prodName}</div><div class="prod-code">${prodCode}</div></div>`;
                    }
                    labels += '</div>';
                }

                win.document.open();
                win.document.write(htmlStart + labels + htmlEnd);
                win.document.close();

                // After window loads, render barcodes and print
                win.onload = function(){
                    try{
                        for(let i=0;i<qty;i++){
                            const svg = win.document.getElementById('bc'+i);
                            if(svg){
                                win.JsBarcode(svg, value, {
                                    format: type,
                                    displayValue: false,
                                    height: 60,
                                    width: 2.5, // Wider bars for better scanner readability
                                    margin: 3,
                                    marginLeft: 8,
                                    marginRight: 8,
                                    fontSize: 0,
                                    textMargin: 0
                                });
                            }
                        }
                    }catch(e){ console.error(e); }
                    setTimeout(function(){ win.focus(); win.print(); }, 700);
                };

                if(bsModal){ bsModal.hide(); } else { manualHideModal(); }
            });

            // wire fallback close buttons if Bootstrap not present
            document.getElementById('pb_modal_close')?.addEventListener('click', function(){ if(bsModal){ bsModal.hide(); } else { manualHideModal(); } });
            document.getElementById('pb_modal_cancel')?.addEventListener('click', function(){ if(bsModal){ bsModal.hide(); } else { manualHideModal(); } });

            function escapeHtml(str){
                return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
            }
        })();
    </script>
@endpush
