@extends('layouts.app')

@section('content')

<style>
    .loan-app-page{
        min-height:calc(100vh - 70px);
        background:#f4f7fb;
        padding:22px 14px 40px;
        color:#172b43;
    }

    .loan-app-wrap{
        max-width:900px;
        margin:0 auto;
    }

    .loan-app-top{
        display:flex;
        align-items:center;
        gap:12px;
        margin-bottom:18px;
    }

    .loan-back{
        width:38px;
        height:38px;
        border-radius:12px;
        display:flex;
        align-items:center;
        justify-content:center;
        background:#fff;
        border:1px solid #e3e9f1;
        color:#53667d;
        text-decoration:none;
        font-size:18px;
    }

    .loan-heading h1{
        margin:0;
        font-size:23px;
        font-weight:850;
        letter-spacing:-.5px;
    }

    .loan-heading p{
        margin:4px 0 0;
        color:#7d8da1;
        font-size:11px;
    }

    .loan-card{
        background:#fff;
        border:1px solid #e2e9f1;
        border-radius:20px;
        box-shadow:0 12px 35px rgba(23,49,82,.055);
        overflow:hidden;
        margin-bottom:15px;
    }

    .loan-card-body{
        padding:20px;
    }

    /* Card summary */

    .emi-card-summary{
        position:relative;
        overflow:hidden;
        padding:20px;
        border-radius:18px;
        color:#fff;
        background:linear-gradient(135deg,#071b36,#0b3d77 65%,#1769e0);
    }

    .emi-card-summary:after{
        content:"";
        position:absolute;
        width:210px;
        height:210px;
        right:-80px;
        top:-120px;
        border:1px solid rgba(255,255,255,.12);
        border-radius:50%;
    }

    .card-summary-label{
        position:relative;
        z-index:2;
        font-size:8px;
        text-transform:uppercase;
        letter-spacing:1.1px;
        color:#a9c3df;
        font-weight:900;
    }

    .card-summary-number{
        position:relative;
        z-index:2;
        margin-top:5px;
        font-size:18px;
        letter-spacing:1.1px;
        font-weight:850;
    }

    .card-summary-row{
        position:relative;
        z-index:2;
        margin-top:20px;
        display:grid;
        grid-template-columns:1fr 1fr;
        gap:12px;
    }

    .card-summary-stat span{
        display:block;
        color:#a9c3df;
        font-size:9px;
        margin-bottom:3px;
    }

    .card-summary-stat strong{
        font-size:16px;
    }

    /* Section */

    .section-title{
        display:flex;
        justify-content:space-between;
        align-items:center;
        gap:10px;
        margin-bottom:15px;
    }

    .section-title h2{
        margin:0;
        font-size:14px;
        font-weight:850;
        color:#253c57;
    }

    .section-title span{
        color:#8998a9;
        font-size:9px;
    }

    /* Amount */

    .amount-box{
        padding:18px;
        border-radius:15px;
        background:#f7faff;
        border:1px solid #e1ebf7;
        text-align:center;
    }

    .amount-label{
        color:#7d8da1;
        font-size:9px;
        font-weight:800;
        text-transform:uppercase;
        letter-spacing:.5px;
    }

    .amount-input-wrap{
        margin:7px auto 4px;
        display:flex;
        align-items:center;
        justify-content:center;
        gap:3px;
    }

    .amount-input-wrap span{
        color:#1769e0;
        font-size:25px;
        font-weight:850;
    }

    .amount-input{
        width:190px;
        border:0;
        outline:0;
        background:transparent;
        color:#162d48;
        text-align:left;
        font-size:28px;
        font-weight:900;
        letter-spacing:-1px;
    }

    .amount-help{
        color:#8291a4;
        font-size:9px;
    }

    .amount-slider{
        width:100%;
        margin-top:17px;
        accent-color:#1769e0;
        cursor:pointer;
    }

    .slider-limits{
        display:flex;
        justify-content:space-between;
        color:#8796a8;
        font-size:9px;
        margin-top:4px;
    }

    .quick-amounts{
        display:flex;
        flex-wrap:wrap;
        justify-content:center;
        gap:7px;
        margin-top:13px;
    }

    .quick-amount{
        border:1px solid #dfe7f0;
        background:#fff;
        color:#53667d;
        border-radius:9px;
        padding:7px 10px;
        font-size:9px;
        font-weight:800;
        cursor:pointer;
    }

    .quick-amount:hover{
        border-color:#8bb5ed;
        color:#1769e0;
        background:#f5f9ff;
    }

    /* Tenure */

    .tenure-grid{
        display:grid;
        grid-template-columns:repeat(4,1fr);
        gap:8px;
    }

    .tenure-option{
        position:relative;
    }

    .tenure-option input{
        position:absolute;
        opacity:0;
        pointer-events:none;
    }

    .tenure-option label{
        display:block;
        padding:12px 7px;
        text-align:center;
        border:1px solid #dfe6ee;
        background:#fff;
        border-radius:11px;
        color:#53667d;
        font-size:10px;
        font-weight:850;
        cursor:pointer;
        transition:.18s;
    }

    .tenure-option label small{
        display:block;
        margin-top:3px;
        color:#8a98a9;
        font-size:8px;
        font-weight:600;
    }

    .tenure-option input:checked + label{
        border-color:#1769e0;
        background:#edf5ff;
        color:#1769e0;
        box-shadow:0 0 0 2px rgba(23,105,224,.07);
    }

    /* Calculation */

    .calculation-card{
        border:1px solid #dfe8f2;
        background:#fbfdff;
    }

    .calculation-row{
        display:flex;
        justify-content:space-between;
        gap:15px;
        padding:10px 0;
        border-bottom:1px solid #edf1f5;
        font-size:11px;
    }

    .calculation-row:last-child{
        border-bottom:0;
    }

    .calculation-row span{
        color:#7c8c9f;
    }

    .calculation-row strong{
        color:#273d57;
    }

    .zero-interest{
        display:inline-flex;
        align-items:center;
        gap:5px;
        padding:5px 8px;
        border-radius:7px;
        background:#eaf8f0;
        color:#198754 !important;
        font-size:9px;
        font-weight:900;
    }

    .processing-fee{
        color:#d97706 !important;
    }

    .total-row{
        padding-top:14px;
        margin-top:3px;
    }

    .total-row span{
        color:#2c425d;
        font-weight:850;
    }

    .total-row strong{
        font-size:18px;
        color:#1769e0;
    }

    .emi-highlight{
        margin-top:12px;
        padding:15px;
        border-radius:13px;
        background:#edf5ff;
        border:1px solid #d9e9ff;
        display:flex;
        justify-content:space-between;
        align-items:center;
        gap:15px;
    }

    .emi-highlight span{
        color:#61758d;
        font-size:10px;
    }

    .emi-highlight strong{
        color:#1769e0;
        font-size:21px;
        font-weight:900;
    }

    /* Warning */

    .loan-warning{
        padding:13px 14px;
        border-radius:11px;
        background:#fff6e5;
        border:1px solid #f4dfae;
        color:#986000;
        font-size:10px;
        line-height:1.55;
    }

    .loan-error{
        margin-bottom:14px;
        padding:11px 13px;
        border-radius:10px;
        background:#fff0f1;
        border:1px solid #f3cbd0;
        color:#a52834;
        font-size:11px;
        font-weight:700;
    }

    .loan-submit{
        width:100%;
        min-height:49px;
        border:0;
        border-radius:13px;
        background:#1769e0;
        color:#fff;
        font-size:12px;
        font-weight:900;
        cursor:pointer;
        box-shadow:0 8px 20px rgba(23,105,224,.18);
        transition:.18s;
    }

    .loan-submit:hover{
        transform:translateY(-1px);
        background:#125bc4;
    }

    .loan-submit:disabled{
        opacity:.55;
        cursor:not-allowed;
        transform:none;
    }

    .loan-terms{
        margin-top:10px;
        text-align:center;
        color:#8a98a9;
        font-size:8px;
        line-height:1.5;
    }

    .existing-loan{
        padding:15px;
        border-radius:13px;
        background:#fff7e8;
        border:1px solid #f1dfb7;
        color:#8b610b;
        font-size:10px;
        line-height:1.6;
    }

    .existing-loan strong{
        display:block;
        margin-bottom:4px;
        font-size:11px;
    }

    @media(max-width:650px){
        .loan-app-page{padding:14px 10px 30px}
        .loan-heading h1{font-size:20px}
        .loan-card-body{padding:15px}
        .tenure-grid{grid-template-columns:repeat(2,1fr)}
        .amount-input{font-size:25px;width:165px}
        .emi-highlight strong{font-size:18px}
    }
</style>

<div class="loan-app-page">
<div class="loan-app-wrap">

    <div class="loan-app-top">
        <a href="{{ route('client.dashboard') }}" class="loan-back">←</a>

        <div class="loan-heading">
            <h1>Apply for Loan</h1>
            <p>Simple, transparent and zero-interest EMI financing.</p>
        </div>
    </div>


    @if(session('error'))
        <div class="loan-error">
            {{ session('error') }}
        </div>
    @endif


    @if($errors->any())
        <div class="loan-error">
            {{ $errors->first() }}
        </div>
    @endif


    {{-- Active EMI Card --}}
    <div class="loan-card">
        <div class="loan-card-body">

            <div class="emi-card-summary">

                <div class="card-summary-label">
                    Active EMI Card
                </div>

                <div class="card-summary-number">
                    {{ $emiCard->card_number }}
                </div>

                <div class="card-summary-row">

                    <div class="card-summary-stat">
                        <span>Available Limit</span>
                        <strong>
                            ₹{{ number_format((float)$availableLimit, 2) }}
                        </strong>
                    </div>

                    <div class="card-summary-stat">
                        <span>Card Limit</span>
                        <strong>
                            ₹{{ number_format((float)$emiCard->card_limit, 2) }}
                        </strong>
                    </div>

                </div>

            </div>

        </div>
    </div>


    @if($activeLoanExists)

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

                <div class="existing-loan">
                    <strong>Existing Loan Application</strong>

                    You already have a pending or active loan.
                    A new loan application cannot be submitted until
                    the existing loan is completed or closed.

                </div>

            </div>
        </div>

    @else

        <form
            method="POST"
            action="{{ route('client.loans.store') }}"
            id="loanApplicationForm"
        >

            @csrf


            {{-- Loan Amount --}}
            <div class="loan-card">

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

                    <div class="section-title">
                        <h2>How much do you need?</h2>

                        <span>
                            Maximum available limit
                        </span>
                    </div>


                    <div class="amount-box">

                        <div class="amount-label">
                            Loan Amount
                        </div>


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

                            <span>₹</span>

                            <input
                                type="number"
                                name="loan_amount"
                                id="loanAmount"
                                class="amount-input"
                                min="1"
                                max="{{ (float)$availableLimit }}"
                                step="1"
                                value="{{ old('loan_amount', min(50000, (float)$availableLimit)) }}"
                                required
                            >

                        </div>


                        <div class="amount-help">
                            Enter any amount within your available limit.
                        </div>


                        <input
                            type="range"
                            id="loanAmountSlider"
                            class="amount-slider"
                            min="1"
                            max="{{ max(1, (float)$availableLimit) }}"
                            step="1000"
                            value="{{ old('loan_amount', min(50000, (float)$availableLimit)) }}"
                        >


                        <div class="slider-limits">
                            <span>₹1</span>

                            <span>
                                ₹{{ number_format((float)$availableLimit, 0) }}
                            </span>
                        </div>


                        <div class="quick-amounts">

                            @foreach([
                                10000,
                                25000,
                                50000,
                                100000
                            ] as $quickAmount)

                                @if($quickAmount <= $availableLimit)

                                    <button
                                        type="button"
                                        class="quick-amount"
                                        data-amount="{{ $quickAmount }}"
                                    >
                                        ₹{{ number_format($quickAmount) }}
                                    </button>

                                @endif

                            @endforeach

                        </div>

                    </div>

                </div>

            </div>


            {{-- Tenure --}}
            <div class="loan-card">

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

                    <div class="section-title">
                        <h2>Select repayment period</h2>

                        <span>
                            Choose your EMI tenure
                        </span>
                    </div>


                    <div class="tenure-grid">

                        @foreach([
                            3,
                            6,
                            9,
                            12,
                            18,
                            24,
                            36,
                            48
                        ] as $months)

                            <div class="tenure-option">

                                <input
                                    type="radio"
                                    name="tenure_months"
                                    id="tenure{{ $months }}"
                                    value="{{ $months }}"
                                    @checked((int)old('tenure_months', 12) === $months)
                                >

                                <label for="tenure{{ $months }}">

                                    {{ $months }} Months

                                    <small>
                                        {{ number_format($months * 30) }} days approx.
                                    </small>

                                </label>

                            </div>

                        @endforeach

                    </div>

                </div>

            </div>


            {{-- Calculation --}}
            <div class="loan-card calculation-card">

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

                    <div class="section-title">
                        <h2>Loan Summary</h2>

                        <span>
                            Live calculation
                        </span>
                    </div>


                    <div class="calculation-row">

                        <span>
                            Loan Amount
                        </span>

                        <strong id="summaryLoanAmount">
                            ₹0.00
                        </strong>

                    </div>


                    <div class="calculation-row">

                        <span>
                            Interest Rate
                        </span>

                        <strong class="zero-interest">
                            ✓ 0% Interest
                        </strong>

                    </div>


                    <div class="calculation-row">

                        <span>
                            Interest Amount
                        </span>

                        <strong>
                            ₹0.00
                        </strong>

                    </div>


                    <div class="calculation-row">

                        <span>
                            Processing Fee
                        </span>

                        <strong
                            id="summaryProcessingFee"
                            class="processing-fee"
                        >
                            Calculating...
                        </strong>

                    </div>


                    <div class="calculation-row total-row">

                        <span>
                            Total Payable
                        </span>

                        <strong id="summaryTotal">
                            ₹0.00
                        </strong>

                    </div>


                    <div class="emi-highlight">

                        <span>
                            Estimated Monthly EMI
                        </span>

                        <strong id="summaryEmi">
                            ₹0.00
                        </strong>

                    </div>


                </div>

            </div>


            {{-- Important Notice --}}
            <div class="loan-card">

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

                    <div class="loan-warning">

                        <strong>Important:</strong>

                        This is a 0% interest loan.
                        A processing fee may apply according to
                        the current loan plan. The final processing
                        fee and EMI amount will be confirmed before
                        your application is submitted.

                    </div>

                </div>

            </div>


            {{-- Submit --}}
            <div class="loan-card">

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

                    <button
                        type="submit"
                        class="loan-submit"
                        id="submitLoanButton"
                    >
                        Review & Apply for Loan
                    </button>

                    <div class="loan-terms">
                        By continuing, you confirm that the information
                        provided is correct and agree to the applicable
                        loan terms and repayment schedule.
                    </div>

                </div>

            </div>

        </form>

    @endif

</div>
</div>


<script>
(function () {

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

    const amountSlider =
        document.getElementById('loanAmountSlider');

    const tenureInputs =
        document.querySelectorAll(
            'input[name="tenure_months"]'
        );

    const summaryAmount =
        document.getElementById(
            'summaryLoanAmount'
        );

    const summaryFee =
        document.getElementById(
            'summaryProcessingFee'
        );

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

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


    if (!amountInput) {
        return;
    }


    const calculateUrl =
        @json(route('client.loans.calculate'));


    const csrfToken =
        document.querySelector(
            'input[name="_token"]'
        ).value;


    let calculationTimer = null;


    function formatMoney(value) {

        return '₹' +
            Number(value || 0).toLocaleString(
                'en-IN',
                {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                }
            );
    }


    function getTenure() {

        const selected =
            document.querySelector(
                'input[name="tenure_months"]:checked'
            );

        return selected
            ? parseInt(selected.value)
            : 12;
    }


    function updateBasicAmount() {

        let amount =
            parseFloat(
                amountInput.value
            ) || 0;

        const max =
            parseFloat(
                amountInput.max
            ) || 0;


        if (max > 0 && amount > max) {

            amount = max;

            amountInput.value =
                Math.floor(max);
        }


        if (amount < 1) {
            amount = 0;
        }


        amountSlider.value =
            amount;


        summaryAmount.textContent =
            formatMoney(amount);


        return amount;
    }


    async function calculateLoan() {

        const amount =
            updateBasicAmount();

        const tenure =
            getTenure();


        if (
            amount <= 0 ||
            tenure <= 0
        ) {

            summaryFee.textContent =
                '—';

            summaryTotal.textContent =
                '₹0.00';

            summaryEmi.textContent =
                '₹0.00';

            return;
        }


        summaryFee.textContent =
            'Calculating...';


        try {

            const response =
                await fetch(
                    calculateUrl,
                    {
                        method: 'POST',

                        headers: {
                            'Content-Type':
                                'application/json',

                            'Accept':
                                'application/json',

                            'X-CSRF-TOKEN':
                                csrfToken,

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

                        body:
                            JSON.stringify({
                                loan_amount:
                                    amount,

                                tenure_months:
                                    tenure
                            })
                    }
                );


            const result =
                await response.json();


            if (
                !response.ok ||
                !result.success
            ) {

                throw new Error(
                    'Unable to calculate loan.'
                );
            }


            const data =
                result.data;


            summaryFee.textContent =
                formatMoney(
                    data.processing_fee
                );


            summaryTotal.textContent =
                formatMoney(
                    data.total_payable
                );


            summaryEmi.textContent =
                formatMoney(
                    data.emi_amount
                );


        } catch (error) {

            console.error(error);

            summaryFee.textContent =
                '—';

            summaryTotal.textContent =
                '—';

            summaryEmi.textContent =
                '—';
        }

    }


    amountInput.addEventListener(
        'input',
        function () {

            amountSlider.value =
                this.value;

            clearTimeout(
                calculationTimer
            );

            calculationTimer =
                setTimeout(
                    calculateLoan,
                    250
                );
        }
    );


    amountSlider.addEventListener(
        'input',
        function () {

            amountInput.value =
                this.value;

            calculateLoan();
        }
    );


    tenureInputs.forEach(
        function (input) {

            input.addEventListener(
                'change',
                calculateLoan
            );

        }
    );


    document.querySelectorAll(
        '.quick-amount'
    ).forEach(
        function (button) {

            button.addEventListener(
                'click',
                function () {

                    const amount =
                        this.dataset.amount;

                    amountInput.value =
                        amount;

                    amountSlider.value =
                        amount;

                    calculateLoan();

                }
            );

        }
    );


    /*
    |--------------------------------------------------------------------------
    | Initial Calculation
    |--------------------------------------------------------------------------
    */

    calculateLoan();

})();
</script>

@endsection