@extends('layouts.app')

@section('title', 'Add Payment')

@section('content')

<div class="row">
    <div class="col-lg-12">

        <!-- Page Header -->
        <div class="card card-transparent card-block card-stretch card-height border-none">
            <div class="card-body p-0 mt-lg-2 mt-0">

                <div class="d-flex flex-wrap align-items-center justify-content-between">

                    <div>
                        <h3 class="mb-1">Add Payment</h3>

                        <p class="mb-0 text-muted">
                            Record a payment against an existing order/invoice.
                        </p>
                    </div>

                    <div>
                        <a href="{{ route('payments.index') }}"
                           class="btn btn-secondary">

                            <i class="ri-arrow-left-line mr-1"></i>
                            Back to Payments

                        </a>
                    </div>

                </div>

            </div>
        </div>

    </div>
</div>


<!-- Payment Form -->
<div class="row">
    <div class="col-lg-12">

        <div class="card card-block card-stretch card-height">

            <div class="card-header">
                <div class="header-title">
                    <h4 class="card-title">Payment Information</h4>
                </div>
            </div>

            <div class="card-body">

                {{-- Success Message --}}
                @if(session('success'))
                    <div class="alert alert-success">
                        {{ session('success') }}
                    </div>
                @endif


                {{-- Error Message --}}
                @if(session('error'))
                    <div class="alert alert-danger">
                        {{ session('error') }}
                    </div>
                @endif


                {{-- Validation Errors --}}
                @if($errors->any())

                    <div class="alert alert-danger">

                        <strong>Please fix the following errors:</strong>

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

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

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

                            @endforeach

                        </ul>

                    </div>

                @endif


                <form action="{{ route('payments.store') }}"
                      method="POST">

                    @csrf


                    <div class="row">

                        <!-- ================================================= -->
                        <!-- Invoice / Order -->
                        <!-- ================================================= -->

                        <div class="form-group col-lg-6">

                            <label for="order_id">

                                Invoice / Order

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

                            </label>


                            <select
                                name="order_id"
                                id="order_id"
                                class="form-control @error('order_id') is-invalid @enderror"
                                required
                            >

                                <option value="">
                                    Select Invoice / Order
                                </option>


                                @foreach($orders as $order)

                                    <option
                                        value="{{ $order->order_id }}"

                                        data-customer-name="{{ $order->customer->customer_name ?? 'N/A' }}"

                                        data-total="{{ $order->total_amount ?? 0 }}"

                                        data-paid="{{ $order->payments_sum_amount_paid ?? 0 }}"

                                        {{ old('order_id') == $order->order_id ? 'selected' : '' }}
                                    >

                                        {{ $order->invoice->invoice_number ?? 'No Invoice' }}

                                        —

                                        {{ $order->serial_number }}

                                    </option>

                                @endforeach

                            </select>


                            @error('order_id')

                                <small class="text-danger">
                                    {{ $message }}
                                </small>

                            @enderror

                        </div>


                        <!-- ================================================= -->
                        <!-- Customer -->
                        <!-- ================================================= -->

                        <div class="form-group col-lg-6">

                            <label for="customer_display">
                                Customer
                            </label>


                            <input
                                type="text"
                                id="customer_display"
                                class="form-control"
                                placeholder="Customer will appear here"
                                readonly
                            >

                        </div>


                        <!-- ================================================= -->
                        <!-- Invoice Total -->
                        <!-- ================================================= -->

                        <div class="form-group col-lg-4">

                            <label for="invoice_total">
                                Invoice Total
                            </label>


                            <div class="input-group">

                                <div class="input-group-prepend">

                                    <span class="input-group-text">
                                        Rs.
                                    </span>

                                </div>


                                <input
                                    type="text"
                                    id="invoice_total"
                                    class="form-control"
                                    value="0.00"
                                    readonly
                                >

                            </div>

                        </div>


                        <!-- ================================================= -->
                        <!-- Already Paid -->
                        <!-- ================================================= -->

                        <div class="form-group col-lg-4">

                            <label for="already_paid">
                                Already Paid
                            </label>


                            <div class="input-group">

                                <div class="input-group-prepend">

                                    <span class="input-group-text">
                                        Rs.
                                    </span>

                                </div>


                                <input
                                    type="text"
                                    id="already_paid"
                                    class="form-control"
                                    value="0.00"
                                    readonly
                                >

                            </div>

                        </div>


                        <!-- ================================================= -->
                        <!-- Remaining Balance -->
                        <!-- ================================================= -->

                        <div class="form-group col-lg-4">

                            <label for="remaining_balance">
                                Remaining Balance
                            </label>


                            <div class="input-group">

                                <div class="input-group-prepend">

                                    <span class="input-group-text">
                                        Rs.
                                    </span>

                                </div>


                                <input
                                    type="text"
                                    id="remaining_balance"
                                    class="form-control font-weight-bold"
                                    value="0.00"
                                    readonly
                                >

                            </div>

                        </div>


                        <!-- ================================================= -->
                        <!-- Amount Paid -->
                        <!-- ================================================= -->

                        <div class="form-group col-lg-6">

                            <label for="amount_paid">

                                Amount Paid

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

                            </label>


                            <div class="input-group">

                                <div class="input-group-prepend">

                                    <span class="input-group-text">
                                        Rs.
                                    </span>

                                </div>


                                <input
                                    type="number"
                                    name="amount_paid"
                                    id="amount_paid"

                                    class="form-control @error('amount_paid') is-invalid @enderror"

                                    placeholder="Enter payment amount"

                                    min="0.01"

                                    step="0.01"

                                    value="{{ old('amount_paid') }}"

                                    required
                                >

                            </div>


                            <small class="text-muted">
                                Payment cannot exceed the remaining balance.
                            </small>


                            @error('amount_paid')

                                <small class="text-danger d-block">
                                    {{ $message }}
                                </small>

                            @enderror

                        </div>


                        <!-- ================================================= -->
                        <!-- Payment Method -->
                        <!-- ================================================= -->

                        <div class="form-group col-lg-6">

                            <label for="payment_method">

                                Payment Method

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

                            </label>


                            <select
                                name="payment_method"
                                id="payment_method"

                                class="form-control @error('payment_method') is-invalid @enderror"

                                required
                            >

                                <option value="">
                                    Select Payment Method
                                </option>


                                @foreach($paymentMethods as $method)

                                    <option
                                        value="{{ $method->method_id }}"

                                        {{ old('payment_method') == $method->method_id ? 'selected' : '' }}
                                    >

                                        {{ $method->method_type }}

                                    </option>

                                @endforeach

                            </select>


                            @error('payment_method')

                                <small class="text-danger">
                                    {{ $message }}
                                </small>

                            @enderror

                        </div>


                        <!-- ================================================= -->
                        <!-- Payment Date -->
                        <!-- ================================================= -->

                        <div class="form-group col-lg-6">

                            <label for="payment_date">

                                Payment Date

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

                            </label>


                            <input
                                type="datetime-local"

                                name="payment_date"

                                id="payment_date"

                                class="form-control @error('payment_date') is-invalid @enderror"

                                value="{{ old('payment_date', now()->format('Y-m-d\TH:i')) }}"

                                required
                            >


                            @error('payment_date')

                                <small class="text-danger">
                                    {{ $message }}
                                </small>

                            @enderror

                        </div>


                        <!-- ================================================= -->
                        <!-- Received By -->
                        <!-- ================================================= -->

                        <div class="form-group col-lg-6">

                            <label>
                                Received By
                            </label>


                            <input
                                type="text"

                                class="form-control"

                                value="{{ Auth::user()->user_name ?? 'Current User' }}"

                                readonly
                            >


                            <small class="text-muted">

                                Payment will be recorded under the currently logged-in user.

                            </small>

                        </div>

                    </div>


                    <!-- ===================================================== -->
                    <!-- Payment Preview -->
                    <!-- ===================================================== -->

                    <div class="row mt-3">

                        <div class="col-lg-12">

                            <div class="alert alert-info">

                                <div class="d-flex align-items-center">

                                    <i
                                        class="ri-information-line mr-2"
                                        style="font-size: 22px;"
                                    ></i>


                                    <div>

                                        <strong>
                                            Payment Summary
                                        </strong>


                                        <div class="mt-1">

                                            After this payment,

                                            <strong>

                                                Remaining Balance:

                                                Rs.

                                                <span id="preview_remaining">
                                                    0.00
                                                </span>

                                            </strong>

                                        </div>

                                    </div>

                                </div>

                            </div>

                        </div>

                    </div>


                    <!-- ===================================================== -->
                    <!-- Buttons -->
                    <!-- ===================================================== -->

                    <div class="row mt-3">

                        <div class="col-lg-12">

                            <div class="d-flex justify-content-end">

                                <a
                                    href="{{ route('payments.index') }}"

                                    class="btn btn-secondary mr-2"
                                >

                                    Cancel

                                </a>


                                <button
                                    type="submit"

                                    class="btn btn-primary"

                                    id="savePaymentBtn"
                                >

                                    <i class="ri-save-line mr-1"></i>

                                    Save Payment

                                </button>

                            </div>

                        </div>

                    </div>


                </form>

            </div>

        </div>

    </div>
