@extends('layouts.dashboard.superadminapp')

@section('title', 'Tax Invoice List')

@section('styles')
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap4.min.css">
<style>
    /* ====== Modern Page Header ====== */
    .page-header-compact {
        background: linear-gradient(135deg, #ffffff 0%, #f9fafb 100%);
        border-radius: 12px;
        padding: 1.25rem 1.5rem;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        margin-bottom: 1.5rem;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 1rem;
    }

    .page-header-compact h1 {
        font-size: 1.25rem;
        font-weight: 600;
        color: #1f2937;
        margin: 0;
        display: flex;
        align-items: center;
    }

    .datetime-display {
        display: flex;
        gap: 1rem;
        align-items: center;
    }

    .datetime-display .time {
        font-size: 0.875rem;
        color: #6b7280;
        font-weight: 500;
        background: #f3f4f6;
        padding: 0.5rem 1rem;
        border-radius: 8px;
        font-family: 'SF Mono', Monaco, monospace;
    }

    /* ====== Modern Stat Cards ====== */
    .stat-card {
        background: #ffffff;
        border-radius: 12px;
        padding: 1.5rem;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        transition: all 0.3s ease;
        border-left: 4px solid;
        height: 100%;
    }

    .stat-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.12);
    }

    .stat-card.purple {
        border-left-color: #8b5cf6;
        background: linear-gradient(135deg, #ffffff 0%, #f5f3ff 100%);
    }

    .stat-card.green {
        border-left-color: #10b981;
        background: linear-gradient(135deg, #ffffff 0%, #f0fdf4 100%);
    }

    .stat-card.blue {
        border-left-color: #3b82f6;
        background: linear-gradient(135deg, #ffffff 0%, #eff6ff 100%);
    }

    .stat-card.amber {
        border-left-color: #f59e0b;
        background: linear-gradient(135deg, #ffffff 0%, #fffbeb 100%);
    }

    .stat-label {
        font-size: 0.75rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        color: #6b7280;
        margin-bottom: 0.5rem;
    }

    .stat-value {
        font-size: 1.75rem;
        font-weight: 700;
        color: #1f2937;
        line-height: 1.2;
    }

    .stat-icon {
        font-size: 2.5rem;
        opacity: 0.15;
        position: absolute;
        right: 1.5rem;
        bottom: 1.5rem;
    }

    /* ====== Modern Table Card ====== */
    .table-card {
        background: #ffffff;
        border-radius: 12px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        overflow: hidden;
        margin-bottom: 2rem;
    }

    .table-card-header {
        background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);
        color: #ffffff;
        padding: 1.25rem 1.5rem;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 1rem;
    }

    .table-card-header h5 {
        margin: 0;
        font-size: 1.125rem;
        font-weight: 600;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    .table-card-body {
        padding: 1.5rem;
    }

    /* ====== Modern DataTable Styling ====== */
    .table {
        margin-bottom: 0;
        font-size: 0.875rem;
    }

    .table thead th {
        background: linear-gradient(135deg, #f9fafb 0%, #f3f4f6 100%);
        border-bottom: 2px solid #e5e7eb;
        color: #374151;
        font-weight: 600;
        text-transform: uppercase;
        font-size: 0.75rem;
        letter-spacing: 0.5px;
        padding: 1rem;
        white-space: nowrap;
        vertical-align: middle;
    }

    .table tbody tr {
        transition: all 0.2s ease;
    }

    .table tbody tr:hover {
        background: linear-gradient(135deg, #faf5ff 0%, #f9fafb 100%);
    }

    .table tbody td {
        padding: 1rem;
        vertical-align: middle;
        border-bottom: 1px solid #f3f4f6;
        color: #4b5563;
        white-space: nowrap;
    }

    .table tbody td.wrap-text {
        white-space: normal;
        max-width: 200px;
    }

    /* ====== Modern Buttons ====== */
    .btn {
        border-radius: 8px;
        padding: 0.625rem 1.25rem;
        font-weight: 500;
        transition: all 0.2s ease;
        border: none;
        font-size: 0.875rem;
    }

    .btn:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    .btn-primary {
        background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);
        color: #ffffff;
    }

    .btn-primary:hover {
        box-shadow: 0 4px 12px rgba(139, 92, 246, 0.4);
    }

    .btn-light {
        background: #ffffff;
        color: #8b5cf6;
        border: 2px solid #8b5cf6;
    }

    .btn-light:hover {
        background: #8b5cf6;
        color: #ffffff;
    }

    .btn-sm {
        padding: 0.375rem 0.75rem;
        font-size: 0.8125rem;
    }

    .table-actions .btn {
        padding: 0.25rem 0.5rem;
        font-size: 0.75rem;
        margin: 0 2px;
    }

    /* ====== Modern Badges ====== */
    .badge {
        font-weight: 500;
        padding: 0.375rem 0.75rem;
        border-radius: 9999px;
        font-size: 0.75rem;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .badge-success {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        color: #ffffff;
    }

    .badge-warning {
        background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
        color: #ffffff;
    }

    .badge-danger {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        color: #ffffff;
    }

    /* ====== DataTable Controls ====== */
    .dataTables_wrapper .dataTables_filter input {
        border: 2px solid #e5e7eb;
        border-radius: 8px;
        padding: 0.5rem 1rem;
        transition: all 0.2s ease;
        font-size: 0.875rem;
    }

    .dataTables_wrapper .dataTables_filter input:focus {
        border-color: #8b5cf6;
        box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.1);
        outline: none;
    }

    .dataTables_wrapper .dataTables_length select {
        border: 2px solid #e5e7eb;
        border-radius: 8px;
        padding: 0.375rem 2rem 0.375rem 0.75rem;
        font-size: 0.875rem;
    }

    .dt-buttons .btn {
        background: #ffffff !important;
        color: #6b7280 !important;
        border: 1px solid #e5e7eb !important;
        border-radius: 8px !important;
        padding: 0.5rem 1rem !important;
        font-weight: 500;
        font-size: 0.875rem !important;
        margin-right: 0.5rem;
        transition: all 0.2s ease;
    }

    .dt-buttons .btn:hover {
        background: #f9fafb !important;
        border-color: #8b5cf6 !important;
        color: #8b5cf6 !important;
    }

    /* ====== Modern Modals ====== */
    .modal-content {
        border: none;
        border-radius: 12px;
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
        overflow: hidden;
    }

    .modal-header {
        padding: 1.25rem 1.5rem;
        border: none;
    }

    .modal-header.bg-danger {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%) !important;
    }

    .modal-header.bg-success {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important;
    }

    .modal-header.bg-secondary {
        background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%) !important;
    }

    .modal-header h6 {
        font-weight: 600;
    }

    .modal-body {
        padding: 1.5rem;
    }

    .modal-footer {
        border-top: 1px solid #f3f4f6;
        padding: 1rem 1.5rem;
        background: #f9fafb;
    }

    /* ====== Toast Notifications ====== */
    .toast {
        border-radius: 12px;
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
        border: none;
        overflow: hidden;
        animation: slideInRight 0.3s ease;
    }

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

    .toast.bg-success {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important;
    }

    .toast.bg-danger {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%) !important;
    }

    .toast-body {
        padding: 1rem 1.25rem;
    }

    /* ====== Form Controls ====== */
    .form-control {
        border: 2px solid #e5e7eb;
        border-radius: 8px;
        padding: 0.75rem 1rem;
        font-size: 0.875rem;
        transition: all 0.2s ease;
        background: #f9fafb;
    }

    .form-control:focus {
        border-color: #8b5cf6;
        box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.1);
        background: #ffffff;
        outline: none;
    }

    /* ====== Responsive ====== */
    @media (max-width: 768px) {
        .page-header-compact {
            flex-direction: column;
            align-items: flex-start;
        }

        .datetime-display {
            width: 100%;
            justify-content: space-between;
        }

        .stat-value {
            font-size: 1.5rem;
        }

        .table-card-header {
            flex-direction: column;
            align-items: flex-start;
        }
    }

    /* ====== Loading Spinner ====== */
    .spinner-border-sm {
        width: 1rem;
        height: 1rem;
        border-width: 2px;
    }
</style>
@endsection

@section('content')
    <!-- Modern Page Header -->
    <div class="page-header-compact">
        <h1>
            <i class="fas fa-file-invoice-dollar mr-2" style="color: #8b5cf6;"></i>
            Tax Invoice List
        </h1>
        <div class="datetime-display">
            <span class="time">
                <i class="far fa-clock mr-1"></i>
                <span id="currentTime"></span>
            </span>
        </div>
    </div>

    <!-- Modern Stat Cards -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="stat-card purple">
                <div class="stat-label">Total Invoices</div>
                <div class="stat-value">{{ $invoices->count() }}</div>
                <i class="fas fa-file-invoice stat-icon" style="color: #8b5cf6;"></i>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="stat-card green">
                <div class="stat-label">Total Amount</div>
                <div class="stat-value">₹{{ number_format($invoices->sum('total_amount'), 2) }}</div>
                <i class="fas fa-rupee-sign stat-icon" style="color: #10b981;"></i>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="stat-card blue">
                <div class="stat-label">Total Tax</div>
                <div class="stat-value">₹{{ number_format($invoices->sum('total_tax_amount'), 2) }}</div>
                <i class="fas fa-percentage stat-icon" style="color: #3b82f6;"></i>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="stat-card amber">
                <div class="stat-label">This Month</div>
                <div class="stat-value">{{ $invoices->where('invoice_date', '>=', now()->startOfMonth())->count() }}</div>
                <i class="fas fa-calendar-alt stat-icon" style="color: #f59e0b;"></i>
            </div>
        </div>
    </div>

    <!-- Modern Table Card -->
    <div class="table-card">
        <div class="table-card-header">
            <h5>
                <i class="fas fa-table"></i>
                Tax Invoices
            </h5>
            <a href="{{ route('superadmin.invoice.invoiceorder') }}" class="btn btn-light btn-sm">
                <i class="fa fa-plus-square mr-1"></i> Add New Invoice
            </a>
        </div>
        <div class="table-card-body">
            <div class="table-responsive">
                <table class="table table-hover" id="invoiceTable">
                    <thead>
                        <tr class="text-center">
                            <th>#</th>
                            <th>Invoice No</th>
                            <th>Date</th>
                            <th>Company</th>
                            <th>GST No</th>
                            <th>Buyer Order</th>
                            <th>Destination</th>
                            <th>Total Amount</th>
                            <th>Tax Amount</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($invoices as $index => $invoice)
                            <tr id="row-{{ $invoice->id }}" class="text-center">
                                <td>{{ $index + 1 }}</td>
                                <td class="font-weight-bold" style="color: #8b5cf6;">{{ $invoice->invoice_no }}</td>
                                <td>{{ \Carbon\Carbon::parse($invoice->invoice_date)->format('d M Y') }}</td>
                                <td class="text-left wrap-text">
                                    <strong>{{ $invoice->company?->company ?? '-' }}</strong>
                                    @if($invoice->company?->email)
                                        <br><small class="text-muted">{{ $invoice->company->email }}</small>
                                    @endif
                                </td>
                                <td><small>{{ $invoice->company?->gstno ?? '-' }}</small></td>
                                <td>{{ $invoice->buyer_order_no ?? '-' }}</td>
                                <td>{{ $invoice->destination ?? '-' }}</td>
                                <td class="text-right font-weight-bold" style="color: #10b981;">₹{{ number_format($invoice->total_amount, 2) }}</td>
                                <td class="text-right">₹{{ number_format($invoice->total_tax_amount, 2) }}</td>
                                <td>
                                    @php
                                        $status = $invoice->status ?? 'pending';
                                        $statusClass = match($status) {
                                            'approved' => 'success',
                                            'rejected' => 'danger',
                                            default => 'warning'
                                        };
                                    @endphp
                                    <span class="badge badge-{{ $statusClass }}">{{ ucfirst($status) }}</span>
                                </td>
                                <td>
                                    <div class="btn-group table-actions" role="group">
                                        <a href="{{ route('superadmin.invoice.show', $invoice->id) }}" class="btn btn-info btn-sm" title="View">
                                            <i class="fa fa-eye"></i>
                                        </a>
                                        <a href="{{ route('superadmin.invoice.print', $invoice->id) }}" target="_blank" class="btn btn-secondary btn-sm" title="Print">
                                            <i class="fa fa-print"></i>
                                        </a>
                                        @if(($invoice->status ?? 'pending') === 'pending')
                                            <button class="btn btn-success btn-sm approve-btn" data-id="{{ $invoice->id }}" data-invoice="{{ $invoice->invoice_no }}" title="Approve">
                                                <i class="fa fa-check"></i>
                                            </button>
                                            <button class="btn btn-warning btn-sm reject-btn" data-id="{{ $invoice->id }}" data-invoice="{{ $invoice->invoice_no }}" title="Reject">
                                                <i class="fa fa-times"></i>
                                            </button>
                                        @endif
                                        <a href="{{ route('superadmin.invoice.edit', $invoice->id) }}" class="btn btn-primary btn-sm" title="Edit">
                                            <i class="fa fa-edit"></i>
                                        </a>
                                        <button class="btn btn-danger btn-sm delete-btn" data-id="{{ $invoice->id }}" data-invoice="{{ $invoice->invoice_no }}" title="Delete">
                                            <i class="fa fa-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h6 class="modal-title mb-0">
                        <i class="fas fa-exclamation-triangle mr-2"></i>Delete Invoice
                    </h6>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p class="mb-1">Are you sure you want to delete this invoice?</p>
                    <p class="mb-0 font-weight-bold" id="deleteItemName"></p>
                    <small class="text-muted">This action cannot be undone.</small>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-danger btn-sm" id="confirmDeleteBtn">
                        <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                        <span class="btn-text">Delete</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Approval Modal -->
    <div class="modal fade" id="approvalModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header" id="approvalModalHeader">
                    <h6 class="modal-title mb-0 text-white" id="approvalModalTitle"></h6>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p class="mb-2" id="approvalMessage"></p>
                    <p class="mb-3 font-weight-bold" id="approvalItemName"></p>
                    <div class="form-group">
                        <label for="approvalRemarks">Remarks (Optional)</label>
                        <textarea class="form-control" id="approvalRemarks" rows="3" placeholder="Enter remarks..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-sm" id="confirmApprovalBtn">
                        <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                        <span class="btn-text">Confirm</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('scripts')
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.colVis.min.js"></script>
<script>
$(document).ready(function() {
    // Live DateTime
    function updateDateTime() {
        const now = new Date();
        const timeStr = now.toLocaleTimeString('en-IN', {
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: true
        });
        $('#currentTime').text(timeStr);
    }
    updateDateTime();
    setInterval(updateDateTime, 1000);

    // Initialize DataTable
    var table = $('#invoiceTable').DataTable({
        dom: '<"row"<"col-sm-12 col-md-6"B><"col-sm-12 col-md-6"f>>rtip',
        buttons: [
            { extend: 'copy', className: 'btn btn-sm' },
            { extend: 'csv', className: 'btn btn-sm' },
            { extend: 'excel', className: 'btn btn-sm' },
            { extend: 'pdf', className: 'btn btn-sm' },
            { extend: 'print', className: 'btn btn-sm' }
        ],
        pageLength: 10,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
        order: [[1, 'desc']],
        columnDefs: [
            { orderable: false, targets: [10] }
        ],
        language: {
            emptyTable: "No invoices found"
        }
    });

    // Delete button click
    var deleteId = null;
    $(document).on('click', '.delete-btn', function() {
        deleteId = $(this).data('id');
        $('#deleteItemName').text($(this).data('invoice'));
        $('#deleteModal').modal('show');
    });

    // Confirm delete
    $('#confirmDeleteBtn').on('click', function() {
        if (!deleteId) return;

        var $btn = $(this);
        var $spinner = $btn.find('.spinner-border');
        var $text = $btn.find('.btn-text');

        $btn.prop('disabled', true);
        $spinner.removeClass('d-none');
        $text.text('Deleting...');

        $.ajax({
            url: '{{ url("/superadmin/invoices") }}/' + deleteId,
            type: 'DELETE',
            data: { '_token': '{{ csrf_token() }}' },
            success: function(response) {
                $('#deleteModal').modal('hide');
                table.row('#row-' + deleteId).remove().draw(false);
                showToast('success', response.message || 'Invoice deleted successfully!');
            },
            error: function(xhr) {
                showToast('error', xhr.responseJSON?.message || 'Failed to delete invoice.');
            },
            complete: function() {
                $btn.prop('disabled', false);
                $spinner.addClass('d-none');
                $text.text('Delete');
                deleteId = null;
            }
        });
    });

    // Toast notification helper
    function showToast(type, message) {
        var bgClass = type === 'success' ? 'bg-success' : 'bg-danger';
        var icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';

        var toastHtml = `
            <div class="toast ${bgClass} text-white" role="alert" aria-live="assertive" aria-atomic="true" data-delay="3000" style="position: fixed; top: 20px; right: 20px; z-index: 9999; min-width: 280px;">
                <div class="toast-body d-flex align-items-center">
                    <i class="fas ${icon} mr-2"></i>
                    <span>${message}</span>
                    <button type="button" class="ml-auto close text-white" data-dismiss="toast" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </div>
        `;

        var $toast = $(toastHtml);
        $('body').append($toast);
        $toast.toast('show');

        $toast.on('hidden.bs.toast', function() {
            $(this).remove();
        });
    }

    // Approval functionality
    var approvalId = null;
    var approvalAction = null;

    // Approve button click
    $(document).on('click', '.approve-btn', function() {
        approvalId = $(this).data('id');
        approvalAction = 'approve';
        $('#approvalModalHeader').removeClass('bg-secondary bg-danger').addClass('bg-success');
        $('#approvalModalTitle').html('<i class="fas fa-check-circle mr-2"></i>Approve Invoice');
        $('#approvalMessage').text('Are you sure you want to approve this invoice?');
        $('#approvalItemName').text($(this).data('invoice'));
        $('#confirmApprovalBtn').removeClass('btn-secondary btn-danger').addClass('btn-success');
        $('#confirmApprovalBtn .btn-text').text('Approve');
        $('#approvalRemarks').val('');
        $('#approvalModal').modal('show');
    });

    // Reject button click
    $(document).on('click', '.reject-btn', function() {
        approvalId = $(this).data('id');
        approvalAction = 'reject';
        $('#approvalModalHeader').removeClass('bg-success bg-danger').addClass('bg-secondary');
        $('#approvalModalTitle').html('<i class="fas fa-times-circle mr-2"></i>Reject Invoice');
        $('#approvalMessage').text('Are you sure you want to reject this invoice?');
        $('#approvalItemName').text($(this).data('invoice'));
        $('#confirmApprovalBtn').removeClass('btn-success btn-danger').addClass('btn-secondary');
        $('#confirmApprovalBtn .btn-text').text('Reject');
        $('#approvalRemarks').val('');
        $('#approvalModal').modal('show');
    });

    // Confirm approval/rejection
    $('#confirmApprovalBtn').on('click', function() {
        if (!approvalId || !approvalAction) return;

        var $btn = $(this);
        var $spinner = $btn.find('.spinner-border');
        var $text = $btn.find('.btn-text');

        $btn.prop('disabled', true);
        $spinner.removeClass('d-none');
        $text.text(approvalAction === 'approve' ? 'Approving...' : 'Rejecting...');

        $.ajax({
            url: '{{ url("/superadmin/invoices") }}/' + approvalId + '/' + approvalAction,
            type: 'POST',
            data: {
                '_token': '{{ csrf_token() }}',
                'remarks': $('#approvalRemarks').val()
            },
            success: function(response) {
                $('#approvalModal').modal('hide');
                showToast('success', response.message || 'Invoice ' + approvalAction + 'd successfully!');
                // Reload page to update status
                setTimeout(function() { location.reload(); }, 1000);
            },
            error: function(xhr) {
                showToast('error', xhr.responseJSON?.message || 'Failed to ' + approvalAction + ' invoice.');
            },
            complete: function() {
                $btn.prop('disabled', false);
                $spinner.addClass('d-none');
                $text.text(approvalAction === 'approve' ? 'Approve' : 'Reject');
                approvalId = null;
                approvalAction = null;
            }
        });
    });
});
</script>
@endsection
