@extends('admin.layouts.app')

@section('content')

<style>

/* ==========================================================
   REPORT PAGE
========================================================== */

.reports-page {
    width: 100%;
    max-width: 100%;
    margin: 0;
    padding: 0 4px 35px;
    box-sizing: border-box;
}


/* ==========================================================
   PAGE HEADER
========================================================== */

.reports-page .page-header {
    margin-bottom: 20px;
}

.reports-page .page-header h1 {
    margin: 0 0 5px;
    line-height: 1.2;
    font-size: 28px;
    font-weight: 700;
}

.reports-page .page-header p {
    margin: 0;
    font-size: 14px;
    color: #64748b;
}

.report-page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 18px;
}

.report-actions {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}

.report-print-btn,
.report-pdf-btn {
    white-space: nowrap;
}


/* ==========================================================
   DATE FILTER
========================================================== */

.reports-page .report-filter-card {
    margin: 0 0 20px;
    border: 1px solid #e5e7eb;
    border-radius: 12px;
}

.reports-page .report-filter-card .card-body {
    padding: 18px 20px;
}

.reports-page .report-filter-grid {
    display: grid;

    grid-template-columns:
        minmax(180px, 1fr)
        minmax(180px, 1fr)
        115px
        115px;

    gap: 14px;

    align-items: end;
}

.reports-page .report-filter-field {
    min-width: 0;
}

.reports-page .report-filter-field label {
    display: block;

    margin: 0 0 7px;

    font-size: 13px;

    font-weight: 600;

    color: #334155;
}

.reports-page .report-filter-field input[type="date"] {
    width: 100%;

    height: 42px;

    box-sizing: border-box;

    border-radius: 8px;

    border: 1px solid #dbe3ee;

    font-size: 13px;

    padding: 0 12px;

    color: #334155;

    background: #ffffff;

    outline: none;
}

.reports-page .report-filter-field input[type="date"]:focus {
    border-color: #2563eb;

    box-shadow:
        0 0 0 3px
        rgba(37, 99, 235, 0.08);
}

.reports-page .report-filter-action {
    min-width: 0;
}

.reports-page .report-filter-action button,
.reports-page .report-filter-action a {
    width: 100%;

    height: 42px;

    display: flex;

    align-items: center;

    justify-content: center;

    box-sizing: border-box;

    border-radius: 8px;

    font-size: 13px;
}


/* ==========================================================
   SUMMARY CARDS
========================================================== */

.reports-page .report-summary-grid {
    display: grid;

    grid-template-columns:
        repeat(4, minmax(0, 1fr));

    gap: 14px;

    margin: 0 0 20px;
}

.reports-page .report-summary-item {
    min-width: 0;
}

.reports-page .report-summary-item .card {
    width: 100%;

    height: 100%;

    margin: 0;

    border-radius: 12px;

    border: 1px solid #e5e7eb;
}

.reports-page .report-summary-item .card-body {
    padding: 18px 20px;

    min-height: 105px;

    box-sizing: border-box;
}

.reports-page .report-summary-item h6 {
    margin: 0 0 8px;

    font-size: 13px;

    font-weight: 600;

    color: #64748b;
}

.reports-page .report-summary-item h2 {
    margin: 0;

    font-size: 25px;

    line-height: 1.2;

    font-weight: 600;

    color: #1e293b;
}


/* ==========================================================
   REPORT CARDS
========================================================== */

.reports-page .report-card {
    width: 100%;

    margin: 0 0 20px;

    border-radius: 12px;

    border: 1px solid #e5e7eb;

    overflow: hidden;

    transition: opacity 0.15s ease;
}

.reports-page .report-card:last-child {
    margin-bottom: 0;
}

.reports-page .report-card .card-body {
    padding: 20px;
}

.reports-page .report-card.report-loading {
    opacity: 0.55;
}

.reports-page .report-card-header {
    display: flex;

    align-items: center;

    justify-content: space-between;

    gap: 18px;

    margin: 0 0 16px;
}

.reports-page .report-card-header-left {
    min-width: 0;
}

.reports-page .report-card-header h3 {
    margin: 0 0 4px;

    font-size: 19px;

    line-height: 1.3;

    font-weight: 600;

    color: #1e293b;
}

.reports-page .report-card-header p {
    margin: 0;

    font-size: 13px;

    color: #64748b;
}

.reports-page .report-header-tools {
    display: flex;

    align-items: center;

    justify-content: flex-end;

    gap: 10px;

    flex-wrap: wrap;
}

