@extends('layouts.master')

@section('title', 'Client Receipt - ')

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

{{-- Select2 CDN --}}
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<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-select {
        border: 2px solid #e5e7eb;
        border-radius: 10px;
        padding: 12px 15px;
        font-size: 14px;
        transition: all 0.3s ease;
        background: #f9fafb;
    }

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

    /* 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);
    }

    .btn-danger {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        box-shadow: 0 4px 15px rgba(239, 68, 68, 0.4);
    }

    .btn-danger:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(239, 68, 68, 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;
    }

    /* 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);
        }
    }

    .alert-success {
        background: linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%);
        color: #166534;
        border-left: 4px solid #16a34a;
    }

    /* 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;
        overflow: visible;
    }

        .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;
        }
    }

    /* 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;
    }

    /* Payment Items Table Enhancements */
    #paymentItemsTable {
        margin-bottom: 20px;
    }

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

    #paymentItemsTable tbody td {
        padding: 8px;
        vertical-align: middle;
    }

    #paymentItemsTable .form-control {
        border: 1px solid #d1d5db;
        border-radius: 6px;
        padding: 6px 8px;
        font-size: 13px;
    }

    #paymentItemsTable .form-select {
        border: 1px solid #d1d5db;
        border-radius: 6px;
        padding: 6px 8px;
        font-size: 13px;
    }

    #paymentItemsTable .btn-danger {
        padding: 4px 8px;
        font-size: 12px;
    }

    #paymentItemsTable-wrapper {
        overflow: visible !important;
    }

    .invoice-picker {
        position: relative;
    }

    .invoice-suggestions {
        z-index: 3000;
        background: #fff;
    }

    /* Section Header */
    .section-header {
        background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
        padding: 15px;
        border-radius: 10px;
        margin-bottom: 20px;
        border: 1px solid #e2e8f0;
    }

    .section-header i {
        color: #3b82f6;
        font-size: 1.1em;
    }

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

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

    .btn-circle i {
        font-size: 14px;
    }

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

    .totals-summary p {
        margin: 0;
        font-weight: 600;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .totals-summary .total-label {
        opacity: 0.9;
        font-size: 14px;
    }

    .totals-summary .total-value {
        font-size: 18px;
        font-weight: 700;
    }

    /* Select2 styling to match inputs */
    .select2-container--bootstrap-5 .select2-selection {
        min-height: 48px;
        border: 2px solid #e5e7eb;
        border-radius: 10px;
        background: #f9fafb;
        padding: 6px 12px;
        font-size: 14px;
        transition: all 0.3s ease;
    }

    .select2-container--bootstrap-5 .select2-selection--single .select2-selection__rendered {
        line-height: 32px;
        color: #374151;
    }

    .select2-container--bootstrap-5 .select2-selection--single .select2-selection__arrow {
        height: 44px;
    }

    .select2-container--bootstrap-5 .select2-dropdown {
        border-radius: 10px;
        border: 1px solid #e5e7eb;
        box-shadow: 0 10px 30px rgba(0,0,0,0.12);
        z-index: 3000;
    }
</style>

<div class="container-fluid">
    <!-- Enhanced Page Heading -->
    <div class="page-heading">
        <h1>Client Receipt 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">{{ isset($receipt) ? 'Edit Receipt' : 'Process Receipt' }}</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 method="POST" action="{{ isset($receipt) ? route('modules.processing.client-receipt.update', $receipt->id) : route('modules.processing.client-receipt.store') }}" id="receiptForm" autocomplete="off">
                        @method(isset($receipt) ? 'PUT' : 'POST')
                        @csrf

                        <div class="row mb-4">
                            <div class="col-md-6">
                                <div class="section-header">
                                    <i class="fas fa-user me-2"></i> Client Information
                                </div>

                                <div class="form-group">
                                    <label for="client_id">Client <span class="text-danger">*</span></label>
                                    <select name="client_id" class="form-select" id="clientSelect" required>
                                        <option value="">Select client (type to search)</option>
                                        @foreach($clients as $client)
                                            @php
                                                $clientValue = $client->id;
                                            @endphp
                                            <option value="{{ $clientValue }}"
                                                data-address="{{ $client->street_address ?? '' }}"
                                                data-phone="{{ $client->phone_primary ?? '' }}"
                                                data-email="{{ $client->email ?? '' }}"
                                                data-vat="{{ $client->vat ?? '' }}"
                                                data-tin="{{ $client->tin ?? '' }}"
                                                {{ (isset($receipt) && $receipt->client_id == $clientValue) || old('client_id') == $clientValue ? 'selected' : '' }}>
                                                {{ $client->full_name ?? ($client->client_name ?? trim(($client->first_name ?? '') . ' ' . ($client->last_name ?? ''))) }}
                                            </option>
                                        @endforeach
                                    </select>
                                    <small class="text-muted">Please select a client first to enable invoice selection</small>
                                </div>

                                <div class="form-group">
                                    <label for="clientAddress">Address</label>
                                    <input type="text" class="form-control" id="clientAddress" readonly>
                                </div>

                                <div class="form-group">
                                    <label for="clientPhone">Phone</label>
                                    <input type="text" class="form-control" id="clientPhone" readonly>
                                </div>

                                <div class="form-group">
                                    <label for="clientEmail">Email</label>
                                    <input type="email" class="form-control" id="clientEmail" readonly>
                                </div>

                                <div class="form-group">
                                    <label for="invoiceSelect">Invoice</label>
                                    <select class="form-select" id="invoiceSelect" disabled>
                                        <option value="">Select client first</option>
                                    </select>
                                    <input type="hidden" id="globalInvoiceId">
                                    <small class="text-muted" id="invoiceHelpText">Select the invoice to link this receipt to a client invoice.</small>
                                </div>

                                <div class="form-group">
                                    <label>Taxes</label>
                                    <p class="text-muted mb-0">Receipt taxes are recorded on invoices; receipts allocate payments only.</p>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="section-header">
                                    <i class="fas fa-receipt me-2"></i> Receipt Details
                                </div>

                                <div class="form-group">
                                    <label for="receipt_number">Receipt Number <span class="text-danger">*</span></label>
                                    @php
                                        $receiptNumberValue = old('receipt_number');
                                        if (!is_string($receiptNumberValue) || trim($receiptNumberValue) === '' || str_contains($receiptNumberValue, '{' . '{')) {
                                            $receiptNumberValue = null;
                                        }
                                        $receiptNumberValue = $receiptNumberValue ?? ($receipt->receipt_number ?? ($nextReceiptNumber ?? ''));
                                    @endphp
                                    <input type="text" name="receipt_number" class="form-control" id="receipt_number"
                                           value="{{ $receiptNumberValue }}" required>
                                </div>

                                <div class="form-group">
                                    <label for="receipt_date">Receipt Date <span class="text-danger">*</span></label>
                                    @php
                                        $receiptDateValue = old('receipt_date');
                                        $validDate = is_string($receiptDateValue) && preg_match('/^\\d{4}-\\d{2}-\\d{2}$/', $receiptDateValue);
                                        if (!$validDate) {
                                            $receiptDateValue = isset($receipt)
                                                ? $receipt->receipt_date->format('Y-m-d')
                                                : now()->format('Y-m-d');
                                        }
                                    @endphp
                                    <input type="date" name="receipt_date" class="form-control" id="receipt_date"
                                           value="{{ $receiptDateValue }}" required>
                                </div>

                                  <input type="hidden" name="payment_method" value="trust_transfer">
                                  <input type="hidden" id="receiptTotalAmountValue" value="{{ isset($receipt) ? number_format((float) $receipt->total_amount, 2, '.', '') : '0.00' }}">
                            </div>
                        </div>

                        <div class="row mb-4">
                            <div class="col-12">
                                <div class="section-header">
                                    <i class="fas fa-list me-2"></i> Payment Items
                                </div>

                                <div class="table-responsive" id="paymentItemsTable-wrapper">
                                    <table class="table table-bordered" id="paymentItemsTable">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>Description</th>
                                                <th>Account</th>
                                                <th>Amount</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <!-- Lines will be added dynamically -->
                                        </tbody>
                                    </table>
                                </div>

                                <button type="button" class="btn btn-primary" id="addLineBtn">
                                    <i class="fas fa-plus"></i> Add Payment Line
                                </button>
                            </div>
                        </div>

                        <div class="row mb-4">
                            <div class="col-12">
                                <div class="totals-summary">
                                    <p>
                                        <span class="total-label">Sub Total:</span>
                                        <span class="total-value" id="subTotalAmount">$0.00</span>
                                    </p>
                                    <p>
                                        <span class="total-label">Tax Total:</span>
                                        <span class="total-value" id="taxTotalAmount">$0.00</span>
                                    </p>
                                    <p>
                                        <span class="total-label">Grand Total:</span>
                                        <span class="total-value" id="totalAmount">$0.00</span>
                                    </p>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-12 text-center">
                                <button type="submit" class="btn btn-success" id="processReceiptBtn">
                                    <i class="fas fa-save"></i> {{ isset($receipt) ? 'Update Receipt' : 'Process Receipt' }}
                                </button>
                                <a href="{{ route('modules.processing.client-billing') }}" class="btn btn-secondary">
                                    <i class="fas fa-arrow-left"></i> Back to Client Billing
                                </a>
                            </div>
                        </div>
                    </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 class="m-0 font-weight-bold text-primary">Client Receipts</h6>
                    @if($PermissionsAdd)
                        <a href="{{ route('modules.processing.client-receipt.create') }}" class="btn btn-success btn-icon-split" style="float: right; margin-top: -5px;">
                            <span class="icon text-white-50">
                                <i class="fas fa-plus"></i>
                            </span>
                            <span class="text">Add Receipt</span>
                        </a>
                    @endif
                    @if($PermissionsAdd)
                        <a href="{{ route('modules.processing.client-receipt.process', ['receipt' => $batch ?? '']) }}" style="float: right; margin-top: -5px; margin-right: 10px;" class="btn btn-primary btn-icon-split">
                            <span class="icon text-white-50">
                                <i class="fas fa-check"></i>
                            </span>
                            <span class="text">Process</span>
                        </a>
                    @endif
                </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>Receipt Date</th>
                                    <th>Receipt Number</th>
                                    <th>Client</th>
                                    <th>Payment Method</th>
                                    <th>Total Amount</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach ($clientReceipts as $listReceipt)
                                    <tr>
                                        <td>{{ $listReceipt->receipt_date->format('Y-m-d') }}</td>
                                        <td>{{ $listReceipt->receipt_number }}</td>
                                        <td>{{ $listReceipt->client->full_name ?? 'N/A' }}</td>
                                        <td>{{ $listReceipt->payment_methods_label ?: (ucfirst(str_replace('_',' ', $listReceipt->payment_method ?? 'N/A'))) }}</td>
                                        <td>{{ number_format($listReceipt->total_amount, 2) }}</td>
                                        <td>
                                            <span class="badge badge-{{ $listReceipt->status == 'processed' ? 'success' : 'warning' }}">
                                                {{ ucfirst($listReceipt->status) }}
                                            </span>
                                        </td>
                                        <td style="justify-content: center; align-items: center;">
                                            @if($PermissionsEdit)
                                                <a href="{{ route('modules.processing.client-receipt.edit', $listReceipt->id) }}" class="btn btn-primary btn-sm me-1">Edit</a>
                                            @endif
                                            @if($PermissionsAdd)
                                                <a href="{{ route('modules.processing.client-receipt.process', ['receipt' => $listReceipt->id]) }}" class="btn btn-success btn-sm me-1">Process</a>
                                            @endif
                                            @if($PermissionsPrint)
                                                <a href="{{ route('modules.processing.client-receipt.pdf', $listReceipt->id) }}" target="_blank" class="btn btn-info btn-sm me-1">Print</a>
                                            @endif
                                            @if($PermissionsDelete)
                                                <a href="#" class="btn btn-danger btn-sm" onclick="confirmDelete('{{ $listReceipt->receipt_number }}', '{{ $listReceipt->client->full_name ?? 'N/A' }}', '{{ route('modules.processing.client-receipt.destroy', $listReceipt->id) }}'); return false;">Delete</a>
                                            @endif
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </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>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const clientSelect = document.getElementById('clientSelect');
    const invoiceSelect = document.getElementById('invoiceSelect');
    const globalInvoiceId = document.getElementById('globalInvoiceId');
    const invoiceHelpText = document.getElementById('invoiceHelpText');
    const invoiceApiBase = "{{ url('/api/clients') }}";
    const isEditingReceipt = {{ isset($receipt) ? 'true' : 'false' }};
    const editingReceiptId = "{{ $receipt->id ?? '' }}";

    window.addEventListener('pageshow', function(event) {
        if (event.persisted && editingReceiptId) {
            window.location.reload();
        }
    });
    const receiptTotalAmountValue = document.getElementById('receiptTotalAmountValue');

    if (window.$ && $.fn.select2) {
        $('#clientSelect').select2({
            theme: 'bootstrap-5',
            placeholder: 'Type to search clients...',
            allowClear: true,
            width: '100%',
            minimumInputLength: 1,
            matcher: function(params, data) {
                if ($.trim(params.term) === '') {
                    return null;
                }
                if (typeof data.text === 'undefined') {
                    return null;
                }
                const term = params.term.toLowerCase();
                const text = data.text.toLowerCase();
                const email = data.element?.dataset?.email?.toLowerCase() || '';
                const phone = data.element?.dataset?.phone?.toLowerCase() || '';
                if (text.indexOf(term) > -1 || email.indexOf(term) > -1 || phone.indexOf(term) > -1) {
                    return data;
                }
                return null;
            },
            language: {
                inputTooShort: function() {
                    return 'Start typing to search clients...';
                },
                searching: function() {
                    return 'Searching...';
                },
                noResults: function() {
                    return 'No matching clients';
                }
            }
        });
    }

    function setInputValue(id, value) {
        const el = document.getElementById(id);
        if (el) el.value = value || '';
    }

    function setInvoiceState(isClientSelected) {
        if (!invoiceSelect) return;
        invoiceSelect.disabled = !isClientSelected;
        invoiceSelect.innerHTML = isClientSelected
            ? '<option value=\"\">Select invoice</option>'
            : '<option value=\"\">Select client first</option>';
        if (invoiceHelpText) {
            invoiceHelpText.textContent = isClientSelected
                ? 'Select the invoice to link this receipt to a client invoice.'
                : 'Select a client to see available invoices.';
        }
        if (globalInvoiceId) globalInvoiceId.value = '';
        document.querySelectorAll('.invoice-id').forEach(h => h.value = '');
    }

    function handleClientChange() {
        // Clear client info
        setInputValue('clientAddress', '');
        setInputValue('clientPhone', '');
        setInputValue('clientEmail', '');

        const selectedOption = clientSelect.options[clientSelect.selectedIndex];
        if (selectedOption && clientSelect.value) {
            setInputValue('clientAddress', selectedOption.dataset.address || '');
            setInputValue('clientPhone', selectedOption.dataset.phone || '');
            setInputValue('clientEmail', selectedOption.dataset.email || '');
        }

        // Reset invoice state
        window.clientInvoices = [];
        setInvoiceState(!!clientSelect.value);
        loadInvoicesForClient(clientSelect.value || '');
        resetAmountInputs();
    }

    clientSelect.addEventListener('change', handleClientChange);
    if (window.$ && $.fn.select2) {
        $('#clientSelect').on('select2:select select2:clear', handleClientChange);
    }

    if (clientSelect) {
        if (clientSelect.value) {
            clientSelect.dispatchEvent(new Event('change'));
        } else {
            setInvoiceState(false);
        }
    }

    function setGlobalInvoiceId(value) {
        if (globalInvoiceId) {
            globalInvoiceId.value = value || '';
        }
        document.querySelectorAll('.invoice-id').forEach(h => h.value = value || '');
    }

    function resetAmountInputs() {
        if (isEditingReceipt) return;
        document.querySelectorAll('.amount-input').forEach(i => {
            i.value = '';
            i.defaultValue = '';
        });
        updateTotals();
    }

    function syncEditAmounts() {
        if (!isEditingReceipt) return;
        document.querySelectorAll('.amount-input').forEach(i => {
            const applied = i.getAttribute('data-applied');
            if (applied !== null) {
                i.value = applied;
                i.defaultValue = applied;
            }
        });
        updateTotals();
    }

    function selectInvoice(inv) {
        const balance = Number(inv.balance_due ?? 0);
        setGlobalInvoiceId(String(inv.id || ''));

          const firstRow = document.querySelector('#paymentItemsTable tbody tr');
          if (firstRow) {
              const accountSelect = firstRow.querySelector('.account-select');
              if (accountSelect && inv.gl_account_id && !accountSelect.value) {
                  accountSelect.value = String(inv.gl_account_id);
                  accountSelect.dispatchEvent(new Event('change'));
              }
          }
      }

    function loadInvoicesForClient(clientId) {
        if (!invoiceSelect) return;
        if (!clientId) {
            setInvoiceState(false);
            return;
        }

        invoiceSelect.disabled = true;
        invoiceSelect.innerHTML = '<option value=\"\">Loading invoices...</option>';
        if (invoiceHelpText) {
            invoiceHelpText.textContent = 'Checking for invoices linked to this client...';
        }

        fetch(`${invoiceApiBase}/${encodeURIComponent(clientId)}/invoices`)
            .then(r => r.ok ? r.json() : [])
            .then(list => {
                window.clientInvoices = Array.isArray(list) ? list : [];
                invoiceSelect.disabled = false;
                invoiceSelect.innerHTML = '<option value=\"\">Select invoice</option>';

                if (!window.clientInvoices.length) {
                    invoiceSelect.innerHTML = '<option value=\"\">No invoices for this client</option>';
                    invoiceSelect.disabled = true;
                    if (invoiceHelpText) {
                        invoiceHelpText.textContent = 'No invoices found for this client.';
                    }
                    return;
                }

                window.clientInvoices.forEach(inv => {
                    const balance = Number(inv.balance_due ?? 0);
                    const invoiceNo = inv.invoice_number || 'N/A';
                    const display = inv.display || `${invoiceNo} — Balance: $${balance.toFixed(2)}`;
                    const opt = document.createElement('option');
                    opt.value = String(inv.id || '');
                    opt.textContent = display;
                    invoiceSelect.appendChild(opt);
                });

                if (invoiceHelpText) {
                    invoiceHelpText.textContent = 'Select the invoice to link this receipt to a client invoice.';
                }

                const preselectId = globalInvoiceId?.value;
                if (preselectId) {
                    invoiceSelect.value = preselectId;
                    const inv = window.clientInvoices.find(i => String(i.id || '') === String(preselectId));
                    if (inv) {
                        selectInvoice(inv);
                    }
                }
            })
            .catch(() => {
                invoiceSelect.disabled = false;
                invoiceSelect.innerHTML = '<option value=\"\">Error loading invoices</option>';
                if (invoiceHelpText) {
                    invoiceHelpText.textContent = 'Unable to load invoices. Please try again.';
                }
            });
    }

    if (invoiceSelect) {
        invoiceSelect.addEventListener('change', function() {
            const selectedId = this.value;
            const inv = (window.clientInvoices || []).find(i => String(i.id || '') === String(selectedId));
            if (inv) {
                selectInvoice(inv);
            } else {
                setGlobalInvoiceId('');
            }
        });
    }

    // ── Row HTML builder ────────────────────────────────────────────────────
    function buildRowHTML(idx) {
        return `
            <td>${idx + 1}</td>
            <td>
              <input type="text" name="lines[${idx}][description]" class="form-control form-control-sm" required>
              <input type="hidden" name="lines[${idx}][invoice_id]" class="invoice-id">
            </td>
            <td>
              <select name="lines[${idx}][account_id]" class="form-select form-control-sm account-select" required>
                <option value="">Select Account</option>
                @foreach($glAccounts as $account)
                  <option value="{{ $account->id }}">{{ $account->code }} - {{ $account->account_name }}</option>
                @endforeach
              </select>
            </td>
            <td><input type="number" name="lines[${idx}][amount]" class="form-control form-control-sm amount-input" min="0.01" step="0.01" value="" placeholder="0.00" required autocomplete="off"></td>
            <td class="text-center">
              <button type="button" class="btn btn-sm btn-danger remove-line"><i class="fas fa-trash-alt"></i></button>
            </td>`;
    }

    document.getElementById('addLineBtn').addEventListener('click', function() {
        const tbody = document.querySelector('#paymentItemsTable tbody');
        const idx   = tbody.children.length;
        const row   = document.createElement('tr');
        row.innerHTML = buildRowHTML(idx);
        tbody.appendChild(row);
        if (globalInvoiceId && globalInvoiceId.value) {
            row.querySelector('.invoice-id').value = globalInvoiceId.value;
        }
        row.querySelector('.amount-input').addEventListener('input', updateTotals);
        row.querySelector('.remove-line').addEventListener('click', () => {
            row.remove(); renumberRows(); updateTotals();
        });
        updateTotals();
        resetAmountInputs();
    });

    // ── Table helpers ───────────────────────────────────────────────────────
    function renumberRows() {
        document.querySelectorAll('#paymentItemsTable tbody tr')
            .forEach((r, i) => r.querySelector('td:first-child').textContent = i + 1);
    }

    function updateTotals() {
        let subTotal = 0;
        document.querySelectorAll('.amount-input').forEach(i => subTotal += parseFloat(i.value) || 0);
        document.getElementById('subTotalAmount').textContent = '$' + subTotal.toFixed(2);
        document.getElementById('taxTotalAmount').textContent = '$0.00';
        document.getElementById('totalAmount').textContent    = '$' + subTotal.toFixed(2);
    }

    function addExistingLine(data) {
        const tbody = document.querySelector('#paymentItemsTable tbody');
        const idx   = tbody.children.length;
        const row   = document.createElement('tr');
        row.innerHTML = buildRowHTML(idx);
        // Patch in existing values
        row.querySelector('[name="lines[' + idx + '][description]"]').value = data.description ?? '';
        const amountInput = row.querySelector('[name="lines[' + idx + '][amount]"]');
        const appliedValue = data.amount_applied ?? '0.00';
        amountInput.value = appliedValue;
        amountInput.setAttribute('data-applied', appliedValue);
        amountInput.defaultValue = appliedValue;
        row.querySelector('[name="lines[' + idx + '][invoice_id]"]').value = data.invoice_id ?? '';
        tbody.appendChild(row);
        row.querySelector('.amount-input').addEventListener('input', updateTotals);
        row.querySelector('.remove-line').addEventListener('click', () => {
            row.remove(); renumberRows(); updateTotals();
        });
        if (data.account_id) {
            const accountSelect = row.querySelector('.account-select');
            accountSelect.value = String(data.account_id);
            accountSelect.dispatchEvent(new Event('change'));
        }
        updateTotals();
    }

    // ── Init ────────────────────────────────────────────────────────────────
    @if(isset($receipt))
        @foreach($receipt->lines as $line)
            addExistingLine({
                description:    '{{ addslashes($line->description) }}',
                invoice_id:     '{{ $line->invoice_id }}',
                account_id:     '{{ $line->account_id }}',
            amount_applied: '{{ $line->amount }}'
            });
        @endforeach
        const firstExistingInvoice = document.querySelector('.invoice-id')?.value;
        if (firstExistingInvoice) {
            setGlobalInvoiceId(firstExistingInvoice);
        }
        syncEditAmounts();
        if (document.querySelectorAll('.amount-input').length === 0 && receiptTotalAmountValue) {
            const fallbackTotal = parseFloat(receiptTotalAmountValue.value) || 0;
            document.getElementById('subTotalAmount').textContent = '$' + fallbackTotal.toFixed(2);
            document.getElementById('totalAmount').textContent    = '$' + fallbackTotal.toFixed(2);
        }
    @else
        document.getElementById('addLineBtn').click();
        resetAmountInputs();
    @endif

    window.editReceipt = function(event, receiptId) {
        event.preventDefault();
        window.location.href = `/modules/processing/client-receipt/${receiptId}/edit`;
    };

    window.confirmDelete = function(receiptNumber, clientName, deleteUrl) {
        document.getElementById('deleteItemName').textContent = `${receiptNumber} for ${clientName}`;
        document.getElementById('confirmDeleteButton').onclick = function() {
            window.location.href = deleteUrl;
        };
        $('#confirmDeleteModal').modal('show');
    };

    document.getElementById('processReceiptBtn').addEventListener('click', () => {
        const form = document.getElementById('receiptForm');
        if (form.checkValidity()) {
            form.submit();
        } else {
            form.reportValidity();
        }
    });
});
</script>
@endsection
