@extends('layouts.master')

@section('title', 'Supplier Invoice - ')

@section('content')
@php
$PermissionsAdd = Auth::check() ? Auth::user()->hasFeaturePermission('supplier-invoices', 'add') : false;
$PermissionsEdit = Auth::check() ? Auth::user()->hasFeaturePermission('supplier-invoices', 'edit') : false;
$PermissionsDelete = Auth::check() ? Auth::user()->hasFeaturePermission('supplier-invoices', 'delete') : false;
$PermissionsPrint = Auth::check() ? Auth::user()->hasFeaturePermission('supplier-invoices', 'print') : false;
@endphp

<style>
    /* Modern UI Enhancements */
    body {
        background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
        min-height: 100vh;
    }

    .container-fluid {
        animation: fadeInUp 0.8s ease forwards;
        opacity: 0;
        transform: translateY(20px);
    }

    @keyframes fadeInUp {
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    /* Enhanced Page Heading */
    .page-heading {
        background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
        color: white;
        padding: 20px;
        border-radius: 15px;
        margin-bottom: 30px;
        box-shadow: 0 8px 25px rgba(59, 130, 246, 0.3);
        animation: slideInLeft 0.6s ease forwards;
    }

    @keyframes slideInLeft {
        from {
            opacity: 0;
            transform: translateX(-50px);
        }
        to {
            opacity: 1;
            transform: translateX(0);
        }
    }

    .page-heading h1 {
        margin: 0;
        font-weight: 700;
        text-shadow: 0 2px 4px rgba(0,0,0,0.3);
    }

    /* Enhanced Cards */
    .card {
        border: none;
        border-radius: 15px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        transition: all 0.3s ease;
        overflow: hidden;
    }

    .card:hover {
        transform: translateY(-5px);
        box-shadow: 0 15px 40px rgba(0,0,0,0.15);
    }

    .card-header {
        background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
        border-bottom: 2px solid #e2e8f0;
        padding: 20px;
    }

    .card-header h6 {
        color: #1e293b;
        font-weight: 600;
        margin: 0;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .card-header h6::before {
        content: "📋";
        font-size: 1.2em;
    }

    .card-body {
        padding: 25px;
    }

    /* Enhanced Form Styling */
    .form-group {
        margin-bottom: 20px;
        position: relative;
    }

    .form-group label {
        font-weight: 600;
        color: #374151;
        margin-bottom: 8px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .form-control {
        border: 2px solid #e5e7eb;
        border-radius: 10px;
        padding: 12px 15px;
        font-size: 14px;
        transition: all 0.3s ease;
        background: #f9fafb;
    }

    .form-control:focus {
        border-color: #3b82f6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        background: white;
        transform: translateY(-2px);
    }

    .form-control::placeholder {
        color: #9ca3af;
    }

    /* Form Icons */
    .form-group::before {
        content: "";
        position: absolute;
        right: 15px;
        top: 45px;
        width: 20px;
        height: 20px;
        opacity: 0.5;
        pointer-events: none;
    }

    .form-group:nth-child(1)::before { content: "🏢"; } /* Supplier */
    .form-group:nth-child(2)::before { content: "📄"; } /* Invoice Number */
    .form-group:nth-child(3)::before { content: "📅"; } /* Date */
    .form-group:nth-child(4)::before { content: "🔗"; } /* Reference Number */
    .form-group:nth-child(5)::before { content: "💼"; } /* Description */
    .form-group:nth-child(6)::before { content: "👤"; } /* Contact Person */
    .form-group:nth-child(7)::before { content: "📝"; } /* Narration */
    .form-group:nth-child(8)::before { content: "🔗"; } /* Reference */
    .form-group:nth-child(9)::before { content: "🏷️"; } /* GL Account */
    .form-group:nth-child(10)::before { content: "💰"; } /* Tax */
    .form-group:nth-child(11)::before { content: "🏷️"; } /* Discount */
    .form-group:nth-child(12)::before { content: "💵"; } /* Price */
    .form-group:nth-child(13)::before { content: "⏱️"; } /* Quantity */
    .form-group:nth-child(14)::before { content: "💱"; } /* Currency */
    .form-group:nth-child(15)::before { content: "⚙️"; } /* Operation Cost */

    /* Enhanced Buttons */
    .btn {
        border-radius: 10px;
        font-weight: 600;
        padding: 12px 24px;
        transition: all 0.3s ease;
        border: none;
        position: relative;
        overflow: hidden;
    }

    .btn-primary {
        background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
        box-shadow: 0 4px 15px rgba(59, 130, 246, 0.4);
    }

    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(59, 130, 246, 0.6);
    }

    .btn-secondary {
        background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
        box-shadow: 0 4px 15px rgba(107, 114, 128, 0.4);
    }

    .btn-secondary:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(107, 114, 128, 0.6);
    }

    .btn-success {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        box-shadow: 0 4px 15px rgba(16, 185, 129, 0.4);
    }

    .btn-success:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(16, 185, 129, 0.6);
    }

    /* Enhanced Table */
    .table {
        border-radius: 10px;
        overflow: hidden;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    }

    .table thead th {
        background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
        color: white;
        border: none;
        padding: 15px 10px;
        font-weight: 600;
        text-transform: uppercase;
        font-size: 12px;
        letter-spacing: 0.5px;
    }

    .table tbody tr {
        transition: all 0.3s ease;
        border-bottom: 1px solid #f1f5f9;
    }

    .table tbody tr:hover {
        background: #f0f9ff;
        transform: scale(1.01);
    }

    .table tbody td {
        padding: 12px 10px;
        vertical-align: middle;
        border: none;
    }

    /* Action Buttons */
    .btn-circle {
        border-radius: 50%;
        width: 35px;
        height: 35px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;
        margin: 0 2px;
    }

    .btn-circle:hover {
        transform: scale(1.1);
    }

    /* Enhanced Alerts */
    .alert {
        border-radius: 10px;
        border: none;
        padding: 15px 20px;
        margin-bottom: 20px;
        animation: slideInRight 0.5s ease forwards;
    }

    @keyframes slideInRight {
        from {
            opacity: 0;
            transform: translateX(50px);
        }
        to {
            opacity: 1;
            transform: translateX(0);
        }
    }

    /* Loading States */
    .loading {
        position: relative;
        pointer-events: none;
        opacity: 0.6;
    }

    .loading::after {
        content: "";
        position: absolute;
        top: 50%;
        left: 50%;
        width: 20px;
        height: 20px;
        margin: -10px 0 0 -10px;
        border: 2px solid #3b82f6;
        border-top: 2px solid transparent;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    /* Tooltips */
    .tooltip-inner {
        background: #1e40af;
        border-radius: 8px;
        font-size: 12px;
    }

    .tooltip.bs-tooltip-top .arrow::before {
        border-top-color: #1e40af;
    }

    /* Totals Section */
    .totals-card {
        background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
        color: white;
        border-radius: 15px;
        padding: 20px;
        margin-top: 20px;
        box-shadow: 0 8px 25px rgba(59, 130, 246, 0.3);
    }

    .totals-card p {
        margin: 5px 0;
        font-weight: 600;
        display: flex;
        justify-content: space-between;
    }

    .totals-card .total-label {
        opacity: 0.9;
    }

    .totals-card .total-value {
        font-weight: 700;
        font-size: 1.1em;
    }

    /* Modal Enhancements */
    .modal-content {
        border-radius: 15px;
        border: none;
        box-shadow: 0 20px 40px rgba(0,0,0,0.2);
    }

    .modal-header {
        background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
        color: #991b1b;
        border-bottom: none;
        border-radius: 15px 15px 0 0;
        padding: 20px;
    }

    .modal-body {
        padding: 25px;
        font-size: 16px;
    }

    /* Responsive Design */
    @media (max-width: 768px) {
        .container-fluid {
            padding: 15px;
        }

        .page-heading {
            padding: 15px;
            margin-bottom: 20px;
        }

        .card-body {
            padding: 15px;
        }

        .table-responsive {
            font-size: 12px;
        }

        .table thead th,
        .table tbody td {
            padding: 8px 5px;
        }

        .btn {
            padding: 10px 20px;
            font-size: 14px;
        }

        .totals-card {
            padding: 15px;
        }

        .totals-card p {
            font-size: 14px;
        }
    }
</style>

<div class="container-fluid">
    <!-- Enhanced Page Heading -->
    <div class="page-heading">
        <h1>Supplier Invoice Management</h1>
    </div>

    <!-- Form Section - Full Width -->
    <div class="row mb-5">
        <div class="col-12">
            <div class="card shadow mb-4">
                <!-- Card Header -->
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary" id="formHeader">Process Supplier Invoice</h6>
                </div>
                <!-- Card Body -->
                <div class="card-body">
                    @if (session('success'))
                        <div class="alert alert-success" id="successMessage" style="margin: 20px;">
                            {{ session('success') }}
                        </div>
                    @endif
                    @if ($errors->any())
                        <div class="form-group" id="errorMessage" style="margin: 20px;">
                            <div class="card bg-warning text-white shadow">
                                <div class="card-body">
                                    @foreach ($errors->all() as $error)
                                        <div style="color: red;">{{ $error }}</div>
                                    @endforeach
                                </div>
                            </div>
                        </div>
                    @endif

                    <form class="card-body" action="{{ route('modules.processing.supplier-invoice.store') }}" method="post" id="invoiceForm">
                        @csrf
                        <input type="hidden" name="_method" id="_method" value="POST">
                        <input type="hidden" id="invoiceId" name="id" value="">
                        <input type="hidden" name="source" value="supplier-invoice">

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    @php
                                        $oldSupplierId = old('supplier_id');
                                        $oldSupplierName = '';
                                        if ($oldSupplierId) {
                                            $matchedSupplier = $suppliers->firstWhere('supplier_id', (int) $oldSupplierId);
                                            $oldSupplierName = $matchedSupplier ? ($matchedSupplier->supplier_name ?? '') : '';
                                        }
                                    @endphp
                                    <label for="supplier_search">Select / Enter Supplier Name</label>
                                    <div class="position-relative">
                                        <input
                                            type="text"
                                            class="form-control form-control-user"
                                            id="supplier_search"
                                            name="supplier_search"
                                            placeholder="Search supplier"
                                            autocomplete="off"
                                            value="{{ old('supplier_search', $oldSupplierName) }}"
                                            required
                                        >
                                        <input type="hidden" id="supplier_id" name="supplier_id" value="{{ old('supplier_id') }}" required>
                                        <div id="supplier_suggestions" class="list-group position-absolute w-100 shadow-sm" style="z-index: 20; max-height: 220px; overflow-y: auto; display: none;"></div>
                                    </div>
                                    <small class="text-muted d-block mt-1">Start typing to search and select a supplier.</small>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="invoice_number">Invoice Number</label>
                                    <input type="text" class="form-control form-control-user" id="invoice_number" placeholder="e.g. INV-20250926-162120" name="invoice_number" value="{{ old('invoice_number', $nextSupplierInvoiceNumber ?? ('INV-' . now()->format('Ymd-His'))) }}" required>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="invoice_date">Date of Invoice</label>
                                    <input type="date" class="form-control form-control-user" id="invoice_date" placeholder="26/09/2025" name="invoice_date" value="{{ old('invoice_date', now()->format('Y-m-d')) }}" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="reference_number">Reference Number</label>
                                    <input type="text" class="form-control form-control-user" id="reference_number" placeholder="Supplier's reference" name="reference_number" value="{{ old('reference_number') }}" required>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="description">Description of Services / Goods</label>
                                    <input type="text" class="form-control form-control-user" id="description" placeholder="(e.g. Legal Research, Office Supplies)" name="description" value="{{ old('description') }}" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="contact_person">Contact Person</label>
                                    <input type="text" class="form-control form-control-user" id="contact_person" placeholder="(Supplier's contact)" name="contact_person" value="{{ old('contact_person') }}" required>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="narration">Narration / Additional Notes</label>
                                    <input type="text" class="form-control form-control-user" id="narration" placeholder="(Optional remarks)" name="narration" value="{{ old('narration') }}" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="reference">Reference</label>
                                    <input type="text" class="form-control form-control-user" id="reference" placeholder="(Internal reference)" name="reference" value="{{ old('reference') }}" required>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="gl_account">Billing Category / GL Account</label>
                                    <select class="form-control form-control-user" id="gl_account" name="gl_account" required>
                                        <option value="" disabled selected>(Professional Fees, Supplies, etc.)</option>
                                        @foreach ($glAccounts as $gl)
                                            <option value="{{ $gl->account_id }}">{{ $gl->code . '/' . $gl->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="tax">Applicable Tax</label>
                                    <select class="form-control form-control-user" id="tax" name="tax_id" required>
                                        <option value="" disabled selected>(VAT / Sales Tax if applicable)</option>
                                        @foreach ($taxes as $tax)
                                            <option value="{{ $tax->tax_id }}">{{ $tax->tax_rate }}% {{ $tax->tax_name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="discount">Discount %</label>
                                    <input type="number" class="form-control form-control-user" id="discount" placeholder="(If applicable)" name="discount" value="{{ old('discount') }}" step="0.01" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="price">Rate</label>
                                    <input type="number" class="form-control form-control-user" id="price" placeholder="(Unit price)" name="price" value="{{ old('price') }}" step="0.01" required>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="quantity">Quantity</label>
                                    <input type="number" class="form-control form-control-user" id="quantity" placeholder="(Units or hours)" name="quantity" value="{{ old('quantity') }}" min="1" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="currency">Currency</label>
                                    <select class="form-control form-control-user" id="currency" name="currency_id" required>
                                        <option value="" disabled selected>(USD, GBP, ZWL, etc.)</option>
                                        @foreach ($currencies as $currency)
                                            <option value="{{ $currency->currency_id }}">{{ $currency->currency_name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="operation_cost">Operation Cost</label>
                                    <input type="number" class="form-control form-control-user" id="operation_cost" placeholder="(Additional costs)" name="operation_cost" value="{{ old('operation_cost') }}" step="0.01">
                                </div>
                            </div>
                        </div>

                        <div style="display: flex; justify-content: center; margin-top: 30px;">
                            <input type="submit" style="width: 150px; height: 45px; margin-right: 15px;" value="Save" class="btn btn-primary btn-user btn-block" id="submitButton" onclick="updateURLAndSubmit(event)"/>
                            <input style="width: 150px; height: 45px;" type="reset" value="Refresh" class="btn btn-secondary btn-user btn-block" onclick="refreshForm()"/>
                        </div>
                        <hr>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Table Section - Full Width Below Form -->
    <div class="row">
        <div class="col-12">
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 style="float: left;" class="m-0 font-weight-bold text-primary">Supplier Transactions</h6>
                    @if($PermissionsAdd)
                        <a id="process" href="{{ route('modules.processing.supplier-invoice.process', ['invoice' => $batch ?? '']) }}" style="float: right; margin-top: -5px;" class="btn btn-success btn-icon-split">
                            <span class="icon text-white-50">
                                <i class="fas fa-check"></i>
                            </span>
                            <span class="text">Process</span>
                        </a>
                    @endif
                    <a href="{{ route('modules.processing') }}" style="float: right; margin-top: -5px; margin-left: 10px;" class="btn btn-primary btn-icon-split">
                        <span class="icon text-white-50">
                            <i class="fas fa-arrow-left"></i>
                        </span>
                        <span class="text">Back to Processing</span>
                    </a>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0" style="font-size: 14px;">
                            <thead>
                                <tr>
                                    <th style="padding: 12px;">Entry Date</th>
                                    <th style="padding: 12px;">Description</th>
                                    <th style="padding: 12px;">Account</th>
                                    <th style="padding: 12px;">Reference</th>
                                    <th style="padding: 12px;">Qty</th>
                                    <th style="padding: 12px;">Price</th>
                                    <th style="padding: 12px;">Disc</th>
                                    <th style="padding: 12px;">Tax %</th>
                                    <th style="padding: 12px;">Tax Amt</th>
                                    <th style="padding: 12px;">Total</th>
                                    <th style="padding: 12px;">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach ($supplierTransactions as $transaction)
                                    @php
                                        $invoiceData = [
                                            'id' => $transaction->id,
                                            'supplier_id' => $transaction->supplier_id,
                                            'invoice_number' => $transaction->invoice_number,
                                            'invoice_date' => optional($transaction->invoice_date)->format('Y-m-d'),
                                            'reference_number' => $transaction->reference_number ?? $transaction->reference ?? null,
                                            'description' => $transaction->description,
                                            'contact_person' => $transaction->contact_person ?? null,
                                            'narration' => $transaction->narration ?? null,
                                            'reference' => $transaction->reference ?? $transaction->reference_det ?? $transaction->reference_number ?? null,
                                            'gl_account' => $transaction->gl_account ?? null,
                                            'tax_id' => $transaction->tax_id ?? null,
                                            'discount' => $transaction->discount ?? 0,
                                            'price' => $transaction->price ?? 0,
                                            'quantity' => $transaction->quantity ?? 1,
                                            'currency_id' => $transaction->currency_id ?? null,
                                            'operation_cost' => $transaction->operation_cost ?? 0,
                                        ];
                                    @endphp
                                    <tr>
                                        <td>{{ $transaction->created_at->format('Y-m-d') }}</td>
                                        <td>{{ $transaction->description }}</td>
                                        <td>{{ $transaction->account }}</td>
                                        <td>{{ $transaction->reference }}</td>
                                        <td>{{ number_format($transaction->quantity, 2) }}</td>
                                        <td>{{ number_format($transaction->price, 2) }}</td>
                                        <td>{{ number_format($transaction->discount, 2) }}</td>
                                        <td>{{ number_format($transaction->tax_rate, 2) }}</td>
                                        <td>{{ number_format($transaction->tax_amount, 2) }}</td>
                                        <td>{{ number_format($transaction->total, 2) }}</td>
                                        <td style="justify-content: center; align-items: center;">
                                            @if($PermissionsEdit)
                                                <a href="#" class="btn btn-primary btn-circle" style="height: 30px; width: 30px;"
                                                   data-invoice='@json($invoiceData)'
                                                   onclick="editTransaction(event, this)">
                                                    <i class="fas fa-edit" style="font-size: 0.8em;"></i>
                                                </a>
                                            @endif
                                            @if($PermissionsPrint)
                                                <a href="{{ route('modules.processing.supplier-invoice.pdf', $transaction->id) }}" target="_blank" class="btn btn-info btn-circle" style="height: 30px; width: 30px;" title="Print PDF">
                                                    <i class="fas fa-print" style="font-size: 0.8em;"></i>
                                                </a>
                                            @endif
                                            @if($PermissionsDelete)
                                                <a href="#" style="height: 30px; width: 30px;" class="btn btn-danger btn-circle" onclick="confirmDelete('{{ $transaction->description }}', '{{ $transaction->reference }}', '{{ route('modules.processing.supplier-invoice.destroy', $transaction->id) }}'); return false;">
                                                    <i class="fas fa-trash" style="font-size: 0.8em;"></i>
                                                </a>
                                            @endif
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>

                        @if(isset($totals))
                        <div class="totals-card" style="margin-top: 30px;">
                            <h6 style="margin-bottom: 20px; text-align: center; font-weight: 700; font-size: 1.2em;">Invoice Summary</h6>
                            <p><span class="total-label">Total (Exc):</span> <span class="total-value">KES {{ number_format($totals['subtotal'], 2) }}</span></p>
                            <p><span class="total-label">Total (Tax):</span> <span class="total-value">KES {{ number_format($totals['tax'], 2) }}</span></p>
                            <p><span class="total-label">Total (Dis):</span> <span class="total-value">KES {{ number_format($totals['discount'], 2) }}</span></p>
                            <p style="border-top: 2px solid rgba(255,255,255,0.3); padding-top: 15px; margin-top: 15px;"><span class="total-label">Total (Inc):</span> <span class="total-value" style="font-size: 1.3em; color: #fbbf24;">KES {{ number_format($totals['total'], 2) }}</span></p>
                        </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Confirmation Modal -->
    <div class="modal fade" id="confirmDeleteModal" tabindex="-1" role="dialog" aria-labelledby="confirmDeleteModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="confirmDeleteModalLabel">Confirm Deletion</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    Are you sure you want to delete: <span id="deleteItemName"></span>?
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-danger" id="confirmDeleteButton">Delete</button>
                </div>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<!-- DataTables if not already included -->
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>

<script>
    const supplierLookup = @json($suppliers->map(function ($supplier) {
        return [
            'id' => $supplier->supplier_id,
            'name' => $supplier->supplier_name,
        ];
    })->values());
    const supplierNameById = new Map(supplierLookup.map(supplier => [String(supplier.id), supplier.name]));

    // Initialize Bootstrap 5 components
    const successAlert = document.getElementById('successMessage');
    const errorAlert = document.getElementById('errorMessage');
    if (successAlert) {
        new bootstrap.Alert(successAlert).show();
        setTimeout(() => successAlert.style.display = 'none', 5000);
    }
    if (errorAlert) {
        new bootstrap.Alert(errorAlert).show();
        setTimeout(() => errorAlert.style.display = 'none', 10000);
    }

    document.addEventListener('DOMContentLoaded', () => {
        const supplierSearchInput = document.getElementById('supplier_search');
        const supplierIdInput = document.getElementById('supplier_id');
        const supplierSuggestions = document.getElementById('supplier_suggestions');

        function closeSupplierSuggestions() {
            if (supplierSuggestions) {
                supplierSuggestions.style.display = 'none';
                supplierSuggestions.innerHTML = '';
            }
        }

        function renderSupplierSuggestions(matches) {
            if (!supplierSuggestions) return;
            supplierSuggestions.innerHTML = '';
            if (!matches.length) {
                closeSupplierSuggestions();
                return;
            }

            matches.forEach(match => {
                const item = document.createElement('button');
                item.type = 'button';
                item.className = 'list-group-item list-group-item-action';
                item.textContent = match.name;
                item.dataset.id = String(match.id);
                item.addEventListener('mousedown', (event) => {
                    event.preventDefault();
                    supplierIdInput.value = String(match.id);
                    supplierSearchInput.value = match.name;
                    closeSupplierSuggestions();
                });
                supplierSuggestions.appendChild(item);
            });

            supplierSuggestions.style.display = 'block';
        }

        function syncSupplierIdFromSearch() {
            if (!supplierSearchInput || !supplierIdInput) return;
            const searchValue = supplierSearchInput.value.trim().toLowerCase();

            if (!searchValue) {
                supplierIdInput.value = '';
                closeSupplierSuggestions();
                return;
            }

            const matches = supplierLookup.filter(supplier => supplier.name.toLowerCase().includes(searchValue));
            renderSupplierSuggestions(matches.slice(0, 20));

            const exactMatch = matches.find(supplier => supplier.name.toLowerCase() === searchValue);
            supplierIdInput.value = exactMatch ? String(exactMatch.id) : '';
        }

        if (supplierSearchInput && supplierIdInput) {
            supplierSearchInput.addEventListener('input', syncSupplierIdFromSearch);
            supplierSearchInput.addEventListener('change', syncSupplierIdFromSearch);

            if (supplierIdInput.value && !supplierSearchInput.value) {
                supplierSearchInput.value = supplierNameById.get(String(supplierIdInput.value)) || '';
            }
        }

        document.addEventListener('click', (event) => {
            if (!supplierSuggestions || !supplierSearchInput) return;
            const isInside = supplierSuggestions.contains(event.target) || supplierSearchInput.contains(event.target);
            if (!isInside) {
                closeSupplierSuggestions();
            }
        });
    });

    // Form Validation (Bootstrap 5)
    (function () {
        'use strict';
        const form = document.getElementById('invoiceForm');
        form.addEventListener('submit', function (event) {
            if (!form.checkValidity()) {
                event.preventDefault();
                event.stopPropagation();
            }
            form.classList.add('was-validated');
        }, false);
    })();

    // Real-time Total Preview Calculation
    function calculateTotal() {
        const price = parseFloat(document.getElementById('price').value) || 0;
        const quantity = parseInt(document.getElementById('quantity').value) || 1;
        const discount = parseFloat(document.getElementById('discount').value) || 0;
        const taxSelect = document.getElementById('tax');
        const taxRate = taxSelect.selectedOptions[0]?.dataset.rate || 0;

        const subtotal = price * quantity;
        const discountAmount = subtotal * (discount / 100);
        const taxable = subtotal - discountAmount;
        const taxAmount = taxable * (taxRate / 100);
        const total = taxable + taxAmount;

        const currencySelect = document.getElementById('currency');
        let symbol = 'KES';
        if (currencySelect && currencySelect.selectedOptions[0]) {
            const text = currencySelect.selectedOptions[0].textContent;
            const match = text.match(/\(([^)]+)\)/);
            symbol = match ? match[1] : 'KES';
        }

        document.getElementById('totalPreview').textContent = `${symbol} ${total.toFixed(2)}`;
    }

    // Attach event listeners for real-time calc
    ['price', 'quantity', 'discount', 'tax', 'currency'].forEach(id => {
        document.getElementById(id).addEventListener('input', calculateTotal);
        document.getElementById(id).addEventListener('change', calculateTotal);
    });
    calculateTotal(); // Initial calc

    function editTransaction(event, button) {
        event.preventDefault();
        const form = document.getElementById('invoiceForm');
        form.classList.add('loading');

        const invoice = JSON.parse(button.dataset.invoice || '{}');

        setTimeout(() => {
            setFormValues(invoice, 'Edit Supplier Invoice', 'Update');
            form.classList.remove('loading');
        }, 200);
    }

    function setFormValues(invoice, headerText, buttonText) {
        document.getElementById('invoiceId').value = invoice.id || '';

        const supplierSearchInput = document.getElementById('supplier_search');
        const supplierIdInput = document.getElementById('supplier_id');
        if (supplierSearchInput && supplierIdInput) {
            const supplierId = invoice.supplier_id ? String(invoice.supplier_id) : '';
            supplierIdInput.value = supplierId;
            supplierSearchInput.value = supplierNameById.get(supplierId) || '';
            supplierSearchInput.dispatchEvent(new Event('input'));
        }

        document.getElementById('invoice_number').value = invoice.invoice_number || '';
        document.getElementById('invoice_date').value = invoice.invoice_date || '';
        document.getElementById('reference_number').value = invoice.reference_number || '';
        document.getElementById('description').value = invoice.description || '';
        document.getElementById('contact_person').value = invoice.contact_person || '';
        document.getElementById('narration').value = invoice.narration || '';
        document.getElementById('reference').value = invoice.reference || '';
        document.getElementById('gl_account').value = invoice.gl_account || '';
        document.getElementById('tax').value = invoice.tax_id || '';
        document.getElementById('discount').value = invoice.discount ?? 0;
        document.getElementById('price').value = invoice.price ?? 0;
        document.getElementById('quantity').value = invoice.quantity ?? 1;
        document.getElementById('currency').value = invoice.currency_id || '';
        document.getElementById('operation_cost').value = invoice.operation_cost ?? 0;

        document.getElementById('formHeader').innerText = headerText;
        document.getElementById('submitButton').value = buttonText;

        if (buttonText === 'Update') {
            document.getElementById('_method').value = 'PUT';
            document.getElementById('invoiceForm').action = '/modules/processing/supplier-invoice/update/' + (invoice.id || '');
        } else {
            document.getElementById('_method').value = 'POST';
            document.getElementById('invoiceForm').action = '{{ route("modules.processing.supplier-invoice.store") }}';
        }

        calculateTotal();
    }

    // Refresh Form
    function refreshForm() {
        document.getElementById('invoiceForm').reset();
        document.getElementById('formHeader').innerHTML = '<i class="fas fa-file-invoice me-2"></i> Process New Supplier Invoice';
        document.getElementById('submitButton').innerHTML = '<i class="fas fa-save me-1"></i>Save Supplier Invoice';
        document.getElementById('_method').value = 'POST';
        document.getElementById('invoiceForm').action = '{{ route("modules.processing.supplier-invoice.store") }}';
        calculateTotal();
        // Reset validation
        document.getElementById('invoiceForm').classList.remove('was-validated');
    }

    // Confirm Delete
    function confirmDelete(name, reference, deleteUrl) {
        document.getElementById('deleteItemName').innerText = `${name} (Ref: ${reference})`;
        const modal = new bootstrap.Modal(document.getElementById('confirmDeleteModal'));
        modal.show();
        document.getElementById('confirmDeleteButton').onclick = function() {
            window.location.href = deleteUrl;
            modal.hide();
        };
    }

    // Update Process Button URL on Form Change
    document.getElementById('invoice_number').addEventListener('input', function() {
        const batchValue = this.value.trim();
        const processButton = document.getElementById('process');
        if (processButton && batchValue) {
            const url = new URL(processButton.href);
            url.searchParams.set('invoice', batchValue);
            processButton.href = url.toString();
        }
    });

    // Export Form Data Preview (Simple console/log for now; enhance with PDF/CSV if needed)
    function exportFormData() {
        const formData = new FormData(document.getElementById('invoiceForm'));
        const data = Object.fromEntries(formData);
        console.log('Form Data Export:', data);
        alert('Form data exported to console. Implement PDF/CSV download as needed.');
    }

        // Initialize DataTable (Enhanced)
        $(document).ready(function() {
            $('#dataTable').DataTable({
                responsive: true,
                pageLength: 10,
                order: [[0, 'desc']], // Sort by date descending
                columnDefs: [
                    { orderable: false, targets: -1 }, // Disable sort on Actions
                    { className: 'text-end', targets: [5,6,7,8,9,10] } // Right-align numbers
                ],
                dom: 'Bfrtip', // Add buttons if needed
                buttons: [
                    'copy', 'csv', 'excel', 'pdf', 'print'
                ],
                language: {
                    emptyTable: "No transactions available. Start by creating a supplier invoice!"
                }
            });

            // Calculate Grand Total from Table
            let grandTotal = 0;
            $('#dataTable tbody tr').each(function() {
                const totalCell = $(this).find('td').eq(10).text().replace(/^[A-Z]{3}\s/, '').replace(/,/g, '');
                if (totalCell) grandTotal += parseFloat(totalCell) || 0;
            });
            $('#grandTotal').text(`KES ${grandTotal.toFixed(2)}`);
        });

    // Auto-hide messages on refresh
    function hideMessages() {
        if (successAlert) successAlert.style.display = 'none';
        if (errorAlert) errorAlert.style.display = 'none';
    }
</script>
@endpush
@endsection