.reports-page .report-header-tools strong {
    white-space: nowrap;

    font-size: 13px;

    font-weight: 500;

    color: #64748b;
}

.report-table-pdf-btn {
    white-space: nowrap;
}


/* ==========================================================
   TABLE FILTER
========================================================== */

.report-table-filter {
    display: flex;

    align-items: center;

    gap: 7px;

    margin: 0;
}

.report-table-filter label {
    margin: 0;

    font-size: 12px;

    font-weight: 600;

    color: #64748b;

    white-space: nowrap;
}

.report-table-filter select {
    width: 145px;

    height: 36px;

    padding: 0 30px 0 10px;

    border: 1px solid #dbe3ee;

    border-radius: 8px;

    background-color: #ffffff;

    color: #334155;

    font-size: 13px;

    font-weight: 400;

    outline: none;

    cursor: pointer;
}

.report-table-filter select:focus {
    border-color: #2563eb;

    box-shadow:
        0 0 0 3px
        rgba(37, 99, 235, 0.08);
}


/* ==========================================================
   TABLE
========================================================== */

.reports-page .table-responsive {
    width: 100%;

    overflow-x: auto;

    margin: 0;

    border-radius: 8px;
}

.reports-page table {
    width: 100%;

    min-width: 780px;

    margin: 0;

    border-collapse: collapse;
}

.reports-page table th,
.reports-page table td {
    vertical-align: middle;

    padding: 10px 12px;

    font-size: 13px;

    line-height: 1.4;

    font-weight: 400;

    color: #334155;

    white-space: nowrap;
}

.reports-page table th {
    font-size: 12px;

    font-weight: 600;

    color: #475569;

    background: #f8fafc;

    white-space: nowrap;
}

.reports-page table td {
    background: #ffffff;
}

.reports-page table tbody tr:hover td {
    background: #f8fafc;
}


/* ==========================================================
   COLUMN ALIGNMENT
========================================================== */

.collection-table th:nth-child(1),
.collection-table td:nth-child(1) {
    width: 12%;
}

.collection-table th:nth-child(2),
.collection-table td:nth-child(2) {
    width: 19%;
}

.collection-table th:nth-child(3),
.collection-table td:nth-child(3) {
    width: 15%;
}

.collection-table th:nth-child(4),
.collection-table td:nth-child(4) {
    width: 15%;
}

.collection-table th:nth-child(5),
.collection-table td:nth-child(5) {
    width: 13%;
}

.collection-table th:nth-child(6),
.collection-table td:nth-child(6) {
    width: 12%;
}

.collection-table th:nth-child(7),
.collection-table td:nth-child(7) {
    width: 14%;
}

.loan-table th:nth-child(1),
.loan-table td:nth-child(1) {
    width: 16%;
}

.loan-table th:nth-child(2),
.loan-table td:nth-child(2) {
    width: 22%;
}

.loan-table th:nth-child(3),
.loan-table td:nth-child(3) {
    width: 17%;
}

.loan-table th:nth-child(4),
.loan-table td:nth-child(4) {
    width: 16%;
}

.loan-table th:nth-child(5),
.loan-table td:nth-child(5) {
    width: 17%;
}

.loan-table th:nth-child(6),
.loan-table td:nth-child(6) {
    width: 12%;
}


/* ==========================================================
   AMOUNT
========================================================== */

.report-amount {
    text-align: right !important;

    white-space: nowrap;

    font-weight: 400 !important;
}


/* ==========================================================
   STATUS / TYPE NORMAL TEXT
========================================================== */

.payment-type-text {
    font-weight: 400;

    color: #334155;
}

.loan-status-text {
    font-weight: 400;

    color: #334155;
}


/* ==========================================================
   PAGINATION
========================================================== */

.reports-page .report-pagination {
    margin-top: 18px;

    width: 100%;
}

.reports-page .report-pagination nav {
    margin: 0;
}

.reports-page .report-pagination nav > div:first-child {
    display: none !important;
}

.reports-page .report-pagination nav > div:last-child {
    display: flex !important;

    align-items: center;

    justify-content: space-between;

    gap: 20px;

    width: 100%;
}

.reports-page .report-pagination nav > div:last-child > div:first-child {
    color: #64748b;

    font-size: 13px;
}

.reports-page .report-pagination nav > div:last-child > div:last-child {
    display: flex;

    align-items: center;
}

