<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Apply for Loan | IMMIA FINANCE LIMITED</title>
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    
    <style>
        :root {
            --primary: #1e40af;
            --primary-dark: #1e3a8a;
            --secondary: #0f172a;
            --accent: #06b6d4;
            --light: #f8fafc;
        }
        
        .sidebar {
            transition: all 0.3s ease;
        }
        
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
            }
            
            .sidebar.active {
                transform: translateX(0);
            }
        }
        
        .card-hover {
            transition: all 0.3s ease;
        }
        
        .card-hover:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        }
        
        .notification-dot {
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }

        .text-truncate-safe {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            min-width: 0;
        }

        .prefilled-field {
            background-color: #f8fafc;
            border-color: #e2e8f0;
            color: #64748b;
            cursor: not-allowed;
        }

        .form-section {
            transition: all 0.3s ease;
        }

        .loading-spinner {
            display: none;
        }

        .loading-spinner.active {
            display: inline-block;
        }

        /* Multi-step form styles */
        .step-indicator {
            display: flex;
            justify-content: space-between;
            align-items: center;
            max-width: 800px;
            margin: 0 auto 2rem;
            position: relative;
        }

        .step-indicator::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 0;
            right: 0;
            height: 2px;
            background: #e2e8f0;
            z-index: 1;
            transform: translateY(-50%);
        }

        .step {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: white;
            border: 2px solid #e2e8f0;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            color: #94a3b8;
            position: relative;
            z-index: 2;
            transition: all 0.3s ease;
        }

        .step.active {
            background: #1e40af;
            border-color: #1e40af;
            color: white;
        }

        .step.completed {
            background: #10b981;
            border-color: #10b981;
            color: white;
        }

        .step-label {
            position: absolute;
            top: 45px;
            left: 50%;
            transform: translateX(-50%);
            white-space: nowrap;
            font-size: 0.875rem;
            color: #64748b;
        }

        .step.active .step-label {
            color: #1e40af;
            font-weight: 600;
        }

        .step.completed .step-label {
            color: #10b981;
        }

        .form-page {
            display: none;
        }

        .form-page.active {
            display: block;
        }

        /* File upload styles */
        .file-drop-area {
            border: 2px dashed #cbd5e1;
            border-radius: 0.5rem;
            padding: 2rem;
            text-align: center;
            transition: all 0.3s ease;
            cursor: pointer;
            background: #f8fafc;
        }

        .file-drop-area:hover {
            border-color: #1e40af;
            background: #eff6ff;
        }

        .file-drop-area.dragover {
            border-color: #1e40af;
            background: #eff6ff;
            transform: scale(1.02);
        }

        .file-preview {
            display: flex;
            align-items: center;
            padding: 1rem;
            background: #f8fafc;
            border-radius: 0.5rem;
            margin-top: 1rem;
        }

        .file-preview-icon {
            width: 48px;
            height: 48px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #1e40af;
            color: white;
            border-radius: 0.375rem;
            margin-right: 1rem;
        }

        .file-preview-info {
            flex: 1;
        }

        .file-preview-name {
            font-weight: 500;
            color: #1e293b;
        }

        .file-preview-size {
            font-size: 0.875rem;
            color: #64748b;
        }

        .file-preview-remove {
            color: #ef4444;
            cursor: pointer;
            padding: 0.5rem;
        }

        /* Requirements checklist */
        .requirement-item {
            display: flex;
            align-items: center;
            padding: 1rem;
            border: 1px solid #e2e8f0;
            border-radius: 0.5rem;
            margin-bottom: 0.5rem;
            transition: all 0.3s ease;
        }

        .requirement-item.completed {
            background: #f0fdf4;
            border-color: #86efac;
        }

        .requirement-item.mandatory {
            border-left: 4px solid #ef4444;
        }

        .requirement-item.optional {
            border-left: 4px solid #3b82f6;
        }
        
        .error-message {
            color: #ef4444;
            font-size: 0.875rem;
            margin-top: 0.25rem;
        }
    </style>
