@extends('admin.layouts.app')

@section('title', 'EMI CREDITS | Create Loan')
@section('page-title', 'Create Loan')

@section('page-description')
    Create and manage a new client loan
@endsection

@push('styles')
<link rel="stylesheet" href="{{ asset('admin/css/loan-create.css') }}">
@endpush

@php
    $currencySettings = \App\Models\SystemSetting::query()->first();

    $currencySymbol = $currencySettings?->currency_symbol ?? '₹';
    $currencyDecimals = (int) ($currencySettings?->currency_decimal_places ?? 2);
    $currencyRound = (bool) ($currencySettings?->currency_round_display ?? false);

    /*
    |--------------------------------------------------------------------------
    | Interest Settings
    |--------------------------------------------------------------------------
    |
    | Interest ON/OFF is controlled from Loan Settings.
    | Each Loan Type has its own interest_rate.
    |
    */

    $interestEnabled = (bool) ($settings->interest_enabled ?? false);
@endphp

@section('content')

<div class="loan-create-page">

    <div class="loan-create-header">

        <div>

            <h1 class="h3 mb-1">
                Create Loan
            </h1>

            <p class="text-muted mb-0">
                Create a new loan for an existing client.
            </p>

        </div>

        <a
            href="{{ route('admin.loans') }}"
            class="loan-back-btn"
        >
            Back to Loans
        </a>

    </div>


    {{-- =====================================================
         ERROR
    ====================================================== --}}

    @if(session('error'))

        <div class="alert alert-danger">
            {{ session('error') }}
        </div>

    @endif


    {{-- =====================================================
         VALIDATION ERRORS
    ====================================================== --}}

    @if($errors->any())

        <div class="alert alert-danger">

            <strong>
                Please correct the following:
            </strong>

            <ul class="mb-0 mt-2">

                @foreach($errors->all() as $error)

                    <li>
                        {{ $error }}
                    </li>

                @endforeach

            </ul>

        </div>

    @endif


    <form
        method="POST"
        action="{{ route('admin.loans.create.store') }}"
        id="adminLoanForm"
    >

        @csrf


        {{-- =================================================
             LOAN INFORMATION
        ================================================== --}}

        <div class="loan-section">

            <div class="loan-section-header">

                <strong>
                    Loan Information
                </strong>

            </div>


            <div class="loan-section-body">

                <div class="loan-grid">


                    {{-- CLIENT --}}

                    <div class="loan-field">

                        <label
                            for="user_id"
                            class="loan-label"
                        >
                            Client
                            <span class="text-danger">*</span>
                        </label>

                        <select
                            name="user_id"
                            id="user_id"
                            class="loan-control"
                            required
                        >

                            <option value="">
                                Select client
                            </option>

                            @foreach($clients as $client)

                                <option
                                    value="{{ $client->id }}"
                                    @selected(
                                        old('user_id') == $client->id
                                    )
                                >

                                    {{ $client->name }}

                                    @if($client->mobile)
                                        — {{ $client->mobile }}
                                    @endif

                                </option>

                            @endforeach

                        </select>

                    </div>


                    {{-- EMI CARD --}}

                    <div class="loan-field">

                        <label
                            for="emi_card_id"
                            class="loan-label"
                        >
                            EMI Card
                            <span class="text-danger">*</span>
                        </label>

                        <select
                            name="emi_card_id"
                            id="emi_card_id"
                            class="loan-control"
                            required
                        >

                            <option value="">
                                Select client first
                            </option>

                            @foreach($emiCards as $card)

                                <option
                                    value="{{ $card->id }}"
                                    data-user-id="{{ $card->user_id }}"
                                    data-limit="{{ (float)($card->available_limit ?? 0) }}"
                                    data-card-number="{{ $card->card_number }}"
                                    @selected(
                                        old('emi_card_id') == $card->id
                                    )
                                >

                                    {{ $card->card_number }}

                                    —
                                    Available:
                                    {{ money((float)($card->available_limit ?? 0)) }}

                                </option>

                            @endforeach

                        </select>


                        <small
                            class="loan-help"
                            id="cardInfo"
                        >
                            Select a client to view active EMI cards.
                        </small>

                    </div>


                    {{-- LOAN TYPE --}}

                    <div class="loan-field">

                        <label
                            for="loan_type_id"
                            class="loan-label"
                        >
                            Loan Type
                            <span class="text-danger">*</span>
                        </label>

                        <select
                            name="loan_type_id"
                            id="loan_type_id"
                            class="loan-control"
                            required
                        >

                            <option value="">
                                Select loan type
                            </option>

                            @foreach($loanTypes as $type)

                                <option
                                    value="{{ $type->id }}"
                                    data-code="{{ strtolower($type->code ?? $type->name) }}"
                                    data-interest-rate="{{ (float)($type->interest_rate ?? 0) }}"
                                    @selected(
                                        old('loan_type_id') == $type->id
                                    )
                                >

                                    {{ $type->name }}

                                </option>

                            @endforeach

                        </select>


                        <div
                            class="interest-status"
                            id="interestStatus"
                        >

                            @if($interestEnabled)

                                Interest:
                                <strong id="selectedInterestRate">
                                    Select loan type
                                </strong>

                            @else

                                Interest:
                                <strong>
                                    0%
                                </strong>

                                <span>
                                    (Interest is disabled in Loan Settings)
                                </span>

                            @endif

                        </div>

                    </div>

                </div>


                {{-- CARD SUMMARY --}}

                <div class="loan-grid">


                    <div class="loan-field">

                        <div class="border rounded p-3 bg-light">

                            <small class="text-muted d-block">
                                Selected Card
                            </small>

                            <strong id="selectedCardNumber">
                                —
                            </strong>

                        </div>

                    </div>


                    <div class="loan-field">

                        <div class="border rounded p-3 bg-light">

                            <small class="text-muted d-block">
                                Available Limit
                            </small>

                            <strong id="selectedCardLimit">
                                —
                            </strong>

                        </div>

                    </div>


                    <div class="loan-field">

                        <div class="border rounded p-3 bg-light">

                            <small class="text-muted d-block">
                                Minimum Loan
                            </small>

                            <strong>
                                {{ money((float)($settings->minimum_loan_amount ?? 0)) }}
                            </strong>

                        </div>

                    </div>

                </div>

            </div>

        </div>


        {{-- =================================================
             LOAN AMOUNT & TENURE
        ================================================== --}}

        <div class="loan-section">

            <div class="loan-section-header">

                <strong>
                    Loan Amount & Tenure
                </strong>

            </div>


            <div class="loan-section-body">

                <div class="loan-grid">


                    {{-- LOAN AMOUNT --}}

                    <div class="loan-field">

                        <label
                            for="loan_amount"
                            class="loan-label"
                        >

                            Loan Amount

                            <span class="text-danger">
                                *
                            </span>

                        </label>


                        <div class="loan-amount-wrap">

                            <span
                                class="loan-amount-prefix"
                                id="loanCurrencyPrefix"
                            >
                                {{ $currencySymbol }}
                            </span>


                            <input
                                type="number"
                                step="0.01"
                                min="0.01"
                                name="loan_amount"
                                id="loan_amount"
                                class="loan-control loan-amount-input"
                                value="{{ old('loan_amount') }}"
                                required
                            >

                        </div>


                        <small class="loan-help">

                            Maximum is the lower of the configured maximum
                            and the selected card's available limit.

                        </small>

                    </div>


                    {{-- TENURE --}}

                    <div class="loan-field">

                        <label
                            for="tenure_months"
                            class="loan-label"
                        >

                            Tenure

                            <span class="text-danger">
                                *
                            </span>

                        </label>


                        <select
                            name="tenure_months"
                            id="tenure_months"
                            class="loan-control"
                            required
                        >

                            <option value="">
                                Select tenure
                            </option>

                            @foreach(($settings->allowed_tenures ?? []) as $tenure)

                                <option
                                    value="{{ (int)$tenure }}"
                                    @selected(
                                        old('tenure_months') == $tenure
                                    )
                                >

                                    {{ (int)$tenure }}
                                    Months

                                </option>

                            @endforeach

                        </select>

                    </div>


                    {{-- INTEREST ENABLE STATUS --}}

                    <div class="loan-field">

                        <label class="loan-label">
                            Interest Status
                        </label>


                        <div
                            class="border rounded p-3 bg-light"
                            style="height:44px;box-sizing:border-box;display:flex;align-items:center"
                        >

                            @if($interestEnabled)

                                <strong
                                    id="interestStatusBox"
                                    style="color:#198754"
                                >
                                    Enabled
                                </strong>

                            @else

                                <strong
                                    id="interestStatusBox"
                                    style="color:#64748b"
                                >
                                    Disabled — 0%
                                </strong>

                            @endif

                        </div>

                    </div>

                </div>

            </div>

        </div>


        {{-- =================================================
             LOAN TYPE DETAILS
        ================================================== --}}

        <div class="loan-section">

            <div class="loan-section-header">

                <strong>
                    Loan Type Details
                </strong>

            </div>


            <div class="loan-section-body">

                <div
                    id="detailsHint"
                    class="loan-details-hint"
                >

                    Select a loan type to enter type-specific details.

                </div>


                {{-- DIGITAL PRODUCT --}}

                <div
                    id="details-digital_product"
                    class="loan-details-group d-none"
                >

                    <div class="loan-grid">


                        <div class="loan-field">

                            <label class="loan-label">
                                Product / Device
                            </label>

                            <input
                                type="text"
                                name="details[product_name]"
                                class="loan-control"
                                value="{{ old('details.product_name') }}"
                                placeholder="e.g. Mobile Phone"
                            >

                        </div>


                        <div class="loan-field">

                            <label class="loan-label">
                                Brand
                            </label>

                            <input
                                type="text"
                                name="details[brand]"
                                class="loan-control"
                                value="{{ old('details.brand') }}"
                            >

                        </div>


                        <div class="loan-field">

                            <label class="loan-label">
                                Model
                            </label>

                            <input
                                type="text"
                                name="details[model]"
                                class="loan-control"
                                value="{{ old('details.model') }}"
                            >

                        </div>


                        <div class="loan-field">

                            <label class="loan-label">
                                IMEI / Serial Number
                            </label>

                            <input
                                type="text"
                                name="details[imei_or_serial]"
                                class="loan-control"
                                value="{{ old('details.imei_or_serial') }}"
                            >

                        </div>


                        <div class="loan-field">

                            <label class="loan-label">
                                Seller / Store
                            </label>

                            <input
                                type="text"
                                name="details[seller]"
                                class="loan-control"
                                value="{{ old('details.seller') }}"
                            >

                        </div>

                    </div>

                </div>


                {{-- GOLD --}}

                <div
                    id="details-gold"
                    class="loan-details-group d-none"
                >

                    <div class="loan-grid">


                        <div class="loan-field">

                            <label class="loan-label">
                                Gold Item
                            </label>

                            <input
                                type="text"
                                name="details[gold_item]"
                                class="loan-control"
                                value="{{ old('details.gold_item') }}"
                                placeholder="Ring / Chain / etc."
                            >

                        </div>


                        <div class="loan-field">

                            <label class="loan-label">
                                Gross Weight (g)
                            </label>

                            <input
                                type="text"
                                name="details[gross_weight]"
                                class="loan-control"
                                value="{{ old('details.gross_weight') }}"
                            >

                        </div>


                        <div class="loan-field">

                            <label class="loan-label">
                                Purity
                            </label>

                            <input
                                type="text"
                                name="details[purity]"
                                class="loan-control"
                                value="{{ old('details.purity') }}"
                                placeholder="22K / 916"
                            >

                        </div>


                        <div class="loan-field">

                            <label class="loan-label">
                                Appraised Value
                            </label>

                            <input
                                type="number"
                                step="0.01"
                                name="details[appraised_value]"
                                class="loan-control"
                                value="{{ old('details.appraised_value') }}"
                            >

                        </div>


                        <div class="loan-field">

                            <label class="loan-label">
                                Description
                            </label>

                            <input
                                type="text"
                                name="details[description]"
                                class="loan-control"
                                value="{{ old('details.description') }}"
                            >

                        </div>

                    </div>

                </div>


                {{-- PERSONAL --}}

                <div
                    id="details-personal"
                    class="loan-details-group d-none"
                >

                    <div class="loan-grid">


                        <div class="loan-field">

                            <label class="loan-label">
                                Purpose
                            </label>

                            <input
                                type="text"
                                name="details[purpose]"
                                class="loan-control"
                                value="{{ old('details.purpose') }}"
                            >

                        </div>


                        <div class="loan-field">

                            <label class="loan-label">
                                Employment / Occupation
                            </label>

                            <input
                                type="text"
                                name="details[occupation]"
                                class="loan-control"
                                value="{{ old('details.occupation') }}"
                            >

                        </div>


                        <div class="loan-field">

                            <label class="loan-label">
                                Employer / Business
                            </label>

                            <input
                                type="text"
                                name="details[employer]"
                                class="loan-control"
                                value="{{ old('details.employer') }}"
                            >

                        </div>


                        <div class="loan-field">

                            <label class="loan-label">
                                Monthly Income
                            </label>

                            <input
                                type="number"
                                step="0.01"
                                name="details[monthly_income]"
                                class="loan-control"
                                value="{{ old('details.monthly_income') }}"
                            >

                        </div>

                    </div>

                </div>


                {{-- VEHICLE --}}

                <div
                    id="details-vehicle"
                    class="loan-details-group d-none"
                >

                    <div class="loan-grid">


                        <div class="loan-field">

                            <label class="loan-label">
                                Vehicle Type
                            </label>

                            <input
                                type="text"
                                name="details[vehicle_type]"
                                class="loan-control"
                                value="{{ old('details.vehicle_type') }}"
                            >

                        </div>


                        <div class="loan-field">

                            <label class="loan-label">
                                Make
                            </label>

                            <input
                                type="text"
                                name="details[make]"
                                class="loan-control"
                                value="{{ old('details.make') }}"
                            >

                        </div>


                        <div class="loan-field">

                            <label class="loan-label">
                                Model
                            </label>

                            <input
                                type="text"
                                name="details[model]"
                                class="loan-control"
                                value="{{ old('details.model') }}"
                            >

                        </div>


                        <div class="loan-field">

                            <label class="loan-label">
                                Registration Number
                            </label>

                            <input
                                type="text"
                                name="details[registration_number]"
                                class="loan-control"
                                value="{{ old('details.registration_number') }}"
                            >

                        </div>


                        <div class="loan-field">

                            <label class="loan-label">
                                Chassis Number
                            </label>

                            <input
                                type="text"
                                name="details[chassis_number]"
                                class="loan-control"
                                value="{{ old('details.chassis_number') }}"
                            >

                        </div>


                        <div class="loan-field">

                            <label class="loan-label">
                                Engine Number
                            </label>

                            <input
                                type="text"
                                name="details[engine_number]"
                                class="loan-control"
                                value="{{ old('details.engine_number') }}"
                            >

                        </div>

                    </div>

                </div>

                {{-- BUSINESS --}}