</div>


@endsection


@push('scripts')

<script>

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


    /*
    |--------------------------------------------------------------------------
    | Elements
    |--------------------------------------------------------------------------
    */

    const orderSelect =
        document.getElementById('order_id');


    const customerDisplay =
        document.getElementById('customer_display');


    const invoiceTotal =
        document.getElementById('invoice_total');


    const alreadyPaid =
        document.getElementById('already_paid');


    const remainingBalance =
        document.getElementById('remaining_balance');


    const amountPaid =
        document.getElementById('amount_paid');


    const previewRemaining =
        document.getElementById('preview_remaining');


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



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

    function formatMoney(value) {

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

    }



    /*
    |--------------------------------------------------------------------------
    | Get Numeric Value
    |--------------------------------------------------------------------------
    */

    function getNumericValue(value) {

        return parseFloat(
            String(value || 0).replace(/,/g, '')
        ) || 0;

    }



    /*
    |--------------------------------------------------------------------------
    | Update Payment Preview
    |--------------------------------------------------------------------------
    */

    function updatePaymentPreview() {

        const remaining =
            getNumericValue(
                remainingBalance.value
            );


        const payment =
            getNumericValue(
                amountPaid.value
            );


        let afterPayment =
            remaining - payment;


        if (afterPayment < 0) {
            afterPayment = 0;
        }


        previewRemaining.textContent =
            formatMoney(afterPayment);

    }



    /*
    |--------------------------------------------------------------------------
    | Load Selected Order Information
    |--------------------------------------------------------------------------
    */

    function loadOrderInformation() {


        const selectedOption =
            orderSelect.options[
                orderSelect.selectedIndex
            ];


        /*
        |--------------------------------------------------------------------------
        | No Order Selected
        |--------------------------------------------------------------------------
        */

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

            customerDisplay.value = '';

            invoiceTotal.value = '0.00';

            alreadyPaid.value = '0.00';

            remainingBalance.value = '0.00';

            previewRemaining.textContent = '0.00';

            amountPaid.value = '';

            amountPaid.removeAttribute('max');

            savePaymentBtn.disabled = true;

            return;

        }



        /*
        |--------------------------------------------------------------------------
        | Customer
        |--------------------------------------------------------------------------
        */

        const customerName =
            selectedOption.dataset.customerName ||
            'N/A';


        /*
        |--------------------------------------------------------------------------
        | Invoice Total
        |--------------------------------------------------------------------------
        */

        const total =
            getNumericValue(
                selectedOption.dataset.total
            );


        /*
        |--------------------------------------------------------------------------
        | Already Paid
        |--------------------------------------------------------------------------
        */

        const paid =
            getNumericValue(
                selectedOption.dataset.paid
            );


        /*
        |--------------------------------------------------------------------------
        | Remaining
        |--------------------------------------------------------------------------
        */

        let remaining =
            total - paid;


        if (remaining < 0) {
            remaining = 0;
        }



        /*
        |--------------------------------------------------------------------------
        | Update Fields
        |--------------------------------------------------------------------------
        */

        customerDisplay.value =
            customerName;


        invoiceTotal.value =
            formatMoney(total);


        alreadyPaid.value =
            formatMoney(paid);


        remainingBalance.value =
            formatMoney(remaining);



        /*
        |--------------------------------------------------------------------------
        | Set Maximum Payment
        |--------------------------------------------------------------------------
        */

        amountPaid.max =
            remaining.toFixed(2);



        /*
        |--------------------------------------------------------------------------
        | Reset Amount
        |--------------------------------------------------------------------------
        */

        amountPaid.value = '';



        /*
        |--------------------------------------------------------------------------
        | Preview
        |--------------------------------------------------------------------------
        */

        previewRemaining.textContent =
            formatMoney(remaining);



        /*
        |--------------------------------------------------------------------------
        | Disable Save if Already Fully Paid
        |--------------------------------------------------------------------------
        */

        if (remaining <= 0) {

            amountPaid.disabled = true;

            savePaymentBtn.disabled = true;

        } else {

            amountPaid.disabled = false;

            savePaymentBtn.disabled = false;

        }

    }



    /*
    |--------------------------------------------------------------------------
    | Order Changed
    |--------------------------------------------------------------------------
    */

    orderSelect.addEventListener(
        'change',
        function () {

            loadOrderInformation();

        }
    );



    /*
    |--------------------------------------------------------------------------
    | Amount Changed
    |--------------------------------------------------------------------------
    */

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


            const remaining =
                getNumericValue(
                    remainingBalance.value
                );


            let amount =
                getNumericValue(
                    amountPaid.value
                );


            /*
            | Prevent amount greater than remaining
            */

            if (amount > remaining) {

                amount =
                    remaining;

                amountPaid.value =
                    remaining.toFixed(2);

            }


            /*
            | Prevent negative amount
            */

            if (amount < 0) {

                amountPaid.value = '';

            }


            updatePaymentPreview();

        }
    );



    /*
    |--------------------------------------------------------------------------
    | Form Submit Protection
    |--------------------------------------------------------------------------
    */

    const paymentForm =
        amountPaid.closest('form');


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


            const remaining =
                getNumericValue(
                    remainingBalance.value
                );


            const amount =
                getNumericValue(
                    amountPaid.value
                );


            /*
            | No order selected
            */

            if (!orderSelect.value) {

                event.preventDefault();

                alert(
                    'Please select an Invoice / Order.'
                );

                return;

            }


            /*
            | Invalid amount
            */

            if (amount <= 0) {

                event.preventDefault();

                alert(
                    'Please enter a valid payment amount.'
                );

                return;

            }


            /*
            | Payment exceeds balance
            */

            if (amount > remaining) {

                event.preventDefault();

                alert(
                    'Payment amount cannot be greater than the remaining balance.'
                );

                amountPaid.value =
                    remaining.toFixed(2);

                updatePaymentPreview();

                return;

            }

        }
    );



    /*
    |--------------------------------------------------------------------------
    | Initial Load
    |--------------------------------------------------------------------------
    */

    if (orderSelect.value) {

        loadOrderInformation();

    } else {

        savePaymentBtn.disabled = true;

    }

});

</script>

@endpush