@extends('layouts.master')

@section('title', 'Client Receipt - Prolex Law Firm')

@section('content')
@php
$PermissionsAdd = Auth::check() ? Auth::user()->hasPermission('add-receipt') : false;
$PermissionsEdit = Auth::check() ? Auth::user()->hasPermission('edit-receipt') : false;
$PermissionsDelete = Auth::check() ? Auth::user()->hasPermission('delete-receipt') : 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-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;
        }

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

    /* 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;
    }
</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">
                        @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> Customer Information
                                </div>

                                <div class="form-group">
                                    <label for="customer_id">Customer <span class="text-danger">*</span></label>
                                    <select name="customer_id" class="form-select" id="customerSelect" required>
                                        <option value="">Select Customer</option>
                                        @foreach($clients as $client)
                                            <option value="{{ $client->id }}"
                                                data-address="{{ $client->address ?? '' }}"
                                                data-phone="{{ $client->contact_1 ?? '' }}"
                                                data-email="{{ $client->email ?? '' }}"
                                                data-vat="{{ $client->vat ?? '' }}"
                                                data-tin="{{ $client->tin ?? '' }}"
                                                {{ isset($receipt) && $receipt->client_id == $client->id ? 'selected' : '' }}>
                                                {{ $client->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>

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

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

                                <div class="form-group">
                                    <label for="customerEmail">Email</label>
                                    <input type="email" class="form-control" id="customerEmail" readonly>
                                </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>
                                    <input type="text" name="receipt_number" class="form-control" id="receipt_number"
                                           value="{{ isset($receipt) ? $receipt->receipt_number : 'RCP-' . now()->format('Y') . '-' . str_pad(\App\Models\ClientReceipt::count() + 1, 4, '0', STR_PAD_LEFT) }}" required>
                                </div>

                                <div class="form-group">
                                    <label for="receipt_date">Receipt Date <span class="text-danger">*</span></label>
                                    <input type="date" name="receipt_date" class="form-control" id="receipt_date"
                                           value="{{ isset($receipt) ? $receipt->receipt_date->format('Y-m-d') : now()->format('Y-m-d') }}" required>
                                </div>

                                <div class="form-group">
                                    <label for="payment_method">Payment Method <span class="text-danger">*</span></label>
                                    <select name="payment_method" class="form-select" id="payment_method" required>
                                        <option value="">Select Payment Method</option>
                                        @foreach($paymentMethods as $method)
                                            <option value="{{ $method }}" {{ isset($receipt) && $receipt->payment_method == $method ? 'selected' : '' }}>
                                                {{ $method }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                            </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">
                                    <table class="table table-bordered" id="paymentItemsTable">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>Description</th>
                                                <th>Invoice</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">Total Amount:</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') }}" class="btn btn-secondary">
                                    <i class="fas fa-arrow-left"></i> Back to Client
                                </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>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach ($clientReceipts as $receipt)
                                    <tr>
                                        <td>{{ $receipt->receipt_date->format('Y-m-d') }}</td>
                                        <td>{{ $receipt->receipt_number }}</td>
                                        <td>{{ $receipt->client->name ?? 'N/A' }}</td>
                                        <td>{{ $receipt->payment_method }}</td>
                                        <td>{{ number_format($receipt->total_amount, 2) }}</td>
                                        <td>
                                            <span class="badge badge-{{ $receipt->status == 'Processed' ? 'success' : 'warning' }}">
                                                {{ $receipt->status }}
                                            </span>
                                        </td>
                                        <td style="justify-content: center; align-items: center;">
                                            @if($PermissionsEdit)
                                                <a href="{{ route('modules.processing.client-receipt.edit', $receipt->id) }}" class="btn btn-primary btn-circle" style="height: 30px; width: 30px;" title="Edit">
                                                    <i class="fas fa-edit" 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('{{ $receipt->receipt_number }}', '{{ $receipt->client->name ?? 'N/A' }}', '{{ route('modules.processing.client-receipt.destroy', $receipt->id) }}'); return false;" title="Delete">
                                                    <i class="fas fa-trash" style="font-size: 0.8em;"></i>
                                                </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() {
    // populate customer info
    document.getElementById('customerSelect').addEventListener('change', function() {
        const o = this.options[this.selectedIndex];
        document.getElementById('customerAddress').value = o.dataset.address||'';
        document.getElementById('customerPhone').value   = o.dataset.phone||'';
        document.getElementById('customerEmail').value   = o.dataset.email||'';
        document.getElementById('customerVat').value     = o.dataset.vat||'';
        document.getElementById('customerTin').value     = o.dataset.tin||'';
        if (this.value) {
            fetch(`/api/customers/${this.value}/invoices`)
              .then(r=>r.json()).then(data=>{
                window.customerInvoices = data;
                document.querySelectorAll('.invoice-select').forEach(s=>updateInvoiceDropdown(s));
              });
        }
    });

    // add line
    document.getElementById('addLineBtn').addEventListener('click', function() {
        const tbody = document.querySelector('#paymentItemsTable tbody');
        const idx   = tbody.children.length;
        const row   = document.createElement('tr');
        row.innerHTML = `
            <td>${idx+1}</td>
            <td><input type="text" name="lines[${idx}][description]" class="form-control form-control-sm" required></td>
            <td>
              <select name="lines[${idx}][invoice_id]" class="form-select form-control-sm invoice-select">
                <option value="">Select Invoice</option>
                ${generateInvoiceOptions()}
              </select>
            </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" required></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>`;
        tbody.appendChild(row);
        row.querySelector('.amount-input').addEventListener('input', updateTotals);
        row.querySelector('.remove-line').addEventListener('click', ()=>{
            row.remove(); renumberRows(); updateTotals();
        });
        updateInvoiceDropdown(row.querySelector('.invoice-select'));
    });

    function generateInvoiceOptions(){
        if (!window.customerInvoices) return '';
        return window.customerInvoices.map(inv=>
            `<option value="${inv.id}" data-amount="${inv.balance_due}">
               ${inv.invoice_number} - Balance: $${inv.balance_due.toFixed(2)}
             </option>`
        ).join('');
    }
    
    function updateInvoiceDropdown(sel){
        const cur=sel.value;
        sel.innerHTML=`<option value="">Select Invoice</option>`+generateInvoiceOptions();
        sel.value=cur;
    }
    
    document.addEventListener('change', function(e){
        if (e.target.classList.contains('invoice-select')){
            const so = e.target.options[e.target.selectedIndex];
            if (so.value){
                e.target.closest('tr').querySelector('.amount-input').value = parseFloat(so.dataset.amount||0).toFixed(2);
                updateTotals();
            }
        }
    });

    function renumberRows(){
        document.querySelectorAll('#paymentItemsTable tbody tr').forEach((r,i)=>r.querySelector('td:first-child').textContent = i+1);
    }
    
    function updateTotals(){
        let t=0;
        document.querySelectorAll('.amount-input').forEach(i=>t+=parseFloat(i.value)||0);
        document.getElementById('totalAmount').textContent = '$'+t.toFixed(2);
    }

    function addExistingLine(data) {
        const tbody = document.querySelector('#paymentItemsTable tbody');
        const idx = tbody.children.length;
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${idx+1}</td>
            <td><input type="text" name="lines[${idx}][description]" class="form-control form-control-sm" value="${data.description}" required></td>
            <td>
              <select name="lines[${idx}][invoice_id]" class="form-select form-control-sm invoice-select">
                <option value="">Select Invoice</option>
                ${generateInvoiceOptions()}
              </select>
            </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->id == data.account_id ? 'selected' : '' }}>{{ $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="${data.amount}" required></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>`;
        tbody.appendChild(row);
        row.querySelector('.amount-input').addEventListener('input', updateTotals);
        row.querySelector('.remove-line').addEventListener('click', ()=>{
            row.remove(); renumberRows(); updateTotals();
        });
        updateInvoiceDropdown(row.querySelector('.invoice-select'));
        if (data.invoice_id) {
            row.querySelector('.invoice-select').value = data.invoice_id;
        }
    }

    // init one line or load existing lines
    @if(isset($receipt))
        @foreach($receipt->lines as $line)
            addExistingLine({
                description: '{{ $line->description }}',
                invoice_id: '{{ $line->invoice_id }}',
                account_id: '{{ $line->account_id }}',
                amount: '{{ $line->amount }}'
            });
        @endforeach
    @else
        document.getElementById('addLineBtn').click();
    @endif

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

    // confirm delete
    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');
    };

    // show print modal
    document.getElementById('processReceiptBtn').addEventListener('click', ()=>{
        // Validate form first
        const form = document.getElementById('receiptForm');
        if (form.checkValidity()) {
            // Submit the form directly since no print modal in prolex
            form.submit();
        } else {
            form.reportValidity();
        }
    });
});
</script>
@endsection

