@include('admin.layouts.header')
@include('admin.layouts.sidebar')
<div class="m-grid__item m-grid__item--fluid m-wrapper">
    <div class="m-subheader ">
        <div class="d-flex align-items-center">
            <div class="mr-auto">
                <h3 class="m-subheader__title m-subheader__title--separator">
                    UCIC
                </h3>
            </div>
        </div>
    </div>
    <div class="m-content">
        @if(Session::has('success'))
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close"></button>
                {{ Session::get('success') }}
            </div>
        @endif
        @if(Session::has('error'))
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close"></button>
                {{ Session::get('error') }}
            </div>
        @endif

        <div class="m-portlet m-portlet--mobile">
            <div class="m-portlet__head">
                <div class="m-portlet__head-caption">
                    <div class="m-portlet__head-title">
                        <h3 class="m-portlet__head-text">
                            Disbursed Applications
                        </h3>
                    </div>
                </div>
            </div>
            <div class="m-portlet__body">
                <!-- Filters -->
                <form method="GET" action="{{ url('/admin/ucic') }}" class="mb-4">
                    <div class="row">
                        <div class="col-md-3">
                            <label>Application ID</label>
                            <input type="text" class="form-control" name="application_id" placeholder="Application ID" value="{{ $applicationId ?? '' }}">
                        </div>
                        <div class="col-md-2">
                            <label>From Date</label>
                            <input type="date" class="form-control" name="from_date" value="{{ $fromDate ?? '' }}">
                        </div>
                        <div class="col-md-2">
                            <label>To Date</label>
                            <input type="date" class="form-control" name="to_date" value="{{ $toDate ?? '' }}">
                        </div>
                        <div class="col-md-3">
                            <label>UCIC Status</label>
                            <select name="ucic_status" class="form-control">
                                <option value="">All Statuses</option>
                                <option value="create_ucic" {{ (isset($ucicStatus) && $ucicStatus == 'create_ucic') ? 'selected' : '' }}>Create UCIC</option>
                                <option value="ucic_generated" {{ (isset($ucicStatus) && $ucicStatus == 'ucic_generated') ? 'selected' : '' }}>UCIC Generated</option>
                            </select>
                        </div>
                        <div class="col-md-2" style="margin-top: 28px;">
                            <button type="submit" class="btn btn-primary">Filter</button>
                            <a href="{{ url('/admin/ucic') }}" class="btn btn-secondary">Reset</a>
                        </div>
                    </div>
                </form>

                <!-- Data Table -->
                <div class="table-responsive">
                    <table class="table table-striped table-bordered table-hover table-checkable">
                        <thead>
                            <tr>
                                <th>Application ID</th>
                                <th>Customer Name</th>
                                <th>Merchant Name</th>
                                <th>UCIC ID</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($applications as $app)
                                <tr>
                                    <td>{{ $app->id }}</td>
                                    <td>{{ $app->name }}</td>
                                    <td>{{ $app->merchant->merchant_name }}</td>
                                    <td>
                                        @php
                                            $ucic = $app->ucicDetail;
                                            $coUcic = $app->coUcicDetail;
                                            $hasCoApp = !empty($app->co_applicant_name);
                                            
                                            $applicantSuccess = ($ucic && $ucic->status === 'success');
                                            $coApplicantSuccess = ($coUcic && $coUcic->status === 'success');
                                        @endphp
                                        <div class="d-flex flex-column" style="min-width: 180px;">
                                            <div class="d-flex align-items-center justify-content-between py-1">
                                                <span class="text-muted small m--font-bold mr-3" style="font-size: 0.85rem;">
                                                    <i class="la la-user m--font-info mr-1" style="font-size: 1.1rem; vertical-align: middle;"></i> Applicant
                                                </span>
                                                @if($applicantSuccess && $ucic->ucic_id)
                                                    <span class="m-badge m-badge--success m-badge--wide" style="font-family: monospace; font-weight: 600; font-size: 0.85rem; padding: 4px 10px; border-radius: 4px;">{{ $ucic->ucic_id }}</span>
                                                @else
                                                    <span class="m-badge m-badge--secondary m-badge--wide text-muted" style="font-size: 0.8rem; padding: 4px 10px; border-radius: 4px; background-color: #f4f5f8; font-weight: 500;">N/A</span>
                                                @endif
                                            </div>
                                            @if($hasCoApp)
                                                <div class="d-flex align-items-center justify-content-between py-1 mt-1" style="border-top: 1px dashed #ebedf2;">
                                                    <span class="text-muted small m--font-bold mr-3" style="font-size: 0.85rem;">
                                                        <i class="la la-users m--font-brand mr-1" style="font-size: 1.1rem; vertical-align: middle;"></i> Co-Applicant
                                                    </span>
                                                    @if($coApplicantSuccess && $coUcic->ucic_id)
                                                        <span class="m-badge m-badge--success m-badge--wide" style="font-family: monospace; font-weight: 600; font-size: 0.85rem; padding: 4px 10px; border-radius: 4px;">{{ $coUcic->ucic_id }}</span>
                                                    @else
                                                        <span class="m-badge m-badge--secondary m-badge--wide text-muted" style="font-size: 0.8rem; padding: 4px 10px; border-radius: 4px; background-color: #f4f5f8; font-weight: 500;">N/A</span>
                                                    @endif
                                                </div>
                                            @endif
                                        </div>
                                    </td>
                                    <td>
                                        @php
                                            $isFullyGenerated = $applicantSuccess && (!$hasCoApp || $coApplicantSuccess);
                                        @endphp
                                        @if($isFullyGenerated)
                                            <button class="btn btn-sm btn-success" disabled>
                                                <i class="la la-check"></i> UCIC Generated
                                            </button>
                                        @else
                                            <button class="btn btn-sm btn-info btn-create-ucic" data-id="{{ $app->id }}">
                                                <i class="la la-cog"></i> Create UCIC
                                            </button>
                                        @endif
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="5" class="text-center">No disbursed applications found.</td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>

                <div class="mt-3">
                    {{ $applications->appends(request()->query())->links() }}
                </div>
            </div>
        </div>

    </div>