<div
    id="details-business"
    class="loan-details-group d-none"
>

    <div class="loan-grid">

        <div class="loan-field">
            <label class="loan-label">
                Business Name
            </label>

            <input
                type="text"
                name="details[business_name]"
                class="loan-control"
                value="{{ old('details.business_name') }}"
                placeholder="Enter business name"
            >
        </div>


        <div class="loan-field">
            <label class="loan-label">
                Business Type
            </label>

            <input
                type="text"
                name="details[business_type]"
                class="loan-control"
                value="{{ old('details.business_type') }}"
                placeholder="e.g. Retail, Wholesale"
            >
        </div>


        <div class="loan-field">
            <label class="loan-label">
                Business Address
            </label>

            <input
                type="text"
                name="details[business_address]"
                class="loan-control"
                value="{{ old('details.business_address') }}"
            >
        </div>


        <div class="loan-field">
            <label class="loan-label">
                Monthly Turnover
            </label>

            <input
                type="number"
                step="0.01"
                min="0"
                name="details[monthly_turnover]"
                class="loan-control"
                value="{{ old('details.monthly_turnover') }}"
            >
        </div>


        <div class="loan-field">
            <label class="loan-label">
                Business Experience
            </label>

            <input
                type="text"
                name="details[business_experience]"
                class="loan-control"
                value="{{ old('details.business_experience') }}"
                placeholder="e.g. 5 Years"
            >
        </div>


        <div class="loan-field">
            <label class="loan-label">
                Loan Purpose
            </label>

            <input
                type="text"
                name="details[loan_purpose]"
                class="loan-control"
                value="{{ old('details.loan_purpose') }}"
                placeholder="Purpose of business loan"
            >
        </div>

    </div>