</head>
<body class="bg-gray-50">
    <?php
        $customer = Auth::guard('customer')->user();
        $hasProfilePicture = $customer->docpath && Storage::disk('public')->exists($customer->docpath);
        $profilePictureUrl = $hasProfilePicture ? asset('storage/' . $customer->docpath) : 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?auto=format&fit=crop&w=500&q=60';
    ?>

    <!-- Mobile Menu Button -->
    <button id="mobile-menu-button" class="lg:hidden fixed top-4 left-4 z-50 bg-blue-600 text-white p-3 rounded-lg shadow-lg">
        <i class="fas fa-bars"></i>
    </button>

    <!-- Sidebar -->
    <div id="sidebar" class="sidebar fixed inset-y-0 left-0 z-40 w-64 bg-white shadow-lg">
        <!-- Logo -->
        <div class="p-6 border-b border-gray-200">
            <div class="flex items-center space-x-3">
                <div class="w-10 h-10 bg-blue-600 rounded-lg flex items-center justify-center">
                    <i class="fas fa-hand-holding-usd text-white text-lg"></i>
                </div>
                <div>
                    <h1 class="text-xl font-bold text-blue-600">IMMIA FINANCE</h1>
                    <p class="text-gray-500 text-xs">Client Portal</p>
                </div>
            </div>
        </div>
        
        <!-- Navigation -->
        <nav class="p-4 space-y-2">
            <a href="<?php echo e(route('customer.dashboard')); ?>" class="flex items-center space-x-3 p-3 text-gray-700 hover:bg-gray-100 rounded-lg font-medium">
                <i class="fas fa-tachometer-alt w-5"></i>
                <span>Dashboard</span>
            </a>
            <a href="<?php echo e(route('customer.applications.index')); ?>" class="flex items-center space-x-3 p-3 text-gray-700 hover:bg-gray-100 rounded-lg font-medium">
                <i class="fas fa-file-invoice-dollar w-5"></i>
                <span>My Applications</span>
            </a>
            <a href="<?php echo e(route('customer.loan.application.show')); ?>" class="flex items-center space-x-3 p-3 bg-blue-50 text-blue-600 rounded-lg font-medium">
               <i class="fas fa-paper-plane w-5"></i>
               <span>Apply for Loan</span>
            </a>
            <a href="#" class="flex items-center space-x-3 p-3 text-gray-700 hover:bg-gray-100 rounded-lg font-medium">
                <i class="fas fa-money-bill-wave w-5"></i>
                <span>Make Payment</span>
            </a>
            <a href="<?php echo e(route('customer.transactions.history')); ?>" 
                class="flex items-center space-x-3 p-3 text-gray-700 hover:bg-gray-100 rounded-lg font-medium">
                <i class="fas fa-history w-5"></i>
                <span>Transaction History</span>
            </a>
            <a href="#" class="flex items-center space-x-3 p-3 text-gray-700 hover:bg-gray-100 rounded-lg font-medium">
                <i class="fas fa-file-alt w-5"></i>
                <span>Documents</span>
            </a>
            <a href="<?php echo e(route('customer.profile.show')); ?>" class="flex items-center space-x-3 p-3 text-gray-700 hover:bg-gray-100 rounded-lg font-medium">
                <i class="fas fa-user-cog w-5"></i>
                <span>Profile Settings</span>
            </a>
            <a href="#" class="flex items-center space-x-3 p-3 text-gray-700 hover:bg-gray-100 rounded-lg font-medium">
                <i class="fas fa-question-circle w-5"></i>
                <span>Help & Support</span>
            </a>
            <form method="POST" action="<?php echo e(route('customer.logout')); ?>" class="mt-8">
                <?php echo csrf_field(); ?>
                <button type="submit" class="flex items-center space-x-3 p-3 text-gray-700 hover:bg-gray-100 rounded-lg font-medium w-full">
                    <i class="fas fa-sign-out-alt w-5"></i>
                    <span>Logout</span>
                </button>
            </form>
        </nav>
    </div>

    <!-- Main Content -->
    <div class="lg:ml-64">
        <!-- Top Bar -->
        <header class="bg-white shadow-sm border-b border-gray-200">
            <div class="flex justify-between items-center px-4 sm:px-6 py-4">
                <div class="min-w-0 flex-1">
                    <h1 class="text-xl sm:text-2xl font-bold text-gray-900 text-truncate-safe">Loan Application</h1>
                    <p class="text-gray-600 text-sm text-truncate-safe">Complete the form below to apply for a new loan</p>
                </div>
                
                <div class="flex items-center space-x-2 sm:space-x-4">
                    <!-- Notifications -->
                    <div class="relative">
                        <button class="p-2 text-gray-600 hover:text-blue-600 relative">
                            <i class="fas fa-bell text-lg sm:text-xl"></i>
                            <span class="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full notification-dot"></span>
                        </button>
                    </div>
                    
                    <!-- User Menu -->
                    <div class="relative">
                        <button class="flex items-center space-x-2 sm:space-x-3 p-2 rounded-lg hover:bg-gray-100">
                            <div class="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center overflow-hidden">
                                <?php if($hasProfilePicture): ?>
                                    <img src="<?php echo e($profilePictureUrl); ?>" alt="Profile" class="w-full h-full object-cover">
                                <?php else: ?>
                                    <i class="fas fa-user text-blue-600 text-sm"></i>
                                <?php endif; ?>
                            </div>
                            <span class="text-gray-700 font-medium hidden sm:block"><?php echo e($customer->customer); ?></span>
                            <i class="fas fa-chevron-down text-gray-400 hidden sm:block"></i>
                        </button>
                    </div>
                </div>
            </div>
        </header>

        <!-- Main Content Area -->
        <main class="p-4 sm:p-6">
            <!-- Step Indicator -->
            <div class="step-indicator mb-8">
                <div class="step active" data-step="1">
                    <span>1</span>
                    <div class="step-label">Application Details</div>
                </div>
                <div class="step" data-step="2">
                    <span>2</span>
                    <div class="step-label">Document Upload</div>
                </div>
            </div>

            <?php if($errors->any()): ?>
                <div class="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
                    <div class="flex items-start space-x-3">
                        <i class="fas fa-exclamation-triangle text-red-600 mt-1"></i>
                        <div>
                            <h4 class="font-semibold text-red-800">Please fix the following errors:</h4>
                            <ul class="text-red-700 text-sm mt-1 list-disc list-inside">
                                <?php $__currentLoopData = $errors->all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $error): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <li><?php echo e($error); ?></li>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </ul>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Multi-step Form -->
            <form id="loanApplicationForm" action="<?php echo e(route('customer.loan.application.submit')); ?>" method="POST" enctype="multipart/form-data" class="space-y-8">
                <?php echo csrf_field(); ?>
                
                <!-- Hidden field to store selected loan product -->
                <input type="hidden" id="selected_product_id" name="loan_product" value="<?php echo e(old('loan_product')); ?>">
                
                <!-- Page 1: Basic Information -->
                <div id="page1" class="form-page active">
                    <!-- Customer Info -->
                    <div class="flex items-center gap-4 mb-8 p-4 bg-gray-50 rounded-lg">
                        <div class="relative">
                            <img
                                src="<?php echo e($profilePictureUrl); ?>"
                                alt="Profile"
                                class="w-16 h-16 rounded-full object-cover border-4 border-gray-200 shadow-sm"
                            />
                        </div>
                        <div>
                            <p class="text-sm text-gray-500">Applicant</p>
                            <p class="text-gray-700 font-medium"><?php echo e($customer->full_name ?? $customer->customer); ?></p>
                            <p class="text-sm text-gray-600"><?php echo e($customer->email); ?> • <?php echo e($customer->phone); ?></p>
                            <p class="text-xs text-blue-600 font-medium mt-1">Customer No: <?php echo e($customer->customer_number ?? 'N/A'); ?></p>
                        </div>
                    </div>

                    <!-- Auto-filled Notice -->
                    <div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
                        <div class="flex items-start space-x-3">
                            <i class="fas fa-info-circle text-blue-600 mt-1"></i>
                            <div>
                                <h4 class="font-semibold text-blue-800">Auto-filled Information</h4>
                                <p class="text-blue-700 text-sm mt-1">
                                    Your personal information has been pre-filled from your profile. Please review and update any information that may have changed.
                                </p>
                            </div>
                        </div>
                    </div>

                    <!-- PART 1: Applicant Details Card -->
                    <div class="bg-white border border-gray-200 rounded-xl shadow-sm p-6 form-section">
                        <h3 class="text-xl font-semibold text-gray-800 mb-2">Applicant Details</h3>
                        <p class="text-gray-600 mb-6">Your personal information (pre-filled from your profile)</p>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <!-- Title -->
                            <div>
                                <label for="title" class="block text-sm font-medium text-gray-700 mb-1">Title</label>
                                <select id="title" name="title" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors prefilled-field" required readonly>
                                    <option value="">Select Title</option>
                                    <option value="Dr" <?php echo e(old('title', $customer->title) == 'Dr' ? 'selected' : ''); ?>>Dr</option>
                                    <option value="Prof" <?php echo e(old('title', $customer->title) == 'Prof' ? 'selected' : ''); ?>>Prof</option>
                                    <option value="Mr" <?php echo e(old('title', $customer->title) == 'Mr' ? 'selected' : ''); ?>>Mr</option>
                                    <option value="Mrs" <?php echo e(old('title', $customer->title) == 'Mrs' ? 'selected' : ''); ?>>Mrs</option>
                                    <option value="Miss" <?php echo e(old('title', $customer->title) == 'Miss' ? 'selected' : ''); ?>>Miss</option>
                                </select>
                                <p class="text-xs text-gray-500 mt-1">From your profile</p>
                            </div>

                            <!-- Surname -->
                            <div>
                                <label for="surname" class="block text-sm font-medium text-gray-700 mb-1">Surname</label>
                                <input type="text" id="surname" name="surname" value="<?php echo e(old('surname', $customer->surname)); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors prefilled-field" required readonly>
                                <p class="text-xs text-gray-500 mt-1">From your profile</p>
                            </div>

                            <!-- First Name -->
                            <div>
                                <label for="first_name" class="block text-sm font-medium text-gray-700 mb-1">First Name</label>
                                <input type="text" id="first_name" name="first_name" value="<?php echo e(old('first_name', $customer->first_name)); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors prefilled-field" required readonly>
                                <p class="text-xs text-gray-500 mt-1">From your profile</p>
                            </div>

                            <!-- Middle Name -->
                            <div>
                                <label for="middle_name" class="block text-sm font-medium text-gray-700 mb-1">Middle Name</label>
                                <input type="text" id="middle_name" name="middle_name" value="<?php echo e(old('middle_name', $customer->middle_name)); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors prefilled-field" readonly>
                                <p class="text-xs text-gray-500 mt-1">From your profile</p>
                            </div>

                            <!-- Date of Birth -->
                            <div>
                                <label for="date_of_birth" class="block text-sm font-medium text-gray-700 mb-1">Date of Birth</label>
                                <input type="date" id="date_of_birth" name="date_of_birth" value="<?php echo e(old('date_of_birth', $customer->dob ? $customer->dob->format('Y-m-d') : '')); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors prefilled-field" required readonly>
                                <p class="text-xs text-gray-500 mt-1">From your profile</p>
                            </div>

                            <!-- NRC Number -->
                            <div>
                                <label for="nrc_number" class="block text-sm font-medium text-gray-700 mb-1">NRC Number</label>
                                <input type="text" id="nrc_number" name="nrc_number" value="<?php echo e(old('nrc_number', $customer->number)); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors prefilled-field" required readonly>
                                <p class="text-xs text-gray-500 mt-1">From your profile</p>
                            </div>

                            <!-- Email -->
                            <div>
                                <label for="email" class="block text-sm font-medium text-gray-700 mb-1">Email</label>
                                <input type="email" id="email" name="email" value="<?php echo e(old('email', $customer->email)); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors prefilled-field" required readonly>
                                <p class="text-xs text-gray-500 mt-1">From your profile</p>
                            </div>

                            <!-- Mobile Number -->
                            <div>
                                <label for="mobile_number" class="block text-sm font-medium text-gray-700 mb-1">Mobile Number</label>
                                <input type="tel" id="mobile_number" name="mobile_number" value="<?php echo e(old('mobile_number', $customer->phone)); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors prefilled-field" required readonly>
                                <p class="text-xs text-gray-500 mt-1">From your profile</p>
                            </div>

                            <!-- Office Telephone -->
                            <div>
                                <label for="office_phone" class="block text-sm font-medium text-gray-700 mb-1">Office Telephone</label>
                                <input type="tel" id="office_phone" name="office_phone" value="<?php echo e(old('office_phone', $customer->office_phone)); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors prefilled-field" readonly>
                                <p class="text-xs text-gray-500 mt-1">From your profile</p>
                            </div>

                            <!-- Bank Branch -->
                            <div>
                                <label for="bank_branch" class="block text-sm font-medium text-gray-700 mb-1">Bank Branch *</label>
                                <input type="text" id="bank_branch" name="bank_branch" value="<?php echo e(old('bank_branch')); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required placeholder="Enter bank branch name">
                                <div class="error-message" id="bank_branch_error"></div>
                            </div>

                            <!-- Account Number -->
                            <div>
                                <label for="account_number" class="block text-sm font-medium text-gray-700 mb-1">Account Number *</label>
                                <input type="text" id="account_number" name="account_number" value="<?php echo e(old('account_number')); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required placeholder="Enter your account number">
                                <div class="error-message" id="account_number_error"></div>
                            </div>

                            <!-- Years in Employment -->
                            <div>
                                <label for="employment_years" class="block text-sm font-medium text-gray-700 mb-1">Years in Employment *</label>
                                <input type="number" id="employment_years" name="employment_years" value="<?php echo e(old('employment_years')); ?>" min="0" max="50"
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required placeholder="Enter years">
                                <div class="error-message" id="employment_years_error"></div>
                            </div>

                            <!-- Employee Number -->
                            <div>
                                <label for="employee_number" class="block text-sm font-medium text-gray-700 mb-1">Employee Number</label>
                                <input type="text" id="employee_number" name="employee_number" value="<?php echo e(old('employee_number')); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" placeholder="Enter employee number">
                            </div>

                            <!-- Year of Retirement -->
                            <div>
                                <label for="retirement_year" class="block text-sm font-medium text-gray-700 mb-1">Year of Retirement</label>
                                <input type="number" id="retirement_year" name="retirement_year" value="<?php echo e(old('retirement_year')); ?>" min="<?php echo e(date('Y')); ?>" max="<?php echo e(date('Y') + 50); ?>"
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" placeholder="Enter retirement year">
                            </div>

                            <!-- Physical Address -->
                            <div class="md:col-span-2">
                                <label for="physical_address" class="block text-sm font-medium text-gray-700 mb-1">Physical Address</label>
                                <textarea id="physical_address" name="physical_address" rows="2" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors prefilled-field" required readonly><?php echo e(old('physical_address', $customer->address)); ?></textarea>
                                <p class="text-xs text-gray-500 mt-1">From your profile</p>
                            </div>

                            <!-- Postal Address -->
                            <div class="md:col-span-2">
                                <label for="postal_address" class="block text-sm font-medium text-gray-700 mb-1">Postal Address *</label>
                                <textarea id="postal_address" name="postal_address" rows="2" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required placeholder="Enter your postal address"><?php echo e(old('postal_address', $customer->address)); ?></textarea>
                                <div class="error-message" id="postal_address_error"></div>
                            </div>

                            <!-- Town -->
                            <div>
                                <label for="town" class="block text-sm font-medium text-gray-700 mb-1">Town</label>
                                <input type="text" id="town" name="town" value="<?php echo e(old('town', $customer->town)); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors prefilled-field" required readonly>
                                <p class="text-xs text-gray-500 mt-1">From your profile</p>
                            </div>

                            <!-- Province -->
                            <div>
                                <label for="province" class="block text-sm font-medium text-gray-700 mb-1">Province</label>
                                <input type="text" id="province" name="province" value="<?php echo e(old('province', $customer->province)); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors prefilled-field" required readonly>
                                <p class="text-xs text-gray-500 mt-1">From your profile</p>
                            </div>
                        </div>
                    </div>

                    <!-- PART 2: Employment Details Card -->
                    <div class="bg-white border border-gray-200 rounded-xl shadow-sm p-6 form-section">
                        <h3 class="text-xl font-semibold text-gray-800 mb-2">Employment Details</h3>
                        <p class="text-gray-600 mb-6">Your current employment information</p>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <!-- Job Title -->
                            <div>
                                <label for="job_title" class="block text-sm font-medium text-gray-700 mb-1">Job Title *</label>
                                <input type="text" id="job_title" name="job_title" value="<?php echo e(old('job_title', $customer->occupation)); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required placeholder="Enter your job title">
                                <div class="error-message" id="job_title_error"></div>
                            </div>

                            <!-- Employer Name -->
                            <div>
                                <label for="employer_name" class="block text-sm font-medium text-gray-700 mb-1">Employer's Name *</label>
                                <input type="text" id="employer_name" name="employer_name" value="<?php echo e(old('employer_name', $customer->company)); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required placeholder="Enter employer's name">
                                <div class="error-message" id="employer_name_error"></div>
                            </div>

                            <!-- Gross Salary -->
                            <div>
                                <label for="gross_salary" class="block text-sm font-medium text-gray-700 mb-1">Gross Salary (ZMW) *</label>
                                <input type="number" id="gross_salary" name="gross_salary" value="<?php echo e(old('gross_salary', $customer->income)); ?>" step="0.01" min="0"
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required placeholder="Enter gross salary">
                                <div class="error-message" id="gross_salary_error"></div>
                            </div>

                            <!-- Net Salary -->
                            <div>
                                <label for="net_salary" class="block text-sm font-medium text-gray-700 mb-1">Net Salary (ZMW) *</label>
                                <input type="number" id="net_salary" name="net_salary" value="<?php echo e(old('net_salary')); ?>" step="0.01" min="0"
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required placeholder="Enter net salary">
                                <div class="error-message" id="net_salary_error"></div>
                            </div>

                            <!-- Employment Type -->
                            <div>
                                <label for="employment_type" class="block text-sm font-medium text-gray-700 mb-1">Employment Type *</label>
                                <select id="employment_type" name="employment_type" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required>
                                    <option value="">Select Employment Type</option>
                                    <option value="permanent" <?php echo e(old('employment_type') == 'permanent' ? 'selected' : ''); ?>>Permanent Employment</option>
                                    <option value="contract" <?php echo e(old('employment_type') == 'contract' ? 'selected' : ''); ?>>Contract Employment</option>
                                </select>
                                <div class="error-message" id="employment_type_error"></div>
                            </div>

                            <!-- Contract Expiry Date -->
                            <div id="contract_expiry_container" class="<?php echo e(old('employment_type') == 'contract' ? '' : 'hidden'); ?>">
                                <label for="contract_expiry_date" class="block text-sm font-medium text-gray-700 mb-1">Contract Expiry Date *</label>
                                <input type="date" id="contract_expiry_date" name="contract_expiry_date" value="<?php echo e(old('contract_expiry_date')); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" <?php echo e(old('employment_type') == 'contract' ? 'required' : ''); ?>>
                                <div class="error-message" id="contract_expiry_date_error"></div>
                            </div>

                            <!-- Employer Physical Address -->
                            <div class="md:col-span-2">
                                <label for="employer_physical_address" class="block text-sm font-medium text-gray-700 mb-1">Employer Physical Address *</label>
                                <textarea id="employer_physical_address" name="employer_physical_address" rows="2" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required placeholder="Enter employer's physical address"><?php echo e(old('employer_physical_address')); ?></textarea>
                                <div class="error-message" id="employer_physical_address_error"></div>
                            </div>

                            <!-- Employer Postal Address -->
                            <div class="md:col-span-2">
                                <label for="employer_postal_address" class="block text-sm font-medium text-gray-700 mb-1">Employer Postal Address *</label>
                                <textarea id="employer_postal_address" name="employer_postal_address" rows="2" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required placeholder="Enter employer's postal address"><?php echo e(old('employer_postal_address')); ?></textarea>
                                <div class="error-message" id="employer_postal_address_error"></div>
                            </div>

                            <!-- Employer Town/Province -->
                            <div class="md:col-span-2">
                                <label for="employer_town_province" class="block text-sm font-medium text-gray-700 mb-1">Employer Town/Province *</label>
                                <input type="text" id="employer_town_province" name="employer_town_province" value="<?php echo e(old('employer_town_province')); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required placeholder="Enter employer's town/province">
                                <div class="error-message" id="employer_town_province_error"></div>
                            </div>
                        </div>
                    </div>

                    <!-- PART 3: Loan Information Card -->
                    <div class="bg-white border border-gray-200 rounded-xl shadow-sm p-6 form-section">
                        <h3 class="text-xl font-semibold text-gray-800 mb-2">Loan Information</h3>
                        <p class="text-gray-600 mb-6">Details about the loan you're applying for</p>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <!-- Loan Product -->
                            <div class="md:col-span-2">
                                <label for="loan_product_select" class="block text-sm font-medium text-gray-700 mb-1">Loan Product *</label>
                                <select id="loan_product_select" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required>
                                    <option value="">Select Loan Product</option>
                                    <?php $__currentLoopData = $loanTypes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $loanType): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($loanType->id); ?>" 
                                                data-rate="<?php echo e($loanType->monthlyrate); ?>"
                                                data-requirements="<?php echo e($loanType->requirements_count); ?>"
                                                data-mandatory="<?php echo e($loanType->mandatory_requirements_count); ?>"
                                                <?php echo e(old('loan_product') == $loanType->id ? 'selected' : ''); ?>>
                                            <?php echo e($loanType->product); ?> - <?php echo e($loanType->details); ?> (<?php echo e($loanType->monthlyrate); ?>% monthly)
                                        </option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                                <div id="requirements-preview" class="mt-2 hidden">
                                    <p class="text-sm text-gray-600">
                                        <span id="total-reqs">0</span> document(s) required 
                                        (<span id="mandatory-reqs" class="text-red-600">0 mandatory</span>)
                                    </p>
                                </div>
                                <div class="error-message" id="loan_product_error"></div>
                            </div>

                            <!-- Loan Amount -->
                            <div>
                                <label for="loan_amount" class="block text-sm font-medium text-gray-700 mb-1">Loan Amount (ZMW) *</label>
                                <input type="number" id="loan_amount" name="loan_amount" value="<?php echo e(old('loan_amount')); ?>" step="0.01" min="100"
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required placeholder="Enter loan amount">
                                <div class="error-message" id="loan_amount_error"></div>
                            </div>

                            <!-- Loan Tenure -->
                            <div>
                                <label for="loan_tenure" class="block text-sm font-medium text-gray-700 mb-1">Loan Tenure (Months) *</label>
                                <input type="number" id="loan_tenure" name="loan_tenure" value="<?php echo e(old('loan_tenure')); ?>" min="1" max="120"
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required placeholder="Enter months">
                                <div class="error-message" id="loan_tenure_error"></div>
                            </div>

                            <!-- Interest Rate (Display Only) -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Interest Rate</label>
                                <input type="text" id="interest_rate_display" class="w-full border border-gray-300 rounded-lg px-3 py-2 bg-gray-100 text-gray-600" readonly placeholder="Select loan product">
                            </div>

                            <!-- Estimated Monthly Payment (Display Only) -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Estimated Monthly Payment</label>
                                <input type="text" id="estimated_payment_display" class="w-full border border-gray-300 rounded-lg px-3 py-2 bg-gray-100 text-gray-600" readonly placeholder="Calculate automatically">
                            </div>

                            <!-- Loan Purpose -->
                            <div class="md:col-span-2">
                                <label for="loan_purpose" class="block text-sm font-medium text-gray-700 mb-1">Purpose of Loan *</label>
                                <textarea id="loan_purpose" name="loan_purpose" rows="3" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required placeholder="Describe the purpose of your loan"><?php echo e(old('loan_purpose')); ?></textarea>
                                <div class="error-message" id="loan_purpose_error"></div>
                            </div>
                        </div>
                    </div>

                    <!-- PART 4: Next of Kin Information Card -->
                    <div class="bg-white border border-gray-200 rounded-xl shadow-sm p-6 form-section">
                        <h3 class="text-xl font-semibold text-gray-800 mb-2">Next of Kin Information</h3>
                        <p class="text-gray-600 mb-6">Your emergency contact person</p>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <!-- Kin Surname -->
                            <div>
                                <label for="kin_surname" class="block text-sm font-medium text-gray-700 mb-1">Surname *</label>
                                <input type="text" id="kin_surname" name="kin_surname" value="<?php echo e(old('kin_surname')); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required placeholder="Enter next of kin surname">
                                <div class="error-message" id="kin_surname_error"></div>
                            </div>

                            <!-- Kin First Name -->
                            <div>
                                <label for="kin_first_name" class="block text-sm font-medium text-gray-700 mb-1">First Name *</label>
                                <input type="text" id="kin_first_name" name="kin_first_name" value="<?php echo e(old('kin_first_name')); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required placeholder="Enter next of kin first name">
                                <div class="error-message" id="kin_first_name_error"></div>
                            </div>

                            <!-- Kin Telephone -->
                            <div>
                                <label for="kin_telephone" class="block text-sm font-medium text-gray-700 mb-1">Telephone *</label>
                                <input type="tel" id="kin_telephone" name="kin_telephone" value="<?php echo e(old('kin_telephone')); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required placeholder="Enter next of kin telephone">
                                <div class="error-message" id="kin_telephone_error"></div>
                            </div>

                            <!-- Kin Email -->
                            <div>
                                <label for="kin_email" class="block text-sm font-medium text-gray-700 mb-1">Email</label>
                                <input type="email" id="kin_email" name="kin_email" value="<?php echo e(old('kin_email')); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" placeholder="Enter next of kin email">
                            </div>

                            <!-- Kin Town -->
                            <div>
                                <label for="kin_town" class="block text-sm font-medium text-gray-700 mb-1">Town *</label>
                                <input type="text" id="kin_town" name="kin_town" value="<?php echo e(old('kin_town')); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required placeholder="Enter next of kin town">
                                <div class="error-message" id="kin_town_error"></div>
                            </div>

                            <!-- Kin Province -->
                            <div>
                                <label for="kin_province" class="block text-sm font-medium text-gray-700 mb-1">Province *</label>
                                <input type="text" id="kin_province" name="kin_province" value="<?php echo e(old('kin_province')); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required placeholder="Enter next of kin province">
                                <div class="error-message" id="kin_province_error"></div>
                            </div>

                            <!-- Kin Country -->
                            <div>
                                <label for="kin_country" class="block text-sm font-medium text-gray-700 mb-1">Country *</label>
                                <input type="text" id="kin_country" name="kin_country" value="<?php echo e(old('kin_country', 'Zambia')); ?>" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required>
                            </div>

                            <!-- Kin Physical Address -->
                            <div class="md:col-span-2">
                                <label for="kin_physical_address" class="block text-sm font-medium text-gray-700 mb-1">Physical Address *</label>
                                <textarea id="kin_physical_address" name="kin_physical_address" rows="2" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required placeholder="Enter next of kin physical address"><?php echo e(old('kin_physical_address')); ?></textarea>
                                <div class="error-message" id="kin_physical_address_error"></div>
                            </div>

                            <!-- Kin Postal Address -->
                            <div class="md:col-span-2">
                                <label for="kin_postal_address" class="block text-sm font-medium text-gray-700 mb-1">Postal Address *</label>
                                <textarea id="kin_postal_address" name="kin_postal_address" rows="2" 
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-colors" required placeholder="Enter next of kin postal address"><?php echo e(old('kin_postal_address')); ?></textarea>
                                <div class="error-message" id="kin_postal_address_error"></div>
                            </div>
                        </div>
                    </div>

                    <!-- Navigation for Page 1 -->
                    <div class="flex flex-col md:flex-row justify-between space-y-3 md:space-y-0 md:space-x-4 pt-6">
                        <a href="<?php echo e(route('customer.dashboard')); ?>" class="bg-gray-100 text-gray-700 px-6 py-3 rounded-lg hover:bg-gray-200 transition-colors text-center">
                            <i class="fas fa-arrow-left mr-2"></i>Back to Dashboard
                        </a>
                        <div class="flex space-x-4">
                            <button type="button" id="resetForm" class="bg-gray-100 text-gray-700 px-6 py-3 rounded-lg hover:bg-gray-200 transition-colors">
                                <i class="fas fa-redo mr-2"></i>Reset Form
                            </button>
                            <button type="button" id="nextBtn" class="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition-colors">
                                Next: Document Upload <i class="fas fa-arrow-right ml-2"></i>
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Page 2: Document Upload -->
                <div id="page2" class="form-page">
                    <div class="bg-white border border-gray-200 rounded-xl shadow-sm p-6 mb-6">
                        <h3 class="text-xl font-semibold text-gray-800 mb-2">Document Requirements</h3>
                        <p class="text-gray-600 mb-6">Please upload the required documents for your loan application</p>
                        
                        <!-- Selected Loan Product Info -->
                        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
                            <div class="flex items-center space-x-3">
                                <i class="fas fa-info-circle text-blue-600"></i>
                                <div>
                                    <h4 class="font-semibold text-blue-800">Selected Loan Product</h4>
                                    <p class="text-blue-700 text-sm mt-1" id="selected-product-info">No product selected</p>
                                </div>
                            </div>
                        </div>

                        <!-- Requirements Progress -->
                        <div class="mb-6">
                            <div class="flex items-center justify-between mb-2">
                                <span class="text-sm font-medium text-gray-700">Upload Progress</span>
                                <span class="text-sm font-medium text-gray-700" id="progress-text">0/0</span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2">
                                <div id="progress-bar" class="bg-blue-600 h-2 rounded-full transition-all duration-300" style="width: 0%"></div>
                            </div>
                        </div>

                        <!-- Requirements Checklist -->
                        <div id="requirements-list" class="space-y-3 mb-8" style="display:none;">
                            <div class="text-center py-8">
                                <i class="fas fa-folder-open text-gray-300 text-4xl mb-3"></i>
                                <p class="text-gray-500">Select a loan product to view requirements</p>
                            </div>
                        </div>

                        <!-- Document Upload Area -->
                        <div id="document-upload-area" class="space-y-6">
                            <!-- Document fields will be generated dynamically -->
                        </div>

                        <!-- Navigation for Page 2 -->
                        <div class="flex justify-between items-center pt-8 border-t border-gray-200">
                            <button type="button" id="prevBtn" class="bg-gray-100 text-gray-700 px-6 py-3 rounded-lg hover:bg-gray-200 transition-colors">
                                <i class="fas fa-arrow-left mr-2"></i>Back to Application
                            </button>
                            <div class="flex space-x-4">
                                <button type="submit" id="submitBtn" class="bg-green-600 text-white px-6 py-3 rounded-lg hover:bg-green-700 transition-colors flex items-center justify-center min-w-40">
                                    <span id="submitText">Submit Application</span>
                                    <i id="submitSpinner" class="fas fa-spinner fa-spin ml-2 hidden"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </main>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Mobile menu toggle
            const mobileMenuButton = document.getElementById('mobile-menu-button');
            const sidebar = document.getElementById('sidebar');
            
            if (mobileMenuButton && sidebar) {
                mobileMenuButton.addEventListener('click', function() {
                    sidebar.classList.toggle('active');
                });
            }

            // Multi-step form navigation
            const page1 = document.getElementById('page1');
            const page2 = document.getElementById('page2');
            const nextBtn = document.getElementById('nextBtn');
            const prevBtn = document.getElementById('prevBtn');
            const step1 = document.querySelector('[data-step="1"]');
            const step2 = document.querySelector('[data-step="2"]');
            const loanProductSelect = document.getElementById('loan_product_select');
            const hiddenProductId = document.getElementById('selected_product_id');
            const requirementsPreview = document.getElementById('requirements-preview');
            const totalReqsSpan = document.getElementById('total-reqs');
            const mandatoryReqsSpan = document.getElementById('mandatory-reqs');
            const documentUploadArea = document.getElementById('document-upload-area');
            const requirementsList = document.getElementById('requirements-list');
            const progressBar = document.getElementById('progress-bar');
            const progressText = document.getElementById('progress-text');
            const selectedProductInfo = document.getElementById('selected-product-info');

            let selectedProductId = null;
            let selectedProductName = '';
            let requirements = [];
            let uploadedFiles = {};

            // Initialize step indicators
            function updateStepIndicator(currentStep) {
                const steps = document.querySelectorAll('.step');
                steps.forEach(step => {
                    step.classList.remove('active', 'completed');
                });

                if (currentStep === 1) {
                    step1.classList.add('active');
                } else {
                    step1.classList.add('completed');
                    step2.classList.add('active');
                }
            }

            // Clear error messages
            function clearErrors() {
                document.querySelectorAll('.error-message').forEach(el => {
                    el.textContent = '';
                });
                document.querySelectorAll('.border-red-500').forEach(el => {
                    el.classList.remove('border-red-500');
                });
            }

            // Show error for a specific field
            function showError(fieldId, message) {
                const field = document.getElementById(fieldId);
                const errorElement = document.getElementById(fieldId + '_error');
                if (field && errorElement) {
                    field.classList.add('border-red-500');
                    errorElement.textContent = message;
                }
            }

            // Validate page 1
            function validatePage1() {
                clearErrors();
                let isValid = true;

                // Required fields validation
                const requiredFields = [
                    'bank_branch', 'account_number', 'employment_years', 'postal_address',
                    'job_title', 'employer_name', 'gross_salary', 'net_salary',
                    'employment_type', 'employer_physical_address', 'employer_postal_address',
                    'employer_town_province', 'loan_amount', 'loan_tenure', 'loan_purpose',
                    'kin_surname', 'kin_first_name', 'kin_telephone', 'kin_town',
                    'kin_province', 'kin_country', 'kin_physical_address', 'kin_postal_address'
                ];

                requiredFields.forEach(fieldId => {
                    const field = document.getElementById(fieldId);
                    if (field && !field.value.trim()) {
                        isValid = false;
                        showError(fieldId, 'This field is required');
                    }
                });

                // Special validation for loan product
                if (!loanProductSelect.value) {
                    isValid = false;
                    showError('loan_product', 'Please select a loan product');
                    loanProductSelect.classList.add('border-red-500');
                }

                // Validate contract expiry date if employment type is contract
                const employmentType = document.getElementById('employment_type');
                if (employmentType && employmentType.value === 'contract') {
                    const contractExpiry = document.getElementById('contract_expiry_date');
                    if (contractExpiry && !contractExpiry.value) {
                        isValid = false;
                        showError('contract_expiry_date', 'Contract expiry date is required for contract employment');
                    }
                }

                return isValid;
            }

            // Next button click handler
            if (nextBtn) {
                nextBtn.addEventListener('click', function() {
                    // Validate page 1 before proceeding
                    if (validatePage1()) {
                        // Store selected product ID and name
                        selectedProductId = loanProductSelect.value;
                        const selectedOption = loanProductSelect.options[loanProductSelect.selectedIndex];
                        selectedProductName = selectedOption.textContent;
                        hiddenProductId.value = selectedProductId;
                        
                        // Update selected product info
                        selectedProductInfo.textContent = selectedProductName;
                        
                        // Load requirements via AJAX
                        if (selectedProductId) {
                            loadRequirements(selectedProductId);
                        }
                        
                        // Switch to page 2
                        page1.classList.remove('active');
                        page2.classList.add('active');
                        updateStepIndicator(2);
                    } else {
                        // Scroll to first error
                        const firstError = document.querySelector('.border-red-500');
                        if (firstError) {
                            firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        }
                    }
                });
            }

            // Previous button click handler
            if (prevBtn) {
                prevBtn.addEventListener('click', function() {
                    page2.classList.remove('active');
                    page1.classList.add('active');
                    updateStepIndicator(1);
                });
            }

            // Load requirements via AJAX
           // Load requirements via AJAX (simplified)
