@extends('adminlte::page')

@section('title', 'Create Loan Application')

@section('content_header')
    <div class="d-flex justify-content-between align-items-center">
        <div>
            <h1 class="mb-0">Create Loan Application</h1>
        </div>
        <div class="d-flex align-items-center">
            <a href="{{ route('loans.index') }}" class="btn btn-secondary btn-sm" title="Back to Loans">
                <i class="fas fa-arrow-left mr-1"></i>Back to Loans
            </a>
        </div>
    </div>
@stop

@section('content')
<div class="container-fluid">
    <div class="row">
        <!-- Left Column - Minimal Form -->
        <div class="col-lg-5 col-md-12">
            <div class="card shadow-sm border-0">
                <div class="card-header bg-white py-3">
                    <h5 class="card-title mb-0">
                        <i class="fas fa-plus-circle mr-2"></i>New Loan Application
                    </h5>
                </div>

                <form id="loan-form" action="{{ route('loans.store') }}" method="POST" enctype="multipart/form-data">
                    @csrf
                    <div class="card-body py-4">
                        <!-- Member Selection -->
                        <div class="form-group mb-3">
                            <label for="user_id" class="text-muted small text-uppercase">Member</label>
                            <select name="user_id" id="user_id" class="form-control @error('user_id') is-invalid @enderror" required>
                                <option value="">Select member...</option>
                                @foreach($users as $user)
                                <option value="{{ $user->id }}" {{ old('user_id') == $user->id ? 'selected' : '' }}>
                                    {{ $user->full_name }} ({{ $user->id_number }})
                                </option>
                                @endforeach
                            </select>
                            @error('user_id')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                        </div>

                        <!-- Loan Amount -->
                        <div class="form-group mb-3">
                            <label for="amount" class="text-muted small text-uppercase">Loan Amount</label>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text bg-light"><i class="fas fa-money-bill-wave text-success"></i></span>
                                </div>
                                <input type="number" name="amount" id="amount" class="form-control @error('amount') is-invalid @enderror"
                                       value="{{ old('amount') }}" min="1000" step="0.01" placeholder="0.00" required>
                                <div class="input-group-append">
                                    <span class="input-group-text bg-light">KSh</span>
                                </div>
                            </div>
                            @error('amount')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                        </div>

                        <!-- Interest Rate -->
                        <div class="form-group mb-3">
                            <label for="interest_rate" class="text-muted small text-uppercase">Interest Rate</label>
                            <div class="input-group">
                                <input type="number" name="interest_rate" id="interest_rate" class="form-control @error('interest_rate') is-invalid @enderror"
                                       value="{{ old('interest_rate', 12) }}" min="0" max="50" step="0.01" placeholder="0.00" required>
                                <div class="input-group-append">
                                    <span class="input-group-text bg-light">%</span>
                                </div>
                            </div>
                            @error('interest_rate')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                        </div>

                        <!-- Application Date & Return Date -->
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label for="application_date" class="text-muted small text-uppercase">Application Date</label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text bg-light"><i class="fas fa-calendar-alt text-primary"></i></span>
                                        </div>
                                        <input type="date" name="application_date" id="application_date" class="form-control @error('application_date') is-invalid @enderror"
                                               value="{{ old('application_date', date('Y-m-d')) }}" required>
                                    </div>
                                    @error('application_date')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label for="return_date" class="text-muted small text-uppercase">Return Date</label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text bg-light"><i class="fas fa-calendar-check text-success"></i></span>
                                        </div>
                                        <input type="date" name="return_date" id="return_date" class="form-control @error('return_date') is-invalid @enderror"
                                               value="{{ old('return_date') }}" required>
                                    </div>
                                    @error('return_date')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <!-- Notes - Compact -->
                        <div class="form-group mb-3">
                            <label for="notes" class="text-muted small text-uppercase">Notes</label>
                            <textarea name="notes" id="notes" class="form-control @error('notes') is-invalid @enderror"
                                      rows="2" placeholder="Optional notes...">{{ old('notes') }}</textarea>
                            @error('notes')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                        </div>

                        <!-- Submit Button -->
                        <div class="form-group mb-0">
                            <button type="submit" class="btn btn-success btn-block font-weight-bold">
                                <i class="fas fa-paper-plane mr-2"></i>Create Loan Application
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- Right Column - Guarantees & Calculation Review -->
        <div class="col-lg-7 col-md-12">
            <!-- Guarantees Section -->
            <div class="card border-0 shadow-sm bg-light mb-3">
                <div class="card-header bg-white border-0 py-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <h6 class="card-title mb-0 text-muted">
                            <i class="fas fa-shield-alt mr-2 text-warning"></i>SECURITY & GUARANTEES
                        </h6>
                        <div class="btn-group btn-group-sm">
                            <button type="button" class="btn btn-outline-success btn-sm" id="add-salary-guarantee">
                                <i class="fas fa-briefcase mr-1"></i>Salary
                            </button>
                            <button type="button" class="btn btn-outline-info btn-sm" id="add-collateral-guarantee">
                                <i class="fas fa-home mr-1"></i>Collateral
                            </button>
                            <button type="button" class="btn btn-outline-primary btn-sm" id="add-guarantor">
                                <i class="fas fa-users mr-1"></i>Guarantor
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body py-3">
                    <div id="guarantees-container">
                        <!-- Dynamic guarantees will be added here -->
                    </div>
                    @error('guarantee')
                        <div class="alert alert-danger alert-sm mt-2 mb-0">
                            <i class="fas fa-exclamation-triangle mr-1"></i>{{ $message }}
                        </div>
                    @enderror

                    <div class="text-muted small mt-2">
                        <i class="fas fa-info-circle mr-1"></i>
                        Add security/guarantee for the loan application.
                    </div>
                </div>
            </div>

            <!-- Loan Calculation Review -->
            <div class="card shadow-sm border-0 bg-light">
                <div class="card-header bg-white border-0 py-3">
                    <h5 class="card-title mb-0 text-muted">
                        <i class="fas fa-calculator mr-2 text-info"></i>Calculation Review
                    </h5>
                </div>
                <div class="card-body py-4">
                    <!-- Compact Calculation Display -->
                    <div class="row">
                        <div class="col-6 mb-3">
                            <div class="text-center p-3 bg-white rounded shadow-sm">
                                <i class="fas fa-coins text-primary mb-2 fa-lg"></i>
                                <div class="small text-muted">PRINCIPAL</div>
                                <div class="h5 text-primary font-weight-bold mb-0" id="preview-principal">KSh 0.00</div>
                            </div>
                        </div>
                        <div class="col-6 mb-3">
                            <div class="text-center p-3 bg-white rounded shadow-sm">
                                <i class="fas fa-percentage text-warning mb-2 fa-lg"></i>
                                <div class="small text-muted">INTEREST</div>
                                <div class="h5 text-warning font-weight-bold mb-0" id="preview-interest">KSh 0.00</div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-6 mb-3">
                            <div class="text-center p-3 bg-white rounded shadow-sm">
                                <i class="fas fa-money-bill-wave text-success mb-2 fa-lg"></i>
                                <div class="small text-muted">TOTAL AMOUNT</div>
                                <div class="h5 text-success font-weight-bold mb-0" id="preview-total">KSh 0.00</div>
                            </div>
                        </div>
                        <div class="col-6 mb-3">
                            <div class="text-center p-3 bg-white rounded shadow-sm">
                                <i class="fas fa-calendar-check text-info mb-2 fa-lg"></i>
                                <div class="small text-muted">MONTHLY PAYMENT</div>
                                <div class="h5 text-info font-weight-bold mb-0" id="preview-monthly">KSh 0.00</div>
                            </div>
                        </div>
                    </div>

                    <!-- Compact Payment Schedule -->
                    <div class="mt-3">
                        <div class="small text-muted mb-2">
                            <i class="fas fa-list-ol mr-1"></i>PAYMENT SCHEDULE
                        </div>
                        <div class="bg-white rounded p-3">
                            <div class="table-responsive">
                                <table class="table table-sm mb-0">
                                    <thead>
                                        <tr class="text-muted small">
                                            <th class="border-0 py-1">#</th>
                                            <th class="border-0 py-1">Due Date</th>
                                            <th class="border-0 py-1 text-right">Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody id="schedule-preview" class="small">
                                        <tr>
                                            <td colspan="3" class="text-center text-muted py-2 border-0">
                                                <i class="fas fa-calculator mr-1"></i>Enter loan details above
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>
@stop

