@extends('layouts.app')

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

@section('content')
<div class="container-fluid">
    <!-- Navigation Bar -->
    <div class="navigation-bar">
        <div class="row align-items-center">
            <div class="col-md-6">
                <div class="page-title">
                    <h1><i class="fas fa-plus-circle me-2 text-primary"></i>New Loan Application</h1>
                    <p class="text-muted mb-0">Create a new loan application for a client</p>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <div class="form-card card">
                <div class="card-body">
                    <!-- Simple Error Display -->
                    @if(session('error'))
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        {{ session('error') }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    @endif

                    <form method="POST" action="{{ route('loans.store') }}" enctype="multipart/form-data" id="loanForm">
                        @csrf

                        <!-- Client Information -->
                        <div class="section-wrapper mb-4">
                            <div class="section-header">
                                <div class="icon-wrapper">
                                    <i class="fas fa-user"></i>
                                </div>
                                <h5>Client Information</h5>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="mb-3">
                                        <label for="client_id" class="form-label">Client <span class="text-danger">*</span></label>
                                        <select name="client_id" id="client_id" class="form-select @error('client_id') is-invalid @enderror" required>
                                            <option value="">Select Client</option>
                                            @foreach($clients as $client)
                                                <option value="{{ $client->id }}" {{ old('client_id') == $client->id ? 'selected' : '' }}>
                                                    {{ $client->first_name }} {{ $client->last_name }} ({{ $client->client_number }})
                                                </option>
                                            @endforeach
                                        </select>
                                        @error('client_id')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Loan Details -->
                        <div class="section-wrapper mb-4">
                            <div class="section-header">
                                <div class="icon-wrapper">
                                    <i class="fas fa-money-bill-wave"></i>
                                </div>
                                <h5>Loan Details</h5>
                            </div>
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="amount" class="form-label">Loan Amount (USD) <span class="text-danger">*</span></label>
                                        <div class="input-group">
                                            <span class="input-group-text">$</span>
                                            <input type="number" name="amount" id="amount" class="form-control @error('amount') is-invalid @enderror"
                                                   value="{{ old('amount') }}" min="50" max="1000000" step="0.01" required placeholder="0.00">
                                        </div>
                                        <small class="form-text text-muted">Minimum: $50, Maximum: $1,000,000</small>
                                        @error('amount')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="interest_rate" class="form-label">Interest Rate (%) <span class="text-danger">*</span></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') }}" min="0.1" max="50" step="0.1" required placeholder="0.0">
                                            <span class="input-group-text">%</span>
                                        </div>
                                        <small class="form-text text-muted">Annual interest rate (0.1% - 50%)</small>
                                        @error('interest_rate')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="duration_months" class="form-label">Duration (Months) <span class="text-danger">*</span></label>
                                        <input type="number" name="duration_months" id="duration_months" class="form-control @error('duration_months') is-invalid @enderror"
                                               value="{{ old('duration_months') }}" min="1" max="360" required placeholder="e.g., 12">
                                        <small class="form-text text-muted">Range: 1 to 360 months</small>
                                        @error('duration_months')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="repayment_frequency" class="form-label">Repayment Frequency <span class="text-danger">*</span></label>
                                        <select name="repayment_frequency" id="repayment_frequency" class="form-select @error('repayment_frequency') is-invalid @enderror" required>
                                            <option value="">Select Frequency</option>
                                            <option value="weekly" {{ old('repayment_frequency') == 'weekly' ? 'selected' : '' }}>Weekly (52 payments/year)</option>
                                            <option value="biweekly" {{ old('repayment_frequency') == 'biweekly' ? 'selected' : '' }}>Bi-Weekly (26 payments/year)</option>
                                            <option value="monthly" {{ old('repayment_frequency', 'monthly') == 'monthly' ? 'selected' : '' }}>Monthly (12 payments/year)</option>
                                            <option value="quarterly" {{ old('repayment_frequency') == 'quarterly' ? 'selected' : '' }}>Quarterly (4 payments/year)</option>
                                        </select>
                                        @error('repayment_frequency')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="loan_type" class="form-label">Loan Type <span class="text-danger">*</span></label>
                                        <select name="loan_type" id="loan_type" class="form-select @error('loan_type') is-invalid @enderror" required>
                                            <option value="">Select Type</option>
                                            <option value="cash" {{ old('loan_type') == 'cash' ? 'selected' : '' }}>Cash Loan</option>
                                            <option value="product" {{ old('loan_type') == 'product' ? 'selected' : '' }}>Product Loan</option>
                                            <option value="personal" {{ old('loan_type') == 'personal' ? 'selected' : '' }}>Personal Loan</option>
                                            <option value="business" {{ old('loan_type') == 'business' ? 'selected' : '' }}>Business Loan</option>
                                            <option value="education" {{ old('loan_type') == 'education' ? 'selected' : '' }}>Education Loan</option>
                                            <option value="emergency" {{ old('loan_type') == 'emergency' ? 'selected' : '' }}>Emergency Loan</option>
                                            <option value="mortgage" {{ old('loan_type') == 'mortgage' ? 'selected' : '' }}>Mortgage Loan</option>
                                            <option value="auto" {{ old('loan_type') == 'auto' ? 'selected' : '' }}>Auto Loan</option>
                                            <option value="agriculture" {{ old('loan_type') == 'agriculture' ? 'selected' : '' }}>Agriculture Loan</option>
                                        </select>
                                        @error('loan_type')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="application_date" class="form-label">Application Date <span class="text-danger">*</span></label>
                                        <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>
                                        @error('application_date')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            </div>

                            <!-- Purpose -->
                            <div class="row">
                                <div class="col-12">
                                    <div class="mb-3">
                                        <label for="purpose" class="form-label">Purpose <span class="text-danger">*</span></label>
                                        <textarea name="purpose" id="purpose" class="form-control @error('purpose') is-invalid @enderror"
                                                  rows="3" required placeholder="Describe the purpose of this loan...">{{ old('purpose') }}</textarea>
                                        <small class="form-text text-muted">Please provide a detailed description of how the loan will be used (minimum 10 characters)</small>
                                        @error('purpose')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            </div>

                            <!-- Loan Calculation Results -->
                            <div class="calculation-results mt-3" id="calculationResults" style="display: none;">
                                <h6 class="mb-3"><i class="fas fa-calculator me-2"></i>Loan Amortization Calculation</h6>
                                <div class="row">
                                    <div class="col-md-3">
                                        <div class="calculation-item">
                                            <span class="calculation-label" id="paymentLabel">Periodic Payment</span>
                                            <span class="calculation-value" id="monthlyPayment">$0.00</span>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="calculation-item">
                                            <span class="calculation-label">Total Interest</span>
                                            <span class="calculation-value" id="totalInterest">$0.00</span>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="calculation-item total-repayment-item">
                                            <span class="calculation-label">Total Repayment</span>
                                            <span class="calculation-value repayment-amount" id="totalRepayment">$0.00</span>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="calculation-item">
                                            <span class="calculation-label">Total Payments</span>
                                            <span class="calculation-value" id="loanTerm">0 payments</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="row mt-2">
                                    <div class="col-12">
                                        <small class="text-muted">
                                            <i class="fas fa-info-circle me-1"></i>
                                            Calculation uses amortization formula: Fixed periodic payments with compound interest
                                        </small>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Employment Information -->
                        <div class="section-wrapper mb-4">
                            <div class="section-header">
                                <div class="icon-wrapper">
                                    <i class="fas fa-briefcase"></i>
                                </div>
                                <h5>Employment Information</h5>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="monthly_income" class="form-label">Monthly Income (USD)</label>
                                        <div class="input-group">
                                            <span class="input-group-text">$</span>
                                            <input type="number" name="monthly_income" id="monthly_income" class="form-control @error('monthly_income') is-invalid @enderror"
                                                   value="{{ old('monthly_income') }}" min="0" step="0.01" placeholder="0.00">
                                        </div>
                                        @error('monthly_income')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="employment_status" class="form-label">Employment Status</label>
                                        <select name="employment_status" id="employment_status" class="form-select @error('employment_status') is-invalid @enderror">
                                            <option value="">Select Status</option>
                                            <option value="employed" {{ old('employment_status') == 'employed' ? 'selected' : '' }}>Employed</option>
                                            <option value="self_employed" {{ old('employment_status') == 'self_employed' ? 'selected' : '' }}>Self-Employed</option>
                                            <option value="unemployed" {{ old('employment_status') == 'unemployed' ? 'selected' : '' }}>Unemployed</option>
                                            <option value="student" {{ old('employment_status') == 'student' ? 'selected' : '' }}>Student</option>
                                            <option value="retired" {{ old('employment_status') == 'retired' ? 'selected' : '' }}>Retired</option>
                                        </select>
                                        @error('employment_status')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Collateral Information -->
                        <div class="section-wrapper mb-4">
                            <div class="section-header">
                                <div class="icon-wrapper">
                                    <i class="fas fa-home"></i>
                                </div>
                                <h5>Collateral Information</h5>
                                <button type="button" class="btn btn-sm btn-outline-primary ms-auto" id="addCollateral">
                                    <i class="fas fa-plus me-1"></i>Add Collateral
                                </button>
                            </div>
                            <div id="collateralContainer">
                                <!-- Collateral entries will be added here -->
                            </div>
                        </div>

                        <!-- Guarantor & Emergency Contact Information -->
                        <div class="section-wrapper mb-4">
                            <div class="section-header">
                                <div class="icon-wrapper">
                                    <i class="fas fa-users"></i>
                                </div>
                                <h5>Guarantor & Emergency Contact Information</h5>
                                <button type="button" class="btn btn-sm btn-outline-primary ms-auto" id="addGuarantor">
                                    <i class="fas fa-plus me-1"></i>Add Guarantor
                                </button>
                            </div>
                            <div id="guarantorContainer">
                                <!-- Guarantor entries will be added here -->
                            </div>
                        </div>

                        <!-- Additional Notes -->
                        <div class="section-wrapper mb-4">
                            <div class="section-header">
                                <div class="icon-wrapper">
                                    <i class="fas fa-sticky-note"></i>
                                </div>
                                <h5>Additional Information</h5>
                            </div>
                            <div class="row">
                                <div class="col-12">
                                    <div class="mb-3">
                                        <label for="notes" class="form-label">Notes</label>
                                        <textarea name="notes" id="notes" class="form-control @error('notes') is-invalid @enderror"
                                                  rows="3" placeholder="Any additional notes or comments...">{{ old('notes') }}</textarea>
                                        @error('notes')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Submit Buttons -->
                        <div class="row">
                            <div class="col-12">
                                <div class="d-flex justify-content-end gap-2">
                                    <a href="{{ route('loans.index') }}" class="btn btn-outline-secondary">
                                        <i class="fas fa-times me-1"></i> Cancel
                                    </a>
                                    <button type="submit" class="btn btn-primary" id="submitBtn">
                                        <i class="fas fa-save me-1"></i> Submit Application
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    :root {
        --primary-green: #198754;
        --primary-green-dark: #146c43;
        --accent-yellow: #fbbf24;
        --accent-yellow-light: #fef3c7;
        --success-green: #198754;
        --white: #ffffff;
        --gray-50: #f9fafb;
        --gray-100: #f3f4f6;
        --gray-200: #e5e7eb;
        --gray-300: #d1d5db;
        --gray-600: #4b5563;
        --gray-700: #374151;
        --gray-900: #111827;
        --danger: #ef4444;
    }

    /* Navigation Bar Styles */
    .navigation-bar {
        background: white;
        padding: 1.5rem 0;
        margin-bottom: 2rem;
        border-bottom: 2px solid var(--gray-200);
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    }

    .page-title h1 {
        color: var(--gray-900);
        font-weight: 700;
        font-size: 1.75rem;
        margin-bottom: 0.25rem;
        display: flex;
        align-items: center;
    }

    .page-title h1 i {
        color: var(--primary-green);
    }

    .page-title p {
        color: var(--gray-600);
        margin-bottom: 0;
    }

    .action-buttons-nav .btn {
        padding: 0.625rem 1.25rem;
        border-radius: 8px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.025em;
        font-size: 0.875rem;
        transition: all 0.3s ease;
    }

    .action-buttons-nav .btn-outline-secondary {
        border: 2px solid var(--gray-300);
        color: var(--gray-700);
    }

    .action-buttons-nav .btn-outline-secondary:hover {
        background: var(--gray-100);
        border-color: var(--gray-400);
        transform: translateY(-1px);
    }

    .action-buttons-nav .btn-primary {
        background: var(--primary-green);
        border: none;
        box-shadow: 0 4px 12px rgba(25, 135, 84, 0.25);
    }

    .action-buttons-nav .btn-primary:hover {
        background: var(--primary-green-dark);
        transform: translateY(-1px);
        box-shadow: 0 6px 16px rgba(25, 135, 84, 0.35);
    }

    /* Form Card */
    .form-card {
        background: white;
        border-radius: 20px;
        box-shadow: 0 15px 40px rgba(0, 0, 0, 0.08);
        border: none;
        overflow: hidden;
    }

    .form-card .card-body {
        padding: 2rem;
    }

    /* Section Styles */
    .section-wrapper {
        background: var(--gray-50);
        padding: 1.5rem;
        border-radius: 14px;
        border: 2px solid var(--gray-200);
        transition: all 0.3s ease;
    }

    .section-wrapper:hover {
        border-color: var(--primary-green);
        box-shadow: 0 6px 20px rgba(25, 135, 84, 0.12);
    }

    .section-header {
        display: flex;
        align-items: center;
        margin-bottom: 1.5rem;
        padding-bottom: 0.75rem;
        border-bottom: 3px solid transparent;
        background: linear-gradient(90deg, var(--primary-green) 0%, var(--accent-yellow) 100%);
        background-clip: text;
        -webkit-background-clip: text;
        border-image: linear-gradient(90deg, var(--primary-green) 0%, var(--accent-yellow) 100%);
        border-image-slice: 1;
        border-bottom: 3px solid;
    }

    .section-header h5 {
        margin: 0;
        font-weight: 700;
        font-size: 1.1rem;
        color: var(--primary-green);
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .section-header .icon-wrapper {
        width: 36px;
        height: 36px;
        background: var(--primary-green);
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 1rem;
    }

    /* Form Controls */
    .form-label {
        font-weight: 600;
        color: var(--gray-700);
        margin-bottom: 0.5rem;
        font-size: 0.9rem;
    }

    .form-control, .form-select {
        border: 2px solid var(--gray-300);
        border-radius: 8px;
        padding: 0.75rem 1rem;
        font-size: 0.95rem;
        transition: all 0.3s ease;
    }

    .form-control:focus, .form-select:focus {
        border-color: var(--primary-green);
        box-shadow: 0 0 0 0.2rem rgba(25, 135, 84, 0.25);
    }

    .form-control.is-invalid, .form-select.is-invalid {
        border-color: var(--danger);
    }

    .invalid-feedback {
        font-size: 0.875rem;
        color: var(--danger);
        margin-top: 0.25rem;
    }

    /* Input Group */
    .input-group {
        border-radius: 8px;
    }

    .input-group-text {
        background: var(--gray-100);
        border: 2px solid var(--gray-300);
        color: var(--gray-700);
        font-weight: 500;
    }

    .input-group .form-control {
        border-left: none;
    }

    .input-group .form-control:focus {
        border-left: 2px solid var(--primary-green);
    }

    /* Calculation Results */
    .calculation-results {
        background: var(--gray-50);
        border: 2px solid var(--gray-200);
        padding: 1.5rem;
        border-radius: 12px;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
    }

    .calculation-results h6 {
        color: var(--gray-700);
        font-weight: 600;
        margin-bottom: 1rem;
        display: flex;
        align-items: center;
    }

    .calculation-results h6 i {
        color: var(--primary-green);
    }

    .calculation-item {
        text-align: center;
        padding: 0.5rem;
        border-radius: 8px;
    }

    .total-repayment-item {
        background: #198754;
        color: white;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(25, 135, 84, 0.3);
    }

    .total-repayment-item .calculation-label,
    .total-repayment-item .calculation-value {
        color: white;
    }

    .calculation-label {
        display: block;
        font-size: 0.8rem;
        opacity: 0.9;
        margin-bottom: 0.25rem;
        color: var(--gray-600);
        font-weight: 500;
    }

    .calculation-value {
        display: block;
        font-size: 1.1rem;
        font-weight: 700;
        color: var(--gray-900);
    }

    .repayment-amount {
        color: white !important;
        font-size: 1.2rem;
        font-weight: 800;
    }

    /* Buttons */
    .btn {
        padding: 0.75rem 1.5rem;
        border-radius: 8px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.025em;
        font-size: 0.875rem;
        transition: all 0.3s ease;
        display: inline-flex;
        align-items: center;
        justify-content: center;
    }

    .btn-outline-secondary {
        border: 2px solid var(--gray-300);
        color: var(--gray-700);
    }

    .btn-outline-secondary:hover {
        background: var(--gray-100);
        border-color: var(--gray-400);
        transform: translateY(-1px);
    }

    .btn-primary {
        background: var(--primary-green);
        border: none;
        box-shadow: 0 4px 12px rgba(25, 135, 84, 0.25);
    }

    .btn-primary:hover {
        background: var(--primary-green-dark);
        transform: translateY(-1px);
        box-shadow: 0 6px 16px rgba(25, 135, 84, 0.35);
    }

    /* Form Text */
    .form-text {
        font-size: 0.8rem;
        color: var(--gray-600);
        margin-top: 0.25rem;
    }

    /* Responsive Design */
    @media (max-width: 768px) {
        .navigation-bar {
            padding: 1rem 0;
        }

        .page-title h1 {
            font-size: 1.5rem;
        }

        .action-buttons-nav {
            margin-top: 1rem;
        }

        .action-buttons-nav .btn {
            width: 100%;
            margin-bottom: 0.5rem;
        }

        .form-card .card-body {
            padding: 1.5rem;
        }

        .section-wrapper {
            padding: 1rem;
        }

        .calculation-item {
            margin-bottom: 1rem;
        }
    }
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('loanForm');
    const submitBtn = document.getElementById('submitBtn');
    const amountInput = document.getElementById('amount');
    const interestRateInput = document.getElementById('interest_rate');
    const durationMonthsInput = document.getElementById('duration_months');
    const repaymentFrequencySelect = document.getElementById('repayment_frequency');
    const calculationResults = document.getElementById('calculationResults');

    // Dynamic collateral and guarantor management
    let collateralIndex = 0;
    let guarantorIndex = 0;

    function addCollateralEntry() {
        const container = document.getElementById('collateralContainer');
        const entryDiv = document.createElement('div');
        entryDiv.className = 'collateral-entry mb-3 p-3 border rounded';
        entryDiv.innerHTML = `
            <div class="row">
                <div class="col-md-5">
                    <label class="form-label">Collateral Type</label>
                    <input type="text" name="collateral_type[${collateralIndex}]" class="form-control"
                           placeholder="e.g., Land, Vehicle, House">
                </div>
                <div class="col-md-5">
                    <label class="form-label">Collateral Value (USD)</label>
                    <div class="input-group">
                        <span class="input-group-text">$</span>
                        <input type="number" name="collateral_value[${collateralIndex}]" class="form-control"
                               min="0" step="0.01" placeholder="0.00">
                    </div>
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <button type="button" class="btn btn-outline-danger btn-sm remove-collateral">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        `;
        container.appendChild(entryDiv);
        collateralIndex++;

        // Add remove event listener
        entryDiv.querySelector('.remove-collateral').addEventListener('click', function() {
            entryDiv.remove();
        });
    }

    function addGuarantorEntry() {
        const container = document.getElementById('guarantorContainer');
        const entryDiv = document.createElement('div');
        entryDiv.className = 'guarantor-entry mb-3 p-3 border rounded';
        entryDiv.innerHTML = `
            <div class="row">
                <div class="col-md-6">
                    <label class="form-label">Guarantor Name</label>
                    <input type="text" name="guarantor_name[${guarantorIndex}]" class="form-control"
                           placeholder="Full name of guarantor">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Guarantor Phone</label>
                    <input type="tel" name="guarantor_phone[${guarantorIndex}]" class="form-control"
                           placeholder="Phone number">
                </div>
            </div>
            <div class="row mt-2">
                <div class="col-md-4">
                    <label class="form-label">Email (Optional)</label>
                    <input type="email" name="guarantor_email[${guarantorIndex}]" class="form-control"
                           placeholder="guarantor@example.com">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Address</label>
                    <input type="text" name="guarantor_address[${guarantorIndex}]" class="form-control"
                           placeholder="Guarantor's address">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Relationship</label>
                    <input type="text" name="guarantor_relationship[${guarantorIndex}]" class="form-control"
                           placeholder="e.g., Spouse, Parent, Sibling">
                </div>
            </div>
            <div class="row mt-2">
                <div class="col-md-6">
                    <label class="form-label">ID Number (Optional)</label>
                    <input type="text" name="guarantor_id_number[${guarantorIndex}]" class="form-control"
                           placeholder="National ID or Passport number">
                </div>
                <div class="col-md-6 d-flex align-items-end">
                    <button type="button" class="btn btn-outline-danger btn-sm remove-guarantor w-100">
                        <i class="fas fa-trash me-1"></i>Remove Guarantor
                    </button>
                </div>
            </div>
        `;
        container.appendChild(entryDiv);
        guarantorIndex++;

        // Add remove event listener
        entryDiv.querySelector('.remove-guarantor').addEventListener('click', function() {
            entryDiv.remove();
        });
    }

    // Initialize with one empty collateral and guarantor entry
    addCollateralEntry();
    addGuarantorEntry();

    // Add collateral button event
    document.getElementById('addCollateral').addEventListener('click', function() {
        addCollateralEntry();
    });

    // Add guarantor button event
    document.getElementById('addGuarantor').addEventListener('click', function() {
        addGuarantorEntry();
    });

    // Calculate loan details using amortization formula
    function calculateLoanDetails() {
        const principal = parseFloat(amountInput.value) || 0;
        const annualRate = parseFloat(interestRateInput.value) || 0;
        const months = parseInt(durationMonthsInput.value) || 1;
        const frequency = repaymentFrequencySelect.value || 'monthly';

        console.log('Calculating with:', { principal, annualRate, months, frequency });

        if (principal > 0 && annualRate > 0 && months > 0) {
            // Get payments per year based on frequency
            const paymentsPerYear = {
                'weekly': 52,
                'biweekly': 26,
                'monthly': 12,
                'quarterly': 4
            }[frequency] || 12;

            // Calculate periodic rate and total payments
            const periodicRate = (annualRate / 100) / paymentsPerYear;
            const totalPayments = months * (paymentsPerYear / 12);

            // Amortization formula: P = L[c(1 + c)^n]/[(1 + c)^n - 1]
            let periodicPayment;
            if (periodicRate > 0) {
                const denominator = Math.pow(1 + periodicRate, totalPayments) - 1;
                const numerator = periodicRate * Math.pow(1 + periodicRate, totalPayments);
                periodicPayment = principal * (numerator / denominator);
            } else {
                periodicPayment = principal / totalPayments;
            }

            const totalRepayment = periodicPayment * totalPayments;
            const totalInterest = totalRepayment - principal;

            console.log('Results:', {
                periodicPayment,
                totalRepayment,
                totalInterest,
                periodicRate,
                totalPayments
            });

            // Display frequency-specific label
            const frequencyLabel = {
                'weekly': 'Weekly Payment',
                'biweekly': 'Bi-Weekly Payment',
                'monthly': 'Monthly Payment',
                'quarterly': 'Quarterly Payment'
            }[frequency] || 'Periodic Payment';

            // Update calculation results
            document.getElementById('paymentLabel').textContent = frequencyLabel;
            document.getElementById('monthlyPayment').textContent = formatCurrency(periodicPayment);
            document.getElementById('totalInterest').textContent = formatCurrency(totalInterest);
            document.getElementById('totalRepayment').textContent = formatCurrency(totalRepayment);
            document.getElementById('loanTerm').textContent = Math.round(totalPayments) + ' payments';

            // Show calculation results
            calculationResults.style.display = 'block';
        } else {
            calculationResults.style.display = 'none';
        }
    }

    function formatCurrency(amount) {
        return '$' + amount.toFixed(2);
    }

    // Add event listeners for real-time calculation
    [amountInput, interestRateInput, durationMonthsInput, repaymentFrequencySelect].forEach(input => {
        input.addEventListener('input', calculateLoanDetails);
        input.addEventListener('change', calculateLoanDetails);
    });

    // Form validation
    form.addEventListener('submit', function(e) {
        let isValid = true;
        const errors = [];

        // Validate amount
        if (!amountInput.value || amountInput.value < 50 || amountInput.value > 1000000) {
            errors.push('Loan amount must be between $50 and $1,000,000');
            isValid = false;
        }

        // Validate duration months
        if (!durationMonthsInput.value || durationMonthsInput.value < 1 || durationMonthsInput.value > 360) {
            errors.push('Loan duration must be between 1 and 360 months');
            isValid = false;
        }

        // Validate interest rate
        if (!interestRateInput.value || interestRateInput.value < 0.1 || interestRateInput.value > 50) {
            errors.push('Interest rate must be between 0.1% and 50%');
            isValid = false;
        }

        // Validate repayment frequency
        if (!repaymentFrequencySelect.value) {
            errors.push('Please select a repayment frequency');
            isValid = false;
        }

        if (!isValid) {
            e.preventDefault();
            alert('Please fix the following errors:\n\n' + errors.join('\n'));
        } else {
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Processing...';
        }
    });

    // Initial calculation if values exist
    calculateLoanDetails();
});
</script>
@endsection