function loadRequirements(productId) {
    if (!productId) return;

    // Clear existing content
    documentUploadArea.innerHTML = `
        <div class="text-center py-8">
            <i class="fas fa-spinner fa-spin text-blue-600 text-2xl mb-3"></i>
            <p class="text-gray-600">Loading document requirements...</p>
        </div>
    `;

    const url = `/financeportal/public/customer/get-requirements/${productId}`;
    
    fetch(url, {
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || ''
        }
    })
    .then(response => {
        if (!response.ok) throw new Error('Failed to load requirements');
        return response.json();
    })
    .then(data => {
        if (data.success) {
            requirements = data.requirements || [];
            renderUploadFields();
            updateProgress();
        } else {
            throw new Error(data.message || 'Failed to load requirements');
        }
    })
    .catch(error => {
        console.error('Error loading requirements:', error);
        documentUploadArea.innerHTML = `
            <div class="bg-red-50 border border-red-200 rounded-lg p-4">
                <div class="flex items-center space-x-3">
                    <i class="fas fa-exclamation-triangle text-red-600"></i>
                    <div>
                        <p class="text-red-700">Failed to load document requirements. Please try again.</p>
                    </div>
                </div>
            </div>
        `;
    });
}

            // Render requirements checklist
            function renderRequirements() {
                if (requirements.length === 0) {
                    requirementsList.innerHTML = `
                        <div class="text-center py-8">
                            <i class="fas fa-check-circle text-green-500 text-4xl mb-3"></i>
                            <p class="text-gray-600">No additional documents required for this loan product.</p>
                        </div>
                    `;
                    return;
                }

                let html = '<h4 class="text-lg font-semibold text-gray-800 mb-4">Required Documents</h4>';
                requirements.forEach(req => {
                    const isMandatory = req.is_mandatory;
                    html += `
                        <div class="requirement-item ${isMandatory ? 'mandatory' : 'optional'}" data-id="${req.id}">
                            <div class="flex items-center justify-between w-full">
                                <div class="flex items-center">
                                    <div class="w-8 h-8 rounded-full flex items-center justify-center mr-3 ${isMandatory ? 'bg-red-100 text-red-600' : 'bg-blue-100 text-blue-600'}">
                                        <i class="fas ${getFileTypeIcon(req.field_type)}"></i>
                                    </div>
                                    <div>
                                        <h4 class="font-medium text-gray-800">${req.name}</h4>
                                        <p class="text-sm text-gray-600">${req.description || ''}</p>
                                        <p class="text-xs ${isMandatory ? 'text-red-600' : 'text-blue-600'} mt-1">
                                            ${isMandatory ? 'Mandatory' : 'Optional'}
                                            ${req.file_types ? ` • Accepts: ${req.file_types}` : ''}
                                            ${req.max_file_size ? ` • Max: ${formatFileSize(req.max_file_size)}` : ''}
                                        </p>
                                    </div>
                                </div>
                                <div class="requirement-status">
                                    <i class="fas fa-check-circle text-green-500 hidden"></i>
                                </div>
                            </div>
                        </div>
                    `;
                });
                requirementsList.innerHTML = html;
            }

