@extends('layouts.app')

@section('title', 'Create Group 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-users me-2 text-primary"></i>New Group Loan Application</h1>
                    <p class="text-muted mb-0">Create a new loan application for a client group</p>
                </div>
            </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.group.store') }}" enctype="multipart/form-data" id="groupLoanForm">
                        @csrf

                        <!-- Client Group Information -->
                        <div class="section-wrapper mb-4">
                            <div class="section-header">
                                <div class="icon-wrapper">
                                    <i class="fas fa-users"></i>
                                </div>
                                <h5>Client Group Information</h5>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="mb-3">
                                        <label for="client_group_id" class="form-label">Client Group <span class="text-danger">*</span></label>
                                        <select name="client_group_id" id="client_group_id" class="form-select @error('client_group_id') is-invalid @enderror" required>
                                            <option value="">Select Client Group</option>
                                            @foreach($clientGroups as $group)
                                                <option value="{{ $group->id }}" {{ old('client_group_id') == $group->id ? 'selected' : '' }}>
                                                    {{ $group->name }} ({{ $group->code }})
                                                </option>
                                            @endforeach
                                        </select>
                                        @error('client_group_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-calculator"></i>
                                </div>
                                <h5>Loan Details</h5>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="amount" class="form-label">Loan Amount <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>
                                        </div>
                                        @error('amount')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <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', '12.00') }}" min="0.1" max="50" step="0.01" required>
                                            <span class="input-group-text">%</span>
                                        </div>
                                        @error('interest_rate')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <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>
                                        @error('duration_months')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <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="monthly" {{ old('repayment_frequency') == 'monthly' ? 'selected' : '' }}>Monthly</option>
                                            <option value="weekly" {{ old('repayment_frequency') == 'weekly' ? 'selected' : '' }}>Weekly</option>
                                            <option value="biweekly" {{ old('repayment_frequency') == 'biweekly' ? 'selected' : '' }}>Bi-weekly</option>
                                            <option value="quarterly" {{ old('repayment_frequency') == 'quarterly' ? 'selected' : '' }}>Quarterly</option>
                                        </select>
                                        @error('repayment_frequency')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <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 class="col-md-6">
                                    <div class="mb-3">
                                        <label for="loan_type" class="form-label">Loan Type <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" value="Group Loan" readonly>
                                        <input type="hidden" name="loan_type" value="group">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Purpose and Notes -->
                        <div class="section-wrapper mb-4">
                            <div class="section-header">
                                <div class="icon-wrapper">
                                    <i class="fas fa-file-alt"></i>
                                </div>
                                <h5>Purpose and Notes</h5>
                            </div>
                            <div class="row">
                                <div class="col-12">
                                    <div class="mb-3">
                                        <label for="purpose" class="form-label">Loan Purpose <span class="text-danger">*</span></label>
                                        <textarea name="purpose" id="purpose" class="form-control @error('purpose') is-invalid @enderror"
                                                  rows="4" placeholder="Describe the purpose of this group loan..." required>{{ old('purpose') }}</textarea>
                                        <div class="form-text">Minimum 10 characters, maximum 1000 characters</div>
                                        @error('purpose')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="mb-3">
                                        <label for="notes" class="form-label">Additional 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>

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

                        <!-- Guarantor Information -->
                        <div class="section-wrapper mb-4">
                            <div class="section-header">
                                <div class="icon-wrapper">
                                    <i class="fas fa-user-check"></i>
                                </div>
                                <h5>Guarantor Information</h5>
                                <button type="button" class="btn btn-sm btn-outline-primary" id="addGuarantor">
                                    <i class="fas fa-plus me-1"></i>Add Guarantor
                                </button>
                            </div>
                            <div id="guarantorContainer">
                                <!-- Guarantor items will be added here dynamically -->
                            </div>
                        </div>

                        <!-- Form Actions -->
                        <div class="row">
                            <div class="col-12">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="termsCheck" required>
                                        <label class="form-check-label" for="termsCheck">
                                            I confirm that all information provided is accurate and complete
                                        </label>
                                    </div>
                                    <div>
                                        <a href="{{ route('loans.index') }}" class="btn btn-outline-secondary me-2">
                                            <i class="fas fa-times me-1"></i>Cancel
                                        </a>
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-save me-1"></i>Submit Application
                                        </button>
                                    </div>
                                </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);
    }

    /* 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);
    }

    .btn-outline-primary {
        border: 2px solid var(--primary-green);
        color: var(--primary-green);
    }

    .btn-outline-primary:hover {
        background: var(--primary-green);
        color: white;
        transform: translateY(-1px);
    }

    .btn-outline-danger {
        border: 2px solid var(--danger);
        color: var(--danger);
    }

    .btn-outline-danger:hover {
        background: var(--danger);
        color: white;
        transform: translateY(-1px);
    }

    /* 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;
        }
    }
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('groupLoanForm');
    const submitBtn = document.querySelector('button[type="submit"]');

    // 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>
                    <select name="collateral_type[${collateralIndex}]" class="form-select">
                        <option value="">Select Type</option>
                        <option value="real_estate">Real Estate</option>
                        <option value="vehicle">Vehicle</option>
                        <option value="equipment">Equipment</option>
                        <option value="inventory">Inventory</option>
                        <option value="cash">Cash Deposit</option>
                        <option value="other">Other</option>
                    </select>
                </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>
            <div class="row mt-2">
                <div class="col-12">
                    <label class="form-label">Description</label>
                    <input type="text" name="collateral_description[${collateralIndex}]" class="form-control"
                           placeholder="Brief description of the collateral">
                </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();
    });

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

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

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

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

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

        // Validate purpose
        const purpose = document.getElementById('purpose').value.trim();
        if (!purpose || purpose.length < 10) {
            errors.push('Loan purpose must be at least 10 characters long');
            isValid = false;
        }

        // Validate terms checkbox
        const termsCheck = document.getElementById('termsCheck');
        if (!termsCheck.checked) {
            errors.push('Please confirm that all information provided is accurate and complete');
            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...';
        }
    });
});
</script>

@endsection