</div>


{{-- EMERGENCY --}}

<div
    id="details-emergency"
    class="loan-details-group d-none"
>

    <div class="loan-grid">

        <div class="loan-field">
            <label class="loan-label">
                Emergency Type
            </label>

            <input
                type="text"
                name="details[emergency_type]"
                class="loan-control"
                value="{{ old('details.emergency_type') }}"
                placeholder="e.g. Family / Accident / Urgent Expense"
            >
        </div>


        <div class="loan-field">
            <label class="loan-label">
                Emergency Description
            </label>

            <input
                type="text"
                name="details[emergency_description]"
                class="loan-control"
                value="{{ old('details.emergency_description') }}"
            >
        </div>


        <div class="loan-field">
            <label class="loan-label">
                Required Amount
            </label>

            <input
                type="number"
                step="0.01"
                min="0"
                name="details[required_amount]"
                class="loan-control"
                value="{{ old('details.required_amount') }}"
            >
        </div>


        <div class="loan-field">
            <label class="loan-label">
                Urgency Level
            </label>

            <select
                name="details[urgency_level]"
                class="loan-control"
            >
                <option value="">Select urgency</option>

                <option
                    value="High"
                    @selected(old('details.urgency_level') === 'High')
                >
                    High
                </option>

                <option
                    value="Medium"
                    @selected(old('details.urgency_level') === 'Medium')
                >
                    Medium
                </option>

                <option
                    value="Low"
                    @selected(old('details.urgency_level') === 'Low')
                >
                    Low
                </option>
            </select>
        </div>

    </div>