@push('css')
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
@endpush

@push('js')
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script>
$(document).ready(function() {
    // Show success message if it exists
    @if(session('success'))
        toastr.success('{{ session('success') }}');
    @endif

    // Show error message if it exists
    @if(session('error'))
        toastr.error('{{ session('error') }}');
    @endif
    let guaranteeCounter = 0;

    function calculateLoan() {
        var amount = parseFloat($('#amount').val()) || 0;
        var interestRate = parseFloat($('#interest_rate').val()) || 0;
        var applicationDate = $('#application_date').val();
        var returnDate = $('#return_date').val();

        var termMonths = 0;
        if (applicationDate && returnDate) {
            var startDate = new Date(applicationDate);
            var endDate = new Date(returnDate);
            var timeDiff = endDate.getTime() - startDate.getTime();
            termMonths = Math.ceil(timeDiff / (1000 * 3600 * 24 * 30)); // Approximate months
            termMonths = Math.max(1, termMonths); // Minimum 1 month
        }

        var interestAmount = amount * (interestRate / 100);
        var totalAmount = amount + interestAmount;
        var monthlyPayment = termMonths > 0 ? totalAmount / termMonths : 0;

        // Update main calculation displays
        $('#preview-principal').text('KSh ' + amount.toLocaleString('en-KE', {minimumFractionDigits: 2, maximumFractionDigits: 2}));
        $('#preview-interest').text('KSh ' + interestAmount.toLocaleString('en-KE', {minimumFractionDigits: 2, maximumFractionDigits: 2}));
        $('#preview-total').text('KSh ' + totalAmount.toLocaleString('en-KE', {minimumFractionDigits: 2, maximumFractionDigits: 2}));
        $('#preview-monthly').text('KSh ' + monthlyPayment.toLocaleString('en-KE', {minimumFractionDigits: 2, maximumFractionDigits: 2}));

        // Update payment schedule preview
        updateSchedulePreview(amount, interestRate, termMonths, monthlyPayment);
    }

    function updateSchedulePreview(amount, interestRate, termMonths, monthlyPayment) {
        var scheduleHtml = '';

        if (amount > 0 && termMonths > 0) {
            var currentDate = new Date();
            var previewMonths = Math.min(termMonths, 6); // Show first 6 months

            for (var month = 1; month <= previewMonths; month++) {
                var dueDate = new Date(currentDate);
                dueDate.setMonth(currentDate.getMonth() + month - 1);

                scheduleHtml += '<tr>';
                scheduleHtml += '<td class="text-center">' + month + '</td>';
                scheduleHtml += '<td>' + dueDate.toLocaleDateString('en-US', { month: 'short', year: 'numeric' }) + '</td>';
                scheduleHtml += '<td class="text-right font-weight-bold">KSh ' + monthlyPayment.toLocaleString('en-KE', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + '</td>';
                scheduleHtml += '</tr>';
            }

            if (termMonths > 6) {
                scheduleHtml += '<tr>';
                scheduleHtml += '<td colspan="3" class="text-center text-muted py-2">';
                scheduleHtml += '<small>... and ' + (termMonths - 6) + ' more payments</small>';
                scheduleHtml += '</td>';
                scheduleHtml += '</tr>';
            }
        } else {
            scheduleHtml = '<tr><td colspan="3" class="text-center text-muted py-3"><i class="fas fa-calculator mr-1"></i>Enter loan details to see schedule</td></tr>';
        }

        $('#schedule-preview').html(scheduleHtml);
    }

    $('#amount, #interest_rate, #application_date, #return_date').on('input change', calculateLoan);
    calculateLoan(); // Initial calculation

    // Add Salary Guarantee
    $('#add-salary-guarantee').on('click', function() {
        addSalaryGuarantee();
    });

    // Add Collateral Guarantee
    $('#add-collateral-guarantee').on('click', function() {
        addCollateralGuarantee();
    });

    // Add Guarantor
    $('#add-guarantor').on('click', function() {
        addGuarantor();
    });

    function addSalaryGuarantee() {
        const index = guaranteeCounter++;
        const html = `
            <div class="guarantee-item border rounded p-3 mb-3 bg-light" data-type="salary" data-index="${index}">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="mb-0"><i class="fas fa-briefcase text-success mr-2"></i>Salary Guarantee</h6>
                    <button type="button" class="btn btn-sm btn-outline-danger remove-guarantee">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
                <input type="hidden" name="guarantees[${index}][type]" value="salary">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Employer Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="guarantees[${index}][salary][employer_name]" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Employer Phone</label>
                            <input type="tel" class="form-control" name="guarantees[${index}][salary][employer_phone]">
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-8">
                        <div class="form-group">
                            <label>Employer Address <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="guarantees[${index}][salary][employer_address]" required>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Monthly Salary (KSh) <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" name="guarantees[${index}][salary][monthly_salary]" min="0" step="0.01" required>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Employee Position <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="guarantees[${index}][salary][employee_position]" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Employment Start Date <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" name="guarantees[${index}][salary][employment_start_date]" required>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Employment Letter</label>
                            <input type="file" class="form-control-file" name="guarantees[${index}][salary][employment_letter]" accept=".pdf,.doc,.docx">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Confirmation Letter</label>
                            <input type="file" class="form-control-file" name="guarantees[${index}][salary][confirmation_letter]" accept=".pdf,.doc,.docx">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Payslips (2 months)</label>
                            <input type="file" class="form-control-file" name="guarantees[${index}][salary][payslips][]" multiple accept=".pdf,.doc,.docx,.jpg,.jpeg,.png">
                        </div>
                    </div>
                </div>
            </div>
        `;
        $('#guarantees-container').append(html);
    }

    function addCollateralGuarantee() {
        const index = guaranteeCounter++;
        const html = `
            <div class="guarantee-item border rounded p-3 mb-3 bg-light" data-type="collateral" data-index="${index}">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="mb-0"><i class="fas fa-home text-info mr-2"></i>Collateral Guarantee</h6>
                    <button type="button" class="btn btn-sm btn-outline-danger remove-guarantee">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
                <input type="hidden" name="guarantees[${index}][type]" value="collateral">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Item Type <span class="text-danger">*</span></label>
                            <select class="form-control" name="guarantees[${index}][collateral][item_type]" required>
                                <option value="">Select Item Type</option>
                                <option value="vehicle">Vehicle</option>
                                <option value="land">Land/Property</option>
                                <option value="house">House</option>
                                <option value="machinery">Machinery/Equipment</option>
                                <option value="other">Other</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Estimated Value (KSh) <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" name="guarantees[${index}][collateral][estimated_value]" min="0" step="0.01" required>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label>Item Description <span class="text-danger">*</span></label>
                            <textarea class="form-control" name="guarantees[${index}][collateral][item_description]" rows="2" required></textarea>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Ownership Document Type <span class="text-danger">*</span></label>
                            <select class="form-control" name="guarantees[${index}][collateral][ownership_document_type]" required>
                                <option value="">Select Document Type</option>
                                <option value="title_deed">Title Deed</option>
                                <option value="log_book">Log Book</option>
                                <option value="receipt">Purchase Receipt</option>
                                <option value="certificate">Ownership Certificate</option>
                                <option value="other">Other Document</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Document Number <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="guarantees[${index}][collateral][ownership_document_number]" required>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Document Date <span class="text-danger">*</span></label>
                            <input type="date" class="form-control" name="guarantees[${index}][collateral][ownership_document_date]" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Ownership Document</label>
                            <input type="file" class="form-control-file" name="guarantees[${index}][collateral][document_file]" accept=".pdf,.doc,.docx,.jpg,.jpeg,.png">
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label>Ownership Details</label>
                            <textarea class="form-control" name="guarantees[${index}][collateral][ownership_details]" rows="2" placeholder="Additional ownership information"></textarea>
                        </div>
                    </div>
                </div>
            </div>
        `;
        $('#guarantees-container').append(html);
    }

    function addGuarantor() {
        const index = guaranteeCounter++;
        const html = `
            <div class="guarantee-item border rounded p-3 mb-3 bg-light" data-type="guarantor" data-index="${index}">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="mb-0"><i class="fas fa-users text-primary mr-2"></i>Guarantor</h6>
                    <button type="button" class="btn btn-sm btn-outline-danger remove-guarantee">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
                <input type="hidden" name="guarantees[${index}][type]" value="guarantor">
                <div class="row">
                    <div class="col-md-8">
                        <div class="form-group">
                            <label>Guarantor (Member) <span class="text-danger">*</span></label>
                            <select class="form-control guarantor-select" name="guarantees[${index}][guarantor][guarantor_user_id]" required>
                                <option value="">Select Guarantor</option>
                                @foreach($users as $user)
                                <option value="{{ $user->id }}">{{ $user->full_name }} ({{ $user->id_number }})</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Guarantee Amount (KSh) <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" name="guarantees[${index}][guarantor][guarantee_amount]" min="0" step="0.01" required>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Relationship Type <span class="text-danger">*</span></label>
                            <select class="form-control" name="guarantees[${index}][guarantor][relationship_type]" required>
                                <option value="">Select Relationship</option>
                                <option value="family">Family Member</option>
                                <option value="friend">Friend</option>
                                <option value="colleague">Colleague</option>
                                <option value="other">Other</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Relationship Details</label>
                            <input type="text" class="form-control" name="guarantees[${index}][guarantor][relationship_details]" placeholder="Additional relationship details">
                        </div>
                    </div>
                </div>
            </div>
        `;
        $('#guarantees-container').append(html);
    }

    // Remove guarantee
    $(document).on('click', '.remove-guarantee', function() {
        $(this).closest('.guarantee-item').remove();
    });
});
</script>
@endpush