.reports-page .report-pagination nav a,
.reports-page .report-pagination nav span {
    display: inline-flex;

    align-items: center;

    justify-content: center;

    min-width: 34px;

    height: 34px;

    padding: 0 9px;

    margin-left: 4px;

    border-radius: 7px;

    text-decoration: none;

    font-size: 13px;

    font-weight: 500;

    box-sizing: border-box;
}

.reports-page .report-pagination nav a {
    color: #2563eb;

    background: #ffffff;

    border: 1px solid #e2e8f0;
}

.reports-page .report-pagination nav a:hover {
    background: #f1f5f9;
}

.reports-page .report-pagination nav span[aria-current="page"] {
    color: #ffffff;

    background: #2563eb;

    border: 1px solid #2563eb;
}

.reports-page .report-pagination nav span[aria-disabled="true"] {
    color: #94a3b8;

    background: #f8fafc;

    border: 1px solid #e2e8f0;
}

.reports-page .report-pagination nav svg {
    width: 15px !important;

    height: 15px !important;

    display: block;
}


/* ==========================================================
   TABLET
========================================================== */

@media (max-width: 1100px) {

    .reports-page .report-summary-grid {
        grid-template-columns:
            repeat(2, minmax(0, 1fr));
    }

    .reports-page .report-filter-grid {
        grid-template-columns:
            1fr
            1fr
            110px
            110px;
    }

}


/* ==========================================================
   MOBILE
========================================================== */

@media (max-width: 700px) {

    .reports-page {
        padding: 0 2px 20px;
    }

    .reports-page .page-header {
        margin-bottom: 15px;
    }

    .reports-page .page-header h1 {
        font-size: 24px;
    }

    .report-page-header {
        align-items: flex-start;

        flex-direction: column;

        gap: 12px;
    }

    .report-actions {
        width: 100%;
    }

    .report-print-btn,
    .report-pdf-btn {
        flex: 1;
    }


    /* DATE FILTER */

    .reports-page .report-filter-card .card-body {
        padding: 15px;
    }

    .reports-page .report-filter-grid {
        grid-template-columns: 1fr;

        gap: 11px;
    }

    .reports-page .report-filter-action {
        width: 100%;
    }


    /* SUMMARY */

    .reports-page .report-summary-grid {
        grid-template-columns: 1fr;

        gap: 11px;

        margin-bottom: 15px;
    }

    .reports-page .report-summary-item .card-body {
        min-height: auto;

        padding: 15px 17px;
    }

    .reports-page .report-summary-item h2 {
        font-size: 22px;
    }


    /* REPORT CARD */

    .reports-page .report-card {
        margin-bottom: 15px;
    }

    .reports-page .report-card .card-body {
        padding: 15px;
    }

    .reports-page .report-card-header {
        align-items: flex-start;

        flex-direction: column;

        gap: 11px;

        margin-bottom: 12px;
    }

    .reports-page .report-card-header h3 {
        font-size: 18px;
    }

    .reports-page .report-header-tools {
        width: 100%;

        justify-content: space-between;

        align-items: center;
    }

    .report-table-filter {
        flex: 1;

        min-width: 0;
    }

    .report-table-filter select {
        width: 100%;

        min-width: 0;
    }

    .reports-page .report-table-pdf-btn {
        flex: 0 0 auto;
    }


    /* TABLE */

    .reports-page table {
        min-width: 760px;
    }

    .reports-page table th,
    .reports-page table td {
        padding: 9px 10px;

        font-size: 12px;
    }


    /* PAGINATION */

    .reports-page .report-pagination nav > div:last-child {
        align-items: flex-start;

        flex-direction: column;

        gap: 10px;
    }

}


/* ==========================================================
   SMALL MOBILE
========================================================== */

@media (max-width: 450px) {

    .reports-page .report-header-tools {
        align-items: stretch;

        flex-direction: column;
    }

    .report-table-filter {
        width: 100%;
    }

    .reports-page .report-table-pdf-btn {
        width: 100%;
    }

}


/* ==========================================================
   PRINT
========================================================== */

@media print {

    body {
        background: #ffffff !important;
    }

    .reports-page {
        width: 100% !important;

        padding: 0 !important;
    }

    .report-actions,
    .report-table-pdf-btn,
    .report-filter-card,
    .report-pagination,
    .report-table-filter {
        display: none !important;
    }

    .page-header {
        margin-bottom: 20px !important;
    }

    .report-card {
        margin-bottom: 20px !important;

        break-inside: avoid;
    }

    .report-card .card-body {
        padding: 10px !important;
    }

    .table-responsive {
        overflow: visible !important;
    }

    .reports-page table {
        min-width: 0 !important;

        width: 100% !important;

        font-size: 11px !important;
    }

    .reports-page table th,
    .reports-page table td {
        padding: 6px !important;

        font-size: 10px !important;
    }

}

