@extends('layouts.app')

@section('title', 'Record Repayment')
@section('page-title', 'Record Repayment')

@section('content')
<div class="card">
    <div class="card-header">
        <h5 class="mb-0">Record Repayment</h5>
    </div>
    <div class="card-body">
        <form action="{{ route('partner.repayments.store') }}" method="POST">
            @csrf
            <div class="mb-3">
                <label for="loan_id" class="form-label">Loan *</label>
                <select class="form-select @error('loan_id') is-invalid @enderror" id="loan_id" name="loan_id" required>
                    <option value="">Select Loan</option>
                    @foreach($loans as $loan)
                        <option value="{{ $loan->id }}" data-remaining="{{ $loan->remaining_amount }}" {{ old('loan_id') == $loan->id ? 'selected' : '' }}>
                            {{ $loan->loan_number }} - {{ $loan->customer->name }} (Remaining: ₹{{ number_format($loan->remaining_amount, 2) }})
                        </option>
                    @endforeach
                </select>
                @error('loan_id')
                    <div class="invalid-feedback">{{ $message }}</div>
                @enderror
            </div>

            <!-- Due Date Selector -->
            <div id="due-date-section" class="mb-3" style="display: none;">
                <label for="due_date_selector" class="form-label">Select Due Date (Optional)</label>
                <select class="form-select" id="due_date_selector">
                    <option value="">-- Select Due Date to Auto-fill Amount --</option>
                </select>
                <small class="text-muted">Select a due date to automatically fill the amount, or enter a custom amount below</small>
            </div>

            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="amount" class="form-label">Amount *</label>
                    <input type="number" step="0.01" class="form-control @error('amount') is-invalid @enderror" 
                           id="amount" name="amount" value="{{ old('amount') }}" required>
                    <small class="text-muted">Select a due date above to auto-fill, or enter custom amount</small>
                    @error('amount')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-6 mb-3">
                    <label for="payment_date" class="form-label">Payment Date *</label>
                    <input type="date" class="form-control @error('payment_date') is-invalid @enderror" 
                           id="payment_date" name="payment_date" value="{{ old('payment_date', date('Y-m-d')) }}" required>
                    @error('payment_date')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="payment_method" class="form-label">Payment Method *</label>
                    <select class="form-select @error('payment_method') is-invalid @enderror" id="payment_method" name="payment_method" required>
                        <option value="cash" {{ old('payment_method') === 'cash' ? 'selected' : '' }}>Cash</option>
                        <option value="bank_transfer" {{ old('payment_method') === 'bank_transfer' ? 'selected' : '' }}>Bank Transfer</option>
                        <option value="cheque" {{ old('payment_method') === 'cheque' ? 'selected' : '' }}>Cheque</option>
                        <option value="other" {{ old('payment_method') === 'other' ? 'selected' : '' }}>Other</option>
                    </select>
                    @error('payment_method')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-6 mb-3">
                    <label for="reference_number" class="form-label">Reference Number</label>
                    <input type="text" class="form-control" id="reference_number" name="reference_number" value="{{ old('reference_number') }}">
                </div>
            </div>
            <div class="mb-3">
                <label for="notes" class="form-label">Notes</label>
                <textarea class="form-control" id="notes" name="notes" rows="3">{{ old('notes') }}</textarea>
            </div>
            <div class="d-flex gap-2">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-save"></i> Record Repayment
                </button>
                <a href="{{ route('partner.repayments.index') }}" class="btn btn-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    console.log('🔄 Repayment form script loaded');
    
    const loanSelect = document.getElementById('loan_id');
    const dueDateSection = document.getElementById('due-date-section');
    const dueDateSelector = document.getElementById('due_date_selector');
    const amountInput = document.getElementById('amount');
    const paymentDateInput = document.getElementById('payment_date');
    let currentSchedule = [];
    
    console.log('Elements found:', {
        loanSelect: !!loanSelect,
        dueDateSection: !!dueDateSection,
        dueDateSelector: !!dueDateSelector,
        amountInput: !!amountInput,
        paymentDateInput: !!paymentDateInput
    });

    // Load schedule when loan is selected
    loanSelect.addEventListener('change', function() {
        const loanId = this.value;
        console.log('📋 Loan changed to:', loanId);
        
        if (loanId) {
            loadSchedule(loanId);
        } else {
            dueDateSection.style.display = 'none';
            dueDateSelector.innerHTML = '<option value="">-- Select Due Date to Auto-fill Amount --</option>';
        }
        
        // Clear amount and reset date when loan changes
        amountInput.value = '';
        paymentDateInput.value = '{{ date('Y-m-d') }}';
    });
    
    // Handle due date selection
    dueDateSelector.addEventListener('change', function() {
        const selectedIndex = this.value;
        console.log('📅 Due date selected, index:', selectedIndex);
        
        if (selectedIndex !== '' && currentSchedule[selectedIndex]) {
            const installment = currentSchedule[selectedIndex];
            console.log('Selected installment:', installment);
            
            // Auto-fill amount
            amountInput.value = parseFloat(installment.due_amount).toFixed(2);
            
            // Auto-fill payment date with due date
            paymentDateInput.value = installment.due_date;
            
            console.log('✅ Auto-filled - Amount:', amountInput.value, 'Date:', paymentDateInput.value);
        } else {
            // Clear fields if "select" option is chosen
            amountInput.value = '';
            paymentDateInput.value = '{{ date('Y-m-d') }}';
        }
    });
    
    // Trigger initial load if loan is already selected (from old input or query params)
    if (loanSelect.value) {
        console.log('✅ Pre-selected loan detected:', loanSelect.value);
        loadSchedule(loanSelect.value);
    } else {
        console.log('⚠️ No loan pre-selected');
    }

    // Load schedule from API
    function loadSchedule(loanId) {
        console.log('📅 Loading repayment schedule for loan:', loanId);
        dueDateSection.style.display = 'block';
        dueDateSelector.innerHTML = '<option value="">Loading...</option>';

        // Build URL using placeholder and replace it
        const urlTemplate = '{{ route("partner.repayments.loan.schedule", 999999) }}';
        const url = urlTemplate.replace('999999', loanId);
        console.log('🔗 Fetching from:', url);
        
        fetch(url)
            .then(response => {
                console.log('📡 Response received:', response.status, response.statusText);
                if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                return response.json();
            })
            .then(data => {
                console.log('✅ Schedule loaded successfully:', data.schedule.length, 'installments');
                currentSchedule = data.schedule;
                populateDropdown(data.schedule);
            })
            .catch(error => {
                console.error('❌ Error loading schedule:', error);
                dueDateSelector.innerHTML = '<option value="">Error loading schedule</option>';
            });
    }

    // Populate dropdown with due dates
    function populateDropdown(schedule) {
        console.log('🎨 Populating dropdown with', schedule.length, 'installments');
        
        let options = '<option value="">-- Select Due Date to Auto-fill Amount --</option>';
        
        schedule.forEach((item, index) => {
            // Only show pending and overdue installments
            if (item.status !== 'paid' && parseFloat(item.due_amount) > 0) {
                const dueDate = new Date(item.due_date);
                const formattedDate = dueDate.toLocaleDateString('en-GB', { 
                    day: '2-digit', 
                    month: 'short', 
                    year: 'numeric' 
                });
                const amount = parseFloat(item.due_amount).toLocaleString('en-IN', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                });
                
                const statusBadge = item.status === 'overdue' ? '⚠️ Overdue' : 'Pending';
                
                options += `<option value="${index}">
                    ${formattedDate} - ₹${amount} (${statusBadge})
                </option>`;
            }
        });
        
        dueDateSelector.innerHTML = options;
        console.log('✅ Dropdown populated');
    }

    // Trigger initial load if loan is already selected (from old input or query params)
    if (loanSelect.value) {
        console.log('✅ Pre-selected loan detected:', loanSelect.value);
        loadSchedule(loanSelect.value);
    } else {
        console.log('⚠️ No loan pre-selected');
    }
    
    console.log('✓ Repayment form with dropdown due date selector initialized');
});
</script>
@endpush
@endsection