</div>


{{-- MEDICAL --}}

<div
    id="details-medical"
    class="loan-details-group d-none"
>

    <div class="loan-grid">

        <div class="loan-field">
            <label class="loan-label">
                Patient Name
            </label>

            <input
                type="text"
                name="details[patient_name]"
                class="loan-control"
                value="{{ old('details.patient_name') }}"
            >
        </div>


        <div class="loan-field">
            <label class="loan-label">
                Treatment Type
            </label>

            <input
                type="text"
                name="details[treatment_type]"
                class="loan-control"
                value="{{ old('details.treatment_type') }}"
                placeholder="e.g. Surgery / Treatment"
            >
        </div>


        <div class="loan-field">
            <label class="loan-label">
                Hospital Name
            </label>

            <input
                type="text"
                name="details[hospital_name]"
                class="loan-control"
                value="{{ old('details.hospital_name') }}"
            >
        </div>


        <div class="loan-field">
            <label class="loan-label">
                Estimated Medical Expense
            </label>

            <input
                type="number"
                step="0.01"
                min="0"
                name="details[medical_expense]"
                class="loan-control"
                value="{{ old('details.medical_expense') }}"
            >
        </div>


        <div class="loan-field">
            <label class="loan-label">
                Treatment Date
            </label>

            <input
                type="date"
                name="details[treatment_date]"
                class="loan-control"
                value="{{ old('details.treatment_date') }}"
            >
        </div>

    </div>

