@extends('layouts.layoutapp')

@section('content')
    <div class="row">
        <div class="col-12">
            <div class="card me-2">
                <div class="card-header pb-0">
                    <div class="d-flex flex-row justify-content-between">
                        <div>
                            <h5 class="mb-0">Add Payment</h5>
                        </div>
                        <span class="badge bg-primary extra_amount" style="display: none;">Extra Amount: ₹ 0.00</span>
                    </div>
                </div>
                <div class="card-body">
                    <form action="{{ route('invoice-payment-store') }}" method="POST">
                        @csrf
                        <div class="row">
                            <div class="col-lg-4 mb-4">
                                <label for="invoice" class="form-label">Invoice:</label>
                                <select class="form-select select2" id="invoice_id" name="invoice" required>
                                    <option value="">Select invoice</option>
                                    @foreach($invoices as $data)
                                        <option value="{{ $data->id }}" {{ old('invoice') == $data->id ? 'selected' : '' }}>
                                            {{ $data->invoice_id }} - {{ $data->client->user->phone ?? '' }}
                                        </option>
                                    @endforeach
                                </select>
                                @error('invoice') <span class="text-danger">{{ $message }}</span> @enderror
                            </div>
                            <div class="col-lg-4 mb-4">
                                <label for="totalAmount" class="form-label">Total Amount:</label>
                                <input type="text" id="totalAmount" class="form-control" name="totalAmount"
                                    value="{{ old('totalAmount') }}" required readonly>
                                @error('totalAmount') <span class="text-danger">{{ $message }}</span> @enderror
                            </div>
                            <div class="col-lg-4 mb-4">
                                <label for="dueAmount" class="form-label">Due Amount:</label>
                                <input type="text" id="dueAmount" class="form-control" name="dueAmount"
                                    value="{{ old('dueAmount') }}" required readonly>
                                @error('dueAmount') <span class="text-danger">{{ $message }}</span> @enderror
                            </div>
                            <div class="col-lg-4 mb-4">
                                <label for="paidAmount" class="form-label">Paid Amount</label>
                                <input type="text" id="paidAmount" class="form-control" name="paidAmount"
                                    value="{{ old('paidAmount') }}" required readonly>
                                @error('paidAmount') <span class="text-danger">{{ $message }}</span> @enderror
                            </div>

                            <div class="col-lg-4 mb-4">
                                <label for="paymentDate" class="form-label">Payment Date</label>
                                <input type="date" id="paymentDate" class="form-control" name="paymentDate"
                                    value="{{ old('paymentDate', now()->toDateString()) }}" required>
                                @error('paymentDate') <span class="text-danger">{{ $message }}</span> @enderror
                            </div>
                            <div class="col-lg-4 mb-4">
                                <label for="paymentMethod" class="form-label">Payment Method</label>
                                <select name="paymentMethod" id="paymentMethod" class="form-select" required>
                                    <option value="">Select Payment Method</option>
                                    @foreach ($payment_mode as $item)
                                        <option value="{{ $item->id }}">{{ $item->name }}</option>
                                    @endforeach
                                </select>
                                @error('paymentMethod') <span class="text-danger">{{ $message }}</span> @enderror
                            </div>

                            {{-- Tendered Amount – only shown for Cash --}}
                            <div class="col-lg-4 mb-4" id="tenderedAmountContainer" style="display: none;">
                                <label for="tendered_amount" class="form-label">Tendered Amount</label>
                                <input type="number" step="0.01" name="tendered_amount" id="tendered_amount"
                                    class="form-control" value="{{ old('tendered_amount') }}"
                                    placeholder="Enter tendered amount">
                                @error('tendered_amount')
                                    <span class="text-danger">{{ $message }}</span>
                                @enderror
                            </div>

                            <div class="col-lg-4 mb-4">
                                <label for="amount" class="form-label">Amount</label>
                                <input type="number" step="0.01" id="amount" class="form-control" name="amount"
                                    value="{{ old('amount') }}" required placeholder="Enter Amount">
                                @error('amount') <span class="text-danger">{{ $message }}</span> @enderror
                            </div>

                            <div class="col-lg-12 mb-4">
                                <label for="note" class="form-label">Note:</label>
                                <textarea id="note" class="form-control" name="note">{{ old('note') }}</textarea>
                                @error('note') <span class="text-danger">{{ $message }}</span> @enderror
                            </div>
                        </div>
                        <div class="d-flex justify-content-end">
                            <button type="submit" class="btn btn-primary me-2">Save Payment</button>
                            <a href="{{ route('invoice-payment-index') }}" class="btn btn-secondary">Cancel</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script>
        let dueAmount;
        $(document).ready(function () {
            $('#invoice_id').on('change', function () {
                const invoiceId = $(this).val();
                if (invoiceId) {
                    fetch(`/invoice-payments/dtls/${invoiceId}`)
                        .then(response => response.json())
                        .then(data => {
                            $('#totalAmount').val(data.totalAmount);
                            $('#dueAmount').val(data.dueAmount);
                            dueAmount = parseFloat(data.dueAmount);
                            $('#paidAmount').val(data.paidAmount ?? 0);
                        });
                }
            });

            $('#paymentMethod').on('change', function () {
                const selectedText = $('#paymentMethod option:selected').text().toLowerCase();
                if (selectedText.includes('cash')) {
                    $('#tenderedAmountContainer').show();
                } else {
                    $('#tenderedAmountContainer').hide();
                    $('.extra_amount').hide();
                    $('#tendered_amount').val('');
                    $('#amount').val('');
                }
            });

            function calculatePaymentBreakdown() {
                let total_due = dueAmount || 0;
                let tendered_amount = parseFloat($('#tendered_amount').val()) || 0;
                let paid_amount = parseFloat($('#paidAmount').val()) || 0;

                let remaining_amount = total_due - paid_amount;

                let extra_amount = 0;
                let paying_amount = tendered_amount;

                if (tendered_amount > remaining_amount) {
                    extra_amount = tendered_amount - remaining_amount;
                    paying_amount = remaining_amount;
                }

                $('.extra_amount').text('Extra Amount: ₹ ' + extra_amount.toFixed(2));
                $('#amount').val(paying_amount.toFixed(2));
            }


            $(document).on('input', '#tendered_amount', calculatePaymentBreakdown);
        });
    </script>
@endpush