</div>

@include("admin.layouts.footer")

<script>
    $(document).ready(function() {
        $('.btn-create-ucic').on('click', function(e) {
            e.preventDefault();
            var appId = $(this).data('id');
            var btn = $(this);
            
            // Add loading state
            btn.addClass('m-loader m-loader--right m-loader--light').attr('disabled', true);
            
            $.ajax({
                url: '/admin/ucic/generate_ucic',
                type: 'GET',
                data: { application_id: appId },
                success: function(response) {
                    alert('UCIC successfully created for Application ' + appId);
                    btn.removeClass('btn-info m-loader m-loader--right m-loader--light')
                       .addClass('btn-success')
                       .html('<i class="la la-check"></i> UCIC Generated');
                    // Note: button stays disabled
                },
                error: function(xhr) {
                    var errorMsg = 'Failed to create UCIC';
                    if (xhr.responseJSON && xhr.responseJSON.error) {
                        var apiError = xhr.responseJSON.error;
                        if (typeof apiError === 'string') {
                            errorMsg = apiError;
                        } else if (apiError && apiError.error && apiError.error.message) {
                            errorMsg = apiError.error.message;
                            if (apiError.error.validationErrors && apiError.error.validationErrors.length > 0) {
                                var vErrors = apiError.error.validationErrors.map(function(e) { 
                                    return '- ' + e.msg + ' (param: ' + e.param + ', value: ' + e.value + ')'; 
                                }).join('\n');
                                errorMsg += '\n' + vErrors;
                            }
                        } else if (typeof apiError === 'object') {
                            errorMsg = apiError.message || JSON.stringify(apiError);
                            if (apiError.details && Array.isArray(apiError.details) && apiError.details.length > 0) {
                                var detailErrors = apiError.details.map(function(d) { return '- ' + d; }).join('\n');
                                errorMsg += '\n' + detailErrors;
                            }
                        }
                    } else if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMsg = xhr.responseJSON.message;
                    }
                    
                    alert('Error:\n' + errorMsg);
                    btn.removeClass('m-loader m-loader--right m-loader--light').attr('disabled', false);
                }
            });
        });
    });
</script>