</div>


{{-- HOME --}}

<div
    id="details-home"
    class="loan-details-group d-none"
>

    <div class="loan-grid">

        <div class="loan-field">
            <label class="loan-label">
                Property Type
            </label>

            <select
                name="details[property_type]"
                class="loan-control"
            >
                <option value="">Select property type</option>

                <option
                    value="House"
                    @selected(old('details.property_type') === 'House')
                >
                    House
                </option>

                <option
                    value="Apartment"
                    @selected(old('details.property_type') === 'Apartment')
                >
                    Apartment
                </option>

                <option
                    value="Villa"
                    @selected(old('details.property_type') === 'Villa')
                >
                    Villa
                </option>

                <option
                    value="Plot"
                    @selected(old('details.property_type') === 'Plot')
                >
                    Plot
                </option>
            </select>
        </div>


        <div class="loan-field">
            <label class="loan-label">
                Property Location
            </label>

            <input
                type="text"
                name="details[property_location]"
                class="loan-control"
                value="{{ old('details.property_location') }}"
            >
        </div>


        <div class="loan-field">
            <label class="loan-label">
                Property Value
            </label>

            <input
                type="number"
                step="0.01"
                min="0"
                name="details[property_value]"
                class="loan-control"
                value="{{ old('details.property_value') }}"
            >
        </div>


        <div class="loan-field">
            <label class="loan-label">
                Loan Purpose
            </label>

            <input
                type="text"
                name="details[home_loan_purpose]"
                class="loan-control"
                value="{{ old('details.home_loan_purpose') }}"
                placeholder="Purchase / Construction / Renovation"
            >
        </div>

    </div>