</style>


<div class="container-fluid reports-page">


    {{-- ======================================================
         PAGE HEADER
    ======================================================= --}}

    <div class="page-header report-page-header">

        <div>

            <h1>
                Reports
            </h1>

            <p>
                Overview of loans and payments.
            </p>

        </div>


        

    </div>


    {{-- ======================================================
         DATE FILTER
    ======================================================= --}}

    <div class="card report-filter-card">

        <div class="card-body">

            <form
                method="GET"
                action="{{ route('admin.reports') }}"
                class="report-filter-form"
            >

                <div class="report-filter-grid">


                    {{-- From Date --}}

                    <div class="report-filter-field">

                        <label for="from_date">
                            From Date
                        </label>

                        <input
                            type="date"
                            name="from_date"
                            id="from_date"
                            class="form-control"
                            value="{{ $fromDate }}"
                        >

                    </div>


                    {{-- To Date --}}

                    <div class="report-filter-field">

                        <label for="to_date">
                            To Date
                        </label>

                        <input
                            type="date"
                            name="to_date"
                            id="to_date"
                            class="form-control"
                            value="{{ $toDate }}"
                        >

                    </div>


                    {{-- Filter --}}

                    <div class="report-filter-action">

                        <button
                            type="submit"
                            class="btn btn-primary"
                        >
                            Filter
                        </button>

                    </div>


                    {{-- Reset --}}

                    <div class="report-filter-action">

                        <a
                            href="{{ route('admin.reports') }}"
                            class="btn btn-secondary"
                        >
                            Reset
                        </a>

                    </div>

                </div>

            </form>

        </div>

    </div>


    {{-- ======================================================
         SUMMARY
    ======================================================= --}}

    <div class="report-summary-grid">


        <div class="report-summary-item">

            <div class="card">

                <div class="card-body">

                    <h6>
                        Total Loans
                    </h6>

                    <h2>
                        {{ $totalLoans }}
                    </h2>

                </div>

            </div>

        </div>


        <div class="report-summary-item">

            <div class="card">

                <div class="card-body">

                    <h6>
                        Total Disbursed
                    </h6>

                    <h2>
                        {{ $currencySymbol }}{{ number_format(
                            $totalDisbursed,
                            $decimalPlaces
                        ) }}
                    </h2>

                </div>

            </div>

        </div>


        <div class="report-summary-item">

            <div class="card">

                <div class="card-body">

                    <h6>
                        Total Collected
                    </h6>

                    <h2>
                        {{ $currencySymbol }}{{ number_format(
                            $totalCollected,
                            $decimalPlaces
                        ) }}
                    </h2>

                </div>

            </div>

        </div>


        <div class="report-summary-item">

            <div class="card">

                <div class="card-body">

                    <h6>
                        Total Outstanding
                    </h6>

                    <h2>
                        {{ $currencySymbol }}{{ number_format(
                            $totalOutstanding,
                            $decimalPlaces
                        ) }}
                    </h2>

                </div>

            </div>

        </div>

    </div>


    {{-- ======================================================
         COLLECTION REPORT
    ======================================================= --}}

    <div
        class="card report-card"
        id="collection-report"
    >

        <div class="card-body">


            <div class="report-card-header">


                <div class="report-card-header-left">

                    <h3>
                        Collection Report
                    </h3>

                    <p>
                        EMI and other payments received
                    </p>

                </div>


                <div class="report-header-tools">


                    {{-- Payment Type Filter --}}

                    <form
                        method="GET"
                        action="{{ route('admin.reports') }}"
                        class="report-table-filter ajax-report-filter"
                        data-target="collection-report"
                    >


                        {{-- Preserve From Date --}}

                        @if($fromDate)

                            <input
                                type="hidden"
                                name="from_date"
                                value="{{ $fromDate }}"
                            >

                        @endif


                        {{-- Preserve To Date --}}

                        @if($toDate)

                            <input
                                type="hidden"
                                name="to_date"
                                value="{{ $toDate }}"
                            >

                        @endif


                        {{-- Preserve Loan Status --}}

                        @if($loanStatus)

                            <input
                                type="hidden"
                                name="loan_status"
                                value="{{ $loanStatus }}"
                            >

                        @endif


                        <label for="payment_type">
                            Type
                        </label>


                        <select
                            name="payment_type"
                            id="payment_type"
                        >

                            <option
                                value=""
                                {{ empty($paymentType) ? 'selected' : '' }}
                            >
                                All Types
                            </option>


                            <option
                                value="emi"
                                {{ $paymentType === 'emi' ? 'selected' : '' }}
                            >
                                EMI
                            </option>


                            <option
                                value="processing_fee"
                                {{ $paymentType === 'processing_fee' ? 'selected' : '' }}
                            >
                                Processing Fee
                            </option>


                            <option
                                value="overdue_fine"
                                {{ $paymentType === 'overdue_fine' ? 'selected' : '' }}
                            >
                                Overdue Fine
                            </option>


                            <option
                                value="card_unlock"
                                {{ $paymentType === 'card_unlock' ? 'selected' : '' }}
                            >
                                Card Unlock
                            </option>


                            <option
                                value="general"
                                {{ $paymentType === 'general' ? 'selected' : '' }}
                            >
                                General
                            </option>

                        </select>

                    </form>


                    <strong>
                        {{ $payments->total() }}
                        Payments
                    </strong>


                    <a
                        href="{{ route(
                            'admin.reports.collection-pdf',
                            request()->query()
                        ) }}"
                        class="btn btn-danger btn-sm report-table-pdf-btn"
                        target="_blank"
                    >
                        Export PDF
                    </a>

                </div>

            </div>


            <div class="table-responsive">

                <table
                    class="table table-bordered table-hover collection-table"
                >

                    <thead>

                        <tr>

                            <th>
                                Date
                            </th>

                            <th>
                                Client
                            </th>

                            <th>
                                Loan
                            </th>

                            <th>
                                Type
                            </th>

                            <th>
                                Method
                            </th>

                            <th class="text-end">
                                Amount
                            </th>

                            <th>
                                Reference
                            </th>

                        </tr>

                    </thead>


                    <tbody>

                        @forelse($payments as $payment)

                            <tr>

                                <td>
                                    {{ $payment->paid_at?->format('d-m-Y') ?? '-' }}
                                </td>


                                <td>
                                    {{ $payment->user?->name ?? '-' }}
                                </td>


                                <td>
                                    {{ $payment->loan?->loan_number ?? '-' }}
                                </td>


                                <td>

                                    <span class="payment-type-text">

                                        {{ ucfirst(
                                            str_replace(
                                                '_',
                                                ' ',
                                                $payment->payment_type ?? 'general'
                                            )
                                        ) }}

                                    </span>

                                </td>


                                <td>

                                    {{ ucfirst(
                                        str_replace(
                                            '_',
                                            ' ',
                                            $payment->payment_method ?? '-'
                                        )
                                    ) }}

                                </td>


                                <td class="report-amount">

                                    {{ $currencySymbol }}{{ number_format(
                                        (float) $payment->amount,
                                        $decimalPlaces
                                    ) }}

                                </td>


                                <td>
                                    {{ $payment->reference_number ?? '-' }}
                                </td>

                            </tr>

                        @empty

                            <tr>

                                <td
                                    colspan="7"
                                    class="text-center py-4"
                                >
                                    No payments found for the selected
                                    filters.
                                </td>

                            </tr>

                        @endforelse

                    </tbody>

                </table>

            </div>


            {{-- Collection Pagination --}}

            <div class="report-pagination">

                {{ $payments->links() }}

            </div>


        </div>

    </div>


    {{-- ======================================================
         LOAN REPORT
    ======================================================= --}}

    <div
        class="card report-card"
        id="loan-report"
    >

        <div class="card-body">


            <div class="report-card-header">


                <div class="report-card-header-left">

                    <h3>
                        Loan Report
                    </h3>

                    <p>
                        Overview of all loans
                    </p>

                </div>


                <div class="report-header-tools">


                    {{-- Loan Status Filter --}}

                    <form
                        method="GET"
                        action="{{ route('admin.reports') }}"
                        class="report-table-filter ajax-report-filter"
                        data-target="loan-report"
                    >


                        {{-- Preserve From Date --}}

                        @if($fromDate)

                            <input
                                type="hidden"
                                name="from_date"
                                value="{{ $fromDate }}"
                            >

                        @endif


                        {{-- Preserve To Date --}}

                        @if($toDate)

                            <input
                                type="hidden"
                                name="to_date"
                                value="{{ $toDate }}"
                            >

                        @endif


                        {{-- Preserve Payment Type --}}

                        @if($paymentType)

                            <input
                                type="hidden"
                                name="payment_type"
                                value="{{ $paymentType }}"
                            >

                        @endif


                        <label for="loan_status">
                            Status
                        </label>


                        <select
                            name="loan_status"
                            id="loan_status"
                        >

                            <option
                                value=""
                                {{ empty($loanStatus) ? 'selected' : '' }}
                            >
                                All Status
                            </option>


                            <option
                                value="active"
                                {{ $loanStatus === 'active' ? 'selected' : '' }}
                            >
                                Active
                            </option>


                            <option
                                value="closed"
                                {{ $loanStatus === 'closed' ? 'selected' : '' }}
                            >
                                Closed
                            </option>

                        </select>

                    </form>


                    <strong>
                        {{ $loans->total() }}
                        Loans
                    </strong>


                    <a
                        href="{{ route(
                            'admin.reports.loan-pdf',
                            request()->query()
                        ) }}"
                        class="btn btn-danger btn-sm report-table-pdf-btn"
                        target="_blank"
                    >
                        Export PDF
                    </a>

                </div>

            </div>


            <div class="table-responsive">

                <table
                    class="table table-bordered table-hover loan-table"
                >

                    <thead>

                        <tr>

                            <th>
                                Loan Number
                            </th>

                            <th>
                                Client
                            </th>

                            <th>
                                Loan Amount
                            </th>

                            <th>
                                Disbursed Date
                            </th>

                            <th>
                                Outstanding
                            </th>

                            <th>
                                Status
                            </th>

                        </tr>

                    </thead>


                    <tbody>

                        @forelse($loans as $loan)

                            <tr>

                                <td>
                                    {{ $loan->loan_number ?? '-' }}
                                </td>


                                <td>
                                    {{ $loan->user?->name ?? '-' }}
                                </td>


                                <td class="report-amount">

                                    {{ $currencySymbol }}{{ number_format(
                                        (float) $loan->loan_amount,
                                        $decimalPlaces
                                    ) }}

                                </td>


                                <td>
                                    {{ $loan->disbursed_at?->format('d-m-Y') ?? '-' }}
                                </td>


                                <td class="report-amount">

                                    {{ $currencySymbol }}{{ number_format(
                                        (float) $loan->outstanding_amount,
                                        $decimalPlaces
                                    ) }}

                                </td>


                                <td>

                                    <span class="loan-status-text">

                                        @php

                                            $displayLoanStatus =
                                                strtolower(
                                                    $loan->status ?? ''
                                                );

                                        @endphp


                                        @if(
                                            $displayLoanStatus === 'completed' ||
                                            $displayLoanStatus === 'closed'
                                        )

                                            Closed

                                        @elseif(
                                            $displayLoanStatus === 'active'
                                        )

                                            Active

                                        @else

                                            {{ ucfirst(
                                                str_replace(
                                                    '_',
                                                    ' ',
                                                    $loan->status ?? '-'
                                                )
                                            ) }}

                                        @endif

                                    </span>

                                </td>

                            </tr>

                        @empty

                            <tr>

                                <td
                                    colspan="6"
                                    class="text-center py-4"
                                >
                                    No loans found for the selected
                                    filters.
                                </td>

                            </tr>

                        @endforelse

                    </tbody>

                </table>

            </div>


            {{-- Loan Pagination --}}

            <div class="report-pagination">

                {{ $loans->links() }}

            </div>


        </div>

    </div>