// Render simplified upload fields
function renderUploadFields() {
    if (requirements.length === 0) {
        documentUploadArea.innerHTML = `
            <div class="text-center py-8 border border-gray-300 rounded-lg bg-gray-50">
                <i class="fas fa-check-circle text-green-500 text-3xl mb-3"></i>
                <p class="text-gray-600 font-medium">No documents required for this loan.</p>
            </div>
        `;
        return;
    }

    let html = '';
    requirements.forEach(req => {
        const isMandatory = req.is_mandatory;
        const fieldName = `requirement_${req.id}`;
        const acceptAttr = req.file_types ? `accept=".${req.file_types.replace(/,/g, ',.')}"` : '';
        const fileId = `file-${req.id}`;
        
        html += `
            <div class="document-field bg-white border border-gray-200 rounded-lg p-4" data-id="${req.id}">
                <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
                    <!-- Document Name -->
                    <div class="md:w-1/3">
                        <div class="flex items-center">
                            <div class="w-8 h-8 rounded-full ${isMandatory ? 'bg-red-100' : 'bg-blue-100'} flex items-center justify-center mr-3">
                                <i class="fas ${getFileTypeIcon(req.field_type || 'file')} ${isMandatory ? 'text-red-600' : 'text-blue-600'}"></i>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700">
                                    ${req.name}
                                    ${isMandatory ? '<span class="text-red-600 ml-1">*</span>' : ''}
                                </label>
                                <div class="flex items-center mt-1">
                                    <span class="text-xs ${isMandatory ? 'text-red-600' : 'text-blue-600'}">
                                        ${isMandatory ? 'Required' : 'Optional'}
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- File Input Field -->
                    <div class="md:w-2/3">
                        <div class="flex flex-col sm:flex-row gap-3">
                            <!-- File input with button -->
                            <div class="flex-1">
                                <div class="relative">
                                    <input type="text" 
                                        id="filename-display-${req.id}" 
                                        class="w-full border border-gray-300 rounded-lg px-3 py-2 bg-gray-50 text-gray-500 cursor-not-allowed" 
                                        readonly 
                                        placeholder="No file selected">
                                    <input type="file" 
                                        name="${fieldName}" 
                                        id="${fileId}" 
                                        class="hidden" 
                                        ${isMandatory ? 'required' : ''}
                                        ${acceptAttr}
                                        ${req.max_file_size ? `data-max-size="${req.max_file_size}"` : ''}>
                                </div>
                                <div class="text-xs text-gray-500 mt-2">
                                    ${req.file_types ? `Accepted formats: ${req.file_types}` : 'All file types accepted'}
                                    ${req.max_file_size ? ` • Max: ${formatFileSize(req.max_file_size)}` : ''}
                                </div>
                            </div>
                            
                            <!-- Browse Button -->
                            <div class="sm:w-auto">
                                <button type="button" 
                                    onclick="document.getElementById('${fileId}').click()"
                                    class="w-full sm:w-auto px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium text-sm flex items-center justify-center">
                                    <i class="fas fa-folder-open mr-2"></i>Browse
                                </button>
                            </div>
                        </div>
                        
                        <!-- File Preview (simple version) -->
                        <div id="preview-${req.id}" class="preview-container mt-3 hidden">
                            <div class="flex items-center justify-between bg-blue-50 border border-blue-200 rounded-lg p-3">
                                <div class="flex items-center">
                                    <i class="fas fa-file text-blue-600 mr-3"></i>
                                    <div>
                                        <div id="preview-name-${req.id}" class="text-sm font-medium text-gray-800"></div>
                                        <div id="preview-size-${req.id}" class="text-xs text-gray-600"></div>
                                    </div>
                                </div>
                                <button type="button" 
                                    onclick="removeFile(${req.id})"
                                    class="text-red-600 hover:text-red-800 text-sm font-medium">
                                    <i class="fas fa-times mr-1"></i>Remove
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    });
    documentUploadArea.innerHTML = html;

    // Initialize file upload handlers
    initializeFileUploads();
}

// Initialize file uploads for simplified layout
function initializeFileUploads() {
    requirements.forEach(req => {
        const fileInput = document.getElementById(`file-${req.id}`);
        
        if (fileInput) {
            fileInput.addEventListener('change', handleFileSelect);
            
            function handleFileSelect() {
                if (this.files.length > 0) {
                    const file = this.files[0];
                    
                    // Validate file type
                    if (req.file_types) {
                        const allowedTypes = req.file_types.split(',').map(t => t.trim().toLowerCase());
                        const fileExt = file.name.split('.').pop().toLowerCase();
                        if (!allowedTypes.includes(fileExt)) {
                            alert(`Invalid file type for ${req.name}. Allowed: ${req.file_types}`);
                            this.value = '';
                            return;
                        }
                    }

                    // Validate file size
                    if (req.max_file_size) {
                        const maxSizeBytes = req.max_file_size * 1024;
                        
                        if (file.size > maxSizeBytes) {
                            alert(`File too large for ${req.name}.\nYour file: ${formatFileSize(file.size)}\nMaximum allowed: ${formatFileSize(maxSizeBytes)}`);
                            this.value = '';
                            return;
                        }
                    }

                    // Store file
                    uploadedFiles[req.id] = file;
                    
                    // Show filename in input field
                    const filenameDisplay = document.getElementById(`filename-display-${req.id}`);
                    if (filenameDisplay) {
                        filenameDisplay.value = file.name;
                        filenameDisplay.classList.remove('text-gray-500');
                        filenameDisplay.classList.add('text-gray-800');
                    }
                    
                    // Show preview
                    showPreview(file, req.id);
                    
                    // Update requirement status
                    updateRequirementStatus(req.id, true);
                    updateProgress();
                }
            }
        }
    });
}

// Show preview in simplified layout
function showPreview(file, reqId) {
    const previewContainer = document.getElementById(`preview-${reqId}`);
    const previewName = document.getElementById(`preview-name-${reqId}`);
    const previewSize = document.getElementById(`preview-size-${reqId}`);
    
    if (previewContainer && previewName && previewSize) {
        previewName.textContent = file.name;
        previewSize.textContent = formatFileSize(file.size);
        previewContainer.classList.remove('hidden');
    }
}

// Remove file in simplified layout
window.removeFile = function(reqId) {
    const fileInput = document.getElementById(`file-${reqId}`);
    const filenameDisplay = document.getElementById(`filename-display-${reqId}`);
    const previewContainer = document.getElementById(`preview-${reqId}`);
    
    // Clear file input
    if (fileInput) {
        fileInput.value = '';
    }
    
    // Clear filename display
    if (filenameDisplay) {
        filenameDisplay.value = 'No file selected';
        filenameDisplay.classList.remove('text-gray-800');
        filenameDisplay.classList.add('text-gray-500');
    }
    
    // Hide preview
    if (previewContainer) {
        previewContainer.classList.add('hidden');
    }
    
    // Remove from uploaded files
    delete uploadedFiles[reqId];
    
    // Update requirement status
    updateRequirementStatus(reqId, false);
    updateProgress();
};

           // Update requirement status (simplified)
function updateRequirementStatus(reqId, completed) {
    // You can add visual feedback to the document card if needed
    const documentField = document.querySelector(`.document-field[data-id="${reqId}"]`);
    if (documentField) {
        if (completed) {
            documentField.classList.add('border-green-500');
            documentField.classList.remove('border-gray-200');
        } else {
            documentField.classList.remove('border-green-500');
            documentField.classList.add('border-gray-200');
        }
    }
}

            // Update progress
            function updateProgress() {
                const total = requirements.length;
                const completed = Object.keys(uploadedFiles).length;
                const percentage = total > 0 ? (completed / total) * 100 : 100;
                
                if (progressBar) {
                    progressBar.style.width = `${percentage}%`;
                }
                
                if (progressText) {
                    progressText.textContent = `${completed}/${total}`;
                }
            }

            // Helper functions
            function getFileTypeIcon(fileType) {
                const icons = {
                    'pdf': 'fa-file-pdf',
                    'doc': 'fa-file-word',
                    'docx': 'fa-file-word',
                    'jpg': 'fa-file-image',
                    'jpeg': 'fa-file-image',
                    'png': 'fa-file-image',
                    'txt': 'fa-file-alt',
                    'xls': 'fa-file-excel',
                    'xlsx': 'fa-file-excel',
                    'csv': 'fa-file-csv'
                };
                return icons[fileType] || 'fa-file';
            }

            function getFileType(filename) {
                return filename.split('.').pop().toLowerCase();
            }

      function formatFileSize(bytes) {
    console.log('formatFileSize input:', bytes); // DEBUG
    
    if (bytes === 0) return '0 Bytes';
    if (!bytes) return 'N/A';
    
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    
    // If bytes is less than 1KB, show in bytes
    if (bytes < k) {
        return bytes + ' Bytes';
    }
    
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    const result = parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    console.log('formatFileSize result:', result); // DEBUG
    return result;
}
            // Loan product change handler
            if (loanProductSelect) {
                loanProductSelect.addEventListener('change', function() {
                    const selectedOption = this.options[this.selectedIndex];
                    const totalReqs = selectedOption.getAttribute('data-requirements') || 0;
                    const mandatoryReqs = selectedOption.getAttribute('data-mandatory') || 0;

                    if (totalReqs > 0) {
                        requirementsPreview.classList.remove('hidden');
                        totalReqsSpan.textContent = totalReqs;
                        mandatoryReqsSpan.textContent = `${mandatoryReqs} mandatory`;
                    } else {
                        requirementsPreview.classList.add('hidden');
                    }

                    // Update hidden field
                    hiddenProductId.value = this.value;
                });
            }

            // Form submission handler
        // Form submission handler
const form = document.getElementById('loanApplicationForm');
if (form) {
    form.addEventListener('submit', async function(e) {
        e.preventDefault(); // Prevent normal form submission
        
        // Validate mandatory files are uploaded
        let isValid = true;
        const missingMandatory = [];

        requirements.forEach(req => {
            if (req.is_mandatory && !uploadedFiles[req.id]) {
                isValid = false;
                missingMandatory.push(req.name);
                
                // Highlight missing requirement
                const requirementItem = document.querySelector(`.requirement-item[data-id="${req.id}"]`);
                if (requirementItem) {
                    requirementItem.classList.add('border-red-500');
                    requirementItem.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }
            }
        });

        if (!isValid) {
            alert(`Please upload the following mandatory documents:\n\n${missingMandatory.join('\n')}`);
            return false;
        }

        // Show loading state
        const submitBtn = document.getElementById('submitBtn');
        const submitText = document.getElementById('submitText');
        const submitSpinner = document.getElementById('submitSpinner');
        
        if (submitBtn && submitText && submitSpinner) {
            submitText.textContent = 'Submitting...';
            submitSpinner.classList.remove('hidden');
            submitBtn.disabled = true;
        }

        try {
            // Submit form via AJAX
            const formData = new FormData(this);
            
            const response = await fetch(this.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || ''
                }
            });
            
            const data = await response.json();
            
            if (data.success) {
                // Simple success alert
                alert('✓ Application submitted successfully!\n\nRedirecting to My Applications...');
                
                // Redirect after 1.5 seconds
                setTimeout(() => {
                    if (data.redirect_url) {
                        window.location.href = data.redirect_url;
                    } else {
                        window.location.href = '/financeportal/public/customer/applications';
                    }
                }, 1500);
            } else {
                alert('✗ Error: ' + (data.message || 'Submission failed'));
                resetSubmitButton();
            }
            
        } catch (error) {
            console.error('Submission error:', error);
            alert('✗ An error occurred. Please try again.');
            resetSubmitButton();
        }
        
        function resetSubmitButton() {
            if (submitBtn && submitText && submitSpinner) {
                submitText.textContent = 'Submit Application';
                submitSpinner.classList.add('hidden');
                submitBtn.disabled = false;
            }
        }
    });
}

            // Reset form
            const resetBtn = document.getElementById('resetForm');
            if (resetBtn) {
                resetBtn.addEventListener('click', function() {
                    if (confirm('Are you sure you want to reset the form? All entered data will be lost.')) {
                        form.reset();
                        uploadedFiles = {};
                        requirementsList.innerHTML = '';
                        documentUploadArea.innerHTML = '';
                        progressBar.style.width = '0%';
                        progressText.textContent = '0/0';
                        page2.classList.remove('active');
                        page1.classList.add('active');
                        updateStepIndicator(1);
                        clearErrors();
                        
                        // Reset loan product preview
                        requirementsPreview.classList.add('hidden');
                    }
                });
            }

            // Initialize loan calculation
            function calculateMonthlyPayment() {
                const selectedOption = loanProductSelect.options[loanProductSelect.selectedIndex];
                const interestRate = parseFloat(selectedOption.getAttribute('data-rate')) || 0;
                const amount = parseFloat(document.getElementById('loan_amount').value) || 0;
                const tenure = parseInt(document.getElementById('loan_tenure').value) || 0;

                if (interestRate > 0 && amount > 0 && tenure > 0) {
                    const monthlyRate = interestRate / 100;
                    const monthlyPayment = (amount * monthlyRate * Math.pow(1 + monthlyRate, tenure)) / 
                                         (Math.pow(1 + monthlyRate, tenure) - 1);
                    
                    const interestRateDisplay = document.getElementById('interest_rate_display');
                    const estimatedPaymentDisplay = document.getElementById('estimated_payment_display');
                    
                    if (interestRateDisplay) {
                        interestRateDisplay.value = interestRate + '% monthly';
                    }
                    
                    if (estimatedPaymentDisplay) {
                        estimatedPaymentDisplay.value = 'ZMW ' + monthlyPayment.toFixed(2);
                    }
                }
            }

            // Add event listeners for loan calculation
            if (loanProductSelect) {
                loanProductSelect.addEventListener('change', calculateMonthlyPayment);
            }
            
            const loanAmount = document.getElementById('loan_amount');
            const loanTenure = document.getElementById('loan_tenure');
            
            if (loanAmount) loanAmount.addEventListener('input', calculateMonthlyPayment);
            if (loanTenure) loanTenure.addEventListener('input', calculateMonthlyPayment);

            // Employment type toggle
            const employmentType = document.getElementById('employment_type');
            const contractExpiryContainer = document.getElementById('contract_expiry_container');
            const contractExpiryDate = document.getElementById('contract_expiry_date');

            if (employmentType && contractExpiryContainer) {
                employmentType.addEventListener('change', function() {
                    if (this.value === 'contract') {
                        contractExpiryContainer.classList.remove('hidden');
                        if (contractExpiryDate) {
                            contractExpiryDate.setAttribute('required', 'required');
                        }
                    } else {
                        contractExpiryContainer.classList.add('hidden');
                        if (contractExpiryDate) {
                            contractExpiryDate.removeAttribute('required');
                        }
                    }
                });

                // Initialize on page load
                if (employmentType.value === 'contract') {
                    contractExpiryContainer.classList.remove('hidden');
                }
            }

            // Initialize on page load
            updateStepIndicator(1);
            
            // Initialize loan calculation if values exist
            if (loanProductSelect.value) {
                calculateMonthlyPayment();
                const selectedOption = loanProductSelect.options[loanProductSelect.selectedIndex];
                const totalReqs = selectedOption.getAttribute('data-requirements') || 0;
                const mandatoryReqs = selectedOption.getAttribute('data-mandatory') || 0;
                
                if (totalReqs > 0) {
                    requirementsPreview.classList.remove('hidden');
                    totalReqsSpan.textContent = totalReqs;
                    mandatoryReqsSpan.textContent = `${mandatoryReqs} mandatory`;
                }
            }
        });
    </script>
</body>
</html><?php /**PATH /home/topacvbu/public_html/zedbankos.cloud/customer-portal/resources/views/customer/loan-application.blade.php ENDPATH**/ ?>