</div>


                {{-- OTHER --}}

                <div
                    id="details-other"
                    class="loan-details-group d-none"
                >

                    <div class="loan-grid">

                        <div class="loan-field">

                            <label class="loan-label">
                                Details / Notes
                            </label>

                            <textarea
                                name="details[description]"
                                class="loan-control"
                                rows="3"
                            >{{ old('details.description') }}</textarea>

                        </div>

                    </div>

                </div>

            </div>

        </div>


        {{-- =================================================
             CALCULATION PREVIEW
        ================================================== --}}

        <div class="loan-section">

            <div class="loan-section-header">

                <strong>
                    Calculation Preview
                </strong>

            </div>


            <div class="loan-section-body">

                <div class="loan-preview-grid">


                    {{-- AMOUNT --}}

                    <div class="loan-preview-box">

                        <small>
                            Loan Amount
                        </small>

                        <strong id="previewAmount">
                            {{ $currencySymbol }}0.00
                        </strong>

                    </div>


                    {{-- INTEREST RATE --}}

                    <div class="loan-preview-box loan-preview-interest">

                        <small>
                            Interest Rate
                        </small>

                        <strong id="previewInterestRate">
                            {{ $interestEnabled ? '0%' : '0%' }}
                        </strong>

                    </div>


                    {{-- INTEREST AMOUNT --}}

                    <div class="loan-preview-box loan-preview-interest">

                        <small>
                            Interest Amount
                        </small>

                        <strong id="previewInterestAmount">
                            {{ $currencySymbol }}0.00
                        </strong>

                    </div>


                    {{-- PROCESSING FEE --}}

                    <div class="loan-preview-box">

                        <small>
                            Processing Fee
                        </small>

                        <strong id="previewFee">
                            {{ $currencySymbol }}0.00
                        </strong>

                    </div>


                    {{-- TOTAL --}}

                    <div class="loan-preview-box">

                        <small>
                            Total Payable
                        </small>

                        <strong id="previewTotal">
                            {{ $currencySymbol }}0.00
                        </strong>

                    </div>


                    {{-- EMI --}}

                    <div class="loan-preview-box">

                        <small>
                            Estimated EMI
                        </small>

                        <strong id="previewEmi">
                            {{ $currencySymbol }}0.00
                        </strong>

                    </div>

                </div>


                <div class="mt-3 text-muted small">

                    Final calculation and validation are performed by the server
                    using the existing loan calculation service.

                </div>

            </div>

        </div>


        {{-- =================================================
             ACTIONS
        ================================================== --}}

        <div class="loan-actions">

            <a
                href="{{ route('admin.loans') }}"
                class="loan-cancel-btn"
            >
                Cancel
            </a>

            <button
                type="submit"
                class="loan-submit-btn"
                id="createLoanBtn"
            >
                Create Loan
            </button>

        </div>

    </form>

</div>


<script>