</div>


{{-- ==========================================================
     AJAX REPORT SYSTEM
========================================================== --}}

<script>

(function () {

    'use strict';


    let loading = false;


    /*
    |--------------------------------------------------------------------------
    | Get Scroll Position
    |--------------------------------------------------------------------------
    */

    function getScrollPosition() {

        return window.pageYOffset ||
               document.documentElement.scrollTop ||
               document.body.scrollTop ||
               0;

    }


    /*
    |--------------------------------------------------------------------------
    | Restore Scroll
    |--------------------------------------------------------------------------
    */

    function restoreScroll(position) {

        window.scrollTo(
            0,
            position
        );


        requestAnimationFrame(
            function () {

                window.scrollTo(
                    0,
                    position
                );

            }
        );


        setTimeout(
            function () {

                window.scrollTo(
                    0,
                    position
                );

            },
            50
        );


        setTimeout(
            function () {

                window.scrollTo(
                    0,
                    position
                );

            },
            150
        );

    }


    /*
    |--------------------------------------------------------------------------
    | Create URL
    |--------------------------------------------------------------------------
    */

    function createUrl(form) {

        const formData =
            new FormData(form);


        const params =
            new URLSearchParams();


        formData.forEach(
            function (value, key) {

                if (
                    value !== null &&
                    value !== ''
                ) {

                    params.append(
                        key,
                        value
                    );

                }

            }
        );


        const action =
            form.getAttribute('action') ||
            window.location.pathname;


        return action +
            (
                params.toString()
                    ? '?' + params.toString()
                    : ''
            );

    }


    /*
    |--------------------------------------------------------------------------
    | Fetch Report
    |--------------------------------------------------------------------------
    */

    async function fetchReport(url) {

        const response =
            await fetch(
                url,
                {
                    method: 'GET',

                    credentials: 'same-origin',

                    headers: {

                        'X-Requested-With':
                            'XMLHttpRequest',

                        'Accept':
                            'application/json'

                    }
                }
            );


        if (!response.ok) {

            throw new Error(
                'HTTP ' + response.status
            );

        }


        const contentType =
            response.headers.get('content-type') || '';

        if (contentType.includes('application/json')) {

            return {
                type: 'json',
                data: await response.json()
            };

        }

        return {
            type: 'html',
            html: await response.text()
        };

    }


    /*
    |--------------------------------------------------------------------------
    | Parse HTML
    |--------------------------------------------------------------------------
    */

    function parseResponseHtml(html) {

        const parser =
            new DOMParser();


        return parser.parseFromString(
            html,
            'text/html'
        );

    }


    /*
    |--------------------------------------------------------------------------
    | Replace Card
    |--------------------------------------------------------------------------
    */

    function replaceCard(
        targetId,
        newDocument
    ) {

        const current =
            document.getElementById(
                targetId
            );


        const updated =
            newDocument.getElementById(
                targetId
            );


        if (
            !current ||
            !updated
        ) {

            console.error(
                'Report card not found:',
                targetId
            );

            return false;

        }


        current.innerHTML =
            updated.innerHTML;


        return true;

    }


    /*
    |--------------------------------------------------------------------------
    | Replace Summary
    |--------------------------------------------------------------------------
    */

    function replaceSummary(
        newDocument
    ) {

        const current =
            document.querySelector(
                '.report-summary-grid'
            );


        const updated =
            newDocument.querySelector(
                '.report-summary-grid'
            );


        if (
            current &&
            updated
        ) {

            current.innerHTML =
                updated.innerHTML;

        }

    }


    /*
    |--------------------------------------------------------------------------
    | Load Single Report
    |--------------------------------------------------------------------------
    */

    async function loadSingleReport(
        url,
        targetId
    ) {

        if (loading) {
            return;
        }


        loading = true;


        /*
        |--------------------------------------------------------------------------
        | IMPORTANT:
        | Save scroll before request.
        |--------------------------------------------------------------------------
        */

        const savedScroll =
            getScrollPosition();


        const target =
            document.getElementById(
                targetId
            );


        if (!target) {

            loading = false;

            return;

        }


        target.classList.add(
            'report-loading'
        );


        try {

            const response =
                await fetchReport(
                    url
                );


            const html =
                response.type === 'json'
                    ? response.data?.html
                    : response.html;


            if (
                typeof html !== 'string' ||
                !html.trim()
            ) {

                throw new Error(
                    'Invalid AJAX response'
                );

            }


            const newDocument =
                parseResponseHtml(
                    html
                );


            replaceSummary(
                newDocument
            );


            replaceCard(
                targetId,
                newDocument
            );


            /*
            |--------------------------------------------------------------------------
            | Update URL without reloading the page
            |--------------------------------------------------------------------------
            */

            window.history.pushState(
                {
                    reportAjax: true
                },
                '',
                url
            );


            /*
            |--------------------------------------------------------------------------
            | Restore scroll AFTER DOM replacement
            |--------------------------------------------------------------------------
            */

            restoreScroll(
                savedScroll
            );


        } catch (error) {

            console.error(
                'Report filter error:',
                error
            );

        } finally {

            const updatedTarget =
                document.getElementById(
                    targetId
                );


            if (updatedTarget) {

                updatedTarget.classList.remove(
                    'report-loading'
                );

            }


            loading = false;

        }

    }


    /*
    |--------------------------------------------------------------------------
    | Load Complete Report
    |--------------------------------------------------------------------------
    */

    async function loadCompleteReport(
        url
    ) {

        if (loading) {
            return;
        }


        loading = true;


        const savedScroll =
            getScrollPosition();


        document
            .querySelectorAll(
                '.report-card'
            )
            .forEach(
                function (card) {

                    card.classList.add(
                        'report-loading'
                    );

                }
            );


        try {

            const response =
                await fetchReport(
                    url
                );


            const html =
                response.type === 'json'
                    ? response.data?.html
                    : response.html;


            if (
                typeof html !== 'string' ||
                !html.trim()
            ) {

                throw new Error(
                    'Invalid AJAX response'
                );

            }


            const newDocument =
                parseResponseHtml(
                    html
                );


            /*
            |--------------------------------------------------------------------------
            | Summary
            |--------------------------------------------------------------------------
            */

            replaceSummary(
                newDocument
            );


            /*
            |--------------------------------------------------------------------------
            | Collection
            |--------------------------------------------------------------------------
            */

            replaceCard(
                'collection-report',
                newDocument
            );


            /*
            |--------------------------------------------------------------------------
            | Loan
            |--------------------------------------------------------------------------
            */

            replaceCard(
                'loan-report',
                newDocument
            );


            /*
            |--------------------------------------------------------------------------
            | Update URL
            |--------------------------------------------------------------------------
            */

            window.history.pushState(
                {
                    reportAjax: true
                },
                '',
                url
            );


            /*
            |--------------------------------------------------------------------------
            | Restore scroll
            |--------------------------------------------------------------------------
            */

            restoreScroll(
                savedScroll
            );


        } catch (error) {

            console.error(
                'Report date filter error:',
                error
            );

        } finally {

            document
                .querySelectorAll(
                    '.report-card'
                )
                .forEach(
                    function (card) {

                        card.classList.remove(
                            'report-loading'
                        );

                    }
                );


            loading = false;

        }

    }


    /*
    |--------------------------------------------------------------------------
    | Collection / Loan Filter
    |--------------------------------------------------------------------------
    */

    document.addEventListener(
        'change',
        function (event) {

            const select =
                event.target.closest(
                    '.ajax-report-filter select'
                );


            if (!select) {
                return;
            }


            const form =
                select.closest(
                    'form'
                );


            if (!form) {
                return;
            }


            event.preventDefault();


            const targetId =
                form.dataset.target;


            const url =
                createUrl(
                    form
                );


            if (!targetId) {

                console.error(
                    'Missing data-target'
                );

                return;

            }


            loadSingleReport(
                url,
                targetId
            );

        }
    );


    /*
    |--------------------------------------------------------------------------
    | Date Filter
    |--------------------------------------------------------------------------
    */

    document.addEventListener(
        'submit',
        function (event) {

            const form =
                event.target.closest(
                    '.report-filter-form'
                );


            if (!form) {
                return;
            }


            event.preventDefault();


            const url =
                createUrl(
                    form
                );


            loadCompleteReport(
                url
            );

        }
    );


    /*
    |--------------------------------------------------------------------------
    | Reset Filter
    |--------------------------------------------------------------------------
    */

    document.addEventListener(
        'click',
        function (event) {

            const link =
                event.target.closest(
                    '.report-filter-card a[href]'
                );


            if (!link) {
                return;
            }


            event.preventDefault();


            loadCompleteReport(
                link.href
            );

        }
    );


    /*
    |--------------------------------------------------------------------------
    | Pagination
    |--------------------------------------------------------------------------
    */

    document.addEventListener(
        'click',
        function (event) {

            const link =
                event.target.closest(
                    '.report-pagination a'
                );


            if (!link) {
                return;
            }


            event.preventDefault();


            const card =
                link.closest(
                    '.report-card'
                );


            if (!card) {
                return;
            }


            const targetId =
                card.id;


            if (!targetId) {
                return;
            }


            const url =
                link.href;


            if (!url) {
                return;
            }


            loadSingleReport(
                url,
                targetId
            );

        }
    );


    /*
    |--------------------------------------------------------------------------
    | Browser Back / Forward
    |--------------------------------------------------------------------------
    */

    window.addEventListener(
        'popstate',
        function () {

            loadCompleteReport(
                window.location.href
            );

        }
    );


})();

</script>

@endsection