document.addEventListener(
    'DOMContentLoaded',
    function () {


        const clientSelect =
            document.getElementById(
                'user_id'
            );


        const cardSelect =
            document.getElementById(
                'emi_card_id'
            );


        const typeSelect =
            document.getElementById(
                'loan_type_id'
            );


        const amountInput =
            document.getElementById(
                'loan_amount'
            );


        const tenureSelect =
            document.getElementById(
                'tenure_months'
            );


        const cardInfo =
            document.getElementById(
                'cardInfo'
            );


        const selectedCardNumber =
            document.getElementById(
                'selectedCardNumber'
            );


        const selectedCardLimit =
            document.getElementById(
                'selectedCardLimit'
            );


        /*
        |--------------------------------------------------------------------------
        | Interest Settings
        |--------------------------------------------------------------------------
        */

        const interestEnabled =
            {{ $interestEnabled ? 'true' : 'false' }};


        const settings = @json([

            'processing_fee' =>
                (float)($settings->processing_fee ?? 0),

            'processing_fee_type' =>
                $settings->processing_fee_type ?? 'fixed',

        ]);


        /*
        |--------------------------------------------------------------------------
        | Original Card Options
        |--------------------------------------------------------------------------
        */

        const originalCardOptions =
            Array.from(
                cardSelect.options
            ).map(
                option => ({

                    value:
                        option.value,

                    text:
                        option.text,

                    userId:
                        option.dataset.userId || '',

                    limit:
                        option.dataset.limit || '0',

                    cardNumber:
                        option.dataset.cardNumber || ''

                })
            );


        /*
        |--------------------------------------------------------------------------
        | Currency
        |--------------------------------------------------------------------------
        */

        const currencyConfig = {

            symbol:
                @js($currencySymbol),

            decimals:
                Number(
                    {{ (int) $currencyDecimals }}
                ),

            round:
                {{ $currencyRound ? 'true' : 'false' }}

        };


        /*
        |--------------------------------------------------------------------------
        | Money Format
        |--------------------------------------------------------------------------
        */

        function moneyJs(value)
        {

            let amount =
                Number(value || 0);


            if (
                currencyConfig.round
            ) {

                amount =
                    Math.round(amount);

            }


            return currencyConfig.symbol +
                amount.toLocaleString(
                    'en-IN',
                    {

                        minimumFractionDigits:
                            currencyConfig.round
                                ? 0
                                : currencyConfig.decimals,

                        maximumFractionDigits:
                            currencyConfig.round
                                ? 0
                                : currencyConfig.decimals

                    }
                );

        }


        /*
        |--------------------------------------------------------------------------
        | Get Interest Rate
        |--------------------------------------------------------------------------
        */

        function getInterestRate()
        {

            if (!interestEnabled) {

                return 0;

            }


            const option =
                typeSelect.options[
                    typeSelect.selectedIndex
                ];


            if (
                !option ||
                !option.value
            ) {

                return 0;

            }


            return Number(
                option.dataset.interestRate || 0
            );

        }


        /*
        |--------------------------------------------------------------------------
        | Update Interest Display
        |--------------------------------------------------------------------------
        */

        function updateInterestDisplay()
        {

            const rate =
                getInterestRate();


            const selectedRate =
                document.getElementById(
                    'selectedInterestRate'
                );


            const statusBox =
                document.getElementById(
                    'interestStatusBox'
                );


            const previewRate =
                document.getElementById(
                    'previewInterestRate'
                );


            if (previewRate) {

                previewRate.textContent =
                    rate + '%';

            }


            if (selectedRate) {

                if (
                    typeSelect.value
                ) {

                    selectedRate.textContent =
                        rate + '%';

                } else {

                    selectedRate.textContent =
                        'Select loan type';

                }

            }


            if (statusBox) {

                if (interestEnabled) {

                    statusBox.textContent =
                        'Enabled — ' + rate + '%';

                    statusBox.style.color =
                        '#198754';

                } else {

                    statusBox.textContent =
                        'Disabled — 0%';

                    statusBox.style.color =
                        '#64748b';

                }

            }

        }


        /*
        |--------------------------------------------------------------------------
        | Filter Cards
        |--------------------------------------------------------------------------
        */

        function filterCards()
        {

            const userId =
                clientSelect.value;


            const previous =
                cardSelect.value;


            cardSelect.innerHTML =
                '';


            const placeholder =
                document.createElement(
                    'option'
                );


            placeholder.value =
                '';


            placeholder.textContent =
                userId
                    ? 'Select EMI Card'
                    : 'Select client first';


            cardSelect.appendChild(
                placeholder
            );


            originalCardOptions.forEach(
                function (item) {


                    if (
                        !item.value ||
                        item.userId !== userId
                    ) {

                        return;

                    }


                    const option =
                        document.createElement(
                            'option'
                        );


                    option.value =
                        item.value;


                    option.textContent =
                        item.text;


                    option.dataset.limit =
                        item.limit;


                    option.dataset.cardNumber =
                        item.cardNumber;


                    if (
                        item.value === previous
                    ) {

                        option.selected =
                            true;

                    }


                    cardSelect.appendChild(
                        option
                    );

                }
            );


            updateCardSummary();


            if (
                userId &&
                cardSelect.options.length === 1
            ) {

                cardInfo.textContent =
                    'No active EMI card found for this client.';

            } else if (userId) {

                cardInfo.textContent =
                    'Select an active EMI card.';

            } else {

                cardInfo.textContent =
                    'Select a client to view active EMI cards.';

            }

        }


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

        function updateCardSummary()
        {

            const option =
                cardSelect.options[
                    cardSelect.selectedIndex
                ];


            if (
                !option ||
                !option.value
            ) {

                selectedCardNumber.textContent =
                    '—';

                selectedCardLimit.textContent =
                    '—';

                return;

            }


            selectedCardNumber.textContent =
                option.dataset.cardNumber ||
                option.textContent;


            selectedCardLimit.textContent =
                moneyJs(
                    option.dataset.limit || 0
                );

        }


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

       function showLoanDetails()
{

    document
        .querySelectorAll(
            '.loan-details-group'
        )
        .forEach(
            function (group) {

                group.classList.add(
                    'loan-hidden'
                );

            }
        );


    const option =
        typeSelect.options[
            typeSelect.selectedIndex
        ];


    if (
        !option ||
        !option.value
    ) {

        document.getElementById(
            'detailsHint'
        ).textContent =
            'Select a loan type to enter type-specific details.';

        updateInterestDisplay();

        updatePreview();

        return;

    }


    let code =
        (
            option.dataset.code ||
            option.textContent ||
            ''
        )
            .toLowerCase()
            .trim();


    /*
    |--------------------------------------------------------------------------
    | Digital Product Loan
    |--------------------------------------------------------------------------
    */

    if (
        code.includes('digital') ||
        code.includes('product') ||
        code.includes('mobile')
    ) {

        code =
            'digital_product';


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

    } else if (
        code.includes('gold')
    ) {

        code =
            'gold';


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

    } else if (
        code.includes('personal')
    ) {

        code =
            'personal';


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

    } else if (
        code.includes('vehicle') ||
        code.includes('car') ||
        code.includes('bike')
    ) {

        code =
            'vehicle';


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

    } else if (
        code.includes('business')
    ) {

        code =
            'business';


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

    } else if (
        code.includes('emergency')
    ) {

        code =
            'emergency';


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

    } else if (
        code.includes('medical')
    ) {

        code =
            'medical';


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

    } else if (
        code.includes('home')
    ) {

        code =
            'home';


    /*
    |--------------------------------------------------------------------------
    | Other
    |--------------------------------------------------------------------------
    */

    } else {

        code =
            'other';

    }


    /*
    |--------------------------------------------------------------------------
    | Show Selected Loan Type Details
    |--------------------------------------------------------------------------
    */

    const group =
        document.getElementById(
            'details-' + code
        );


    if (group) {

        group.classList.remove(
            'loan-hidden'
        );

    }


    /*
    |--------------------------------------------------------------------------
    | Update Hint
    |--------------------------------------------------------------------------
    */

    document.getElementById(
        'detailsHint'
    ).textContent =
        'Enter the details applicable to the selected loan type.';


    /*
    |--------------------------------------------------------------------------
    | Update Interest
    |--------------------------------------------------------------------------
    */

    updateInterestDisplay();


    /*
    |--------------------------------------------------------------------------
    | Update Calculation Preview
    |--------------------------------------------------------------------------
    */

    updatePreview();

}


        


        /*
        |--------------------------------------------------------------------------
        | Loan Calculation Preview
        |--------------------------------------------------------------------------
        */

        function updatePreview()
        {

            const amount =
                Number(
                    amountInput.value || 0
                );


            /*
            |--------------------------------------------------------------------------
            | Interest Rate
            |--------------------------------------------------------------------------
            */

            const interestRate =
                getInterestRate();


            /*
            |--------------------------------------------------------------------------
            | Simple Interest
            |--------------------------------------------------------------------------
            |
            | Same calculation model used by LoanCalculationService.
            |
            */

            const interestAmount =
                interestRate > 0
                    ? amount *
                        (
                            interestRate / 100
                        ) *
                        (
                            Number(
                                tenureSelect.value || 0
                            ) / 12
                        )
                    : 0;


            /*
            |--------------------------------------------------------------------------
            | Processing Fee
            |--------------------------------------------------------------------------
            */

            const fee =
                settings.processing_fee_type ===
                'percentage'

                    ? amount *
                        Number(
                            settings.processing_fee || 0
                        ) /
                        100

                    : Number(
                        settings.processing_fee || 0
                    );


            /*
            |--------------------------------------------------------------------------
            | Total Payable
            |--------------------------------------------------------------------------
            |
            | Processing fee is NOT included in EMI.
            |
            */

            const total =
                amount +
                interestAmount;


            /*
            |--------------------------------------------------------------------------
            | EMI
            |--------------------------------------------------------------------------
            */

            const tenure =
                Number(
                    tenureSelect.value || 0
                );


            const emi =
                tenure > 0
                    ? total / tenure
                    : 0;


            /*
            |--------------------------------------------------------------------------
            | Update UI
            |--------------------------------------------------------------------------
            */

            document.getElementById(
                'previewAmount'
            ).textContent =
                moneyJs(amount);


            document.getElementById(
                'previewInterestRate'
            ).textContent =
                interestRate + '%';


            document.getElementById(
                'previewInterestAmount'
            ).textContent =
                moneyJs(interestAmount);


            document.getElementById(
                'previewFee'
            ).textContent =
                moneyJs(fee);


            document.getElementById(
                'previewTotal'
            ).textContent =
                moneyJs(total);


            document.getElementById(
                'previewEmi'
            ).textContent =
                moneyJs(emi);

        }


        /*
        |--------------------------------------------------------------------------
        | Events
        |--------------------------------------------------------------------------
        */

        clientSelect.addEventListener(
            'change',
            filterCards
        );


        cardSelect.addEventListener(
            'change',
            updateCardSummary
        );


        typeSelect.addEventListener(
            'change',
            showLoanDetails
        );


        amountInput.addEventListener(
            'input',
            updatePreview
        );


        tenureSelect.addEventListener(
            'change',
            updatePreview
        );


        /*
        |--------------------------------------------------------------------------
        | Initial State
        |--------------------------------------------------------------------------
        */

        filterCards();

        showLoanDetails();

        updateInterestDisplay();

        updatePreview();

    }
);

</script>

@endsection