<?php
require_once 'config/config.php';
require_once 'config/vehicle-data.php';
$pageTitle   = 'Logbook Loans in Kenya';
$seoTitle    = 'Logbook Loans in Kenya 2026 — Fast Approval, Competitive Rates | Fantom Capital';
$seoDesc     = 'Get a logbook loan in Kenya within 24 hours. Borrow up to 60% of your vehicle value with Fantom Capital. No salary slip required. Apply online now — Nairobi & nationwide.';
$seoKeywords = 'logbook loans Kenya, logbook loan Nairobi, car logbook loan Kenya, vehicle logbook loan, fast logbook loan Kenya, logbook loan 2026, apply logbook loan Kenya';

// Get logged-in user data for pre-filling form
$loggedInUser = null;
$profileComplete = false;
if (isset($_SESSION['user_id'])) {
    $userStmt = $db->prepare("SELECT * FROM users WHERE id = ?");
    $userStmt->execute([$_SESSION['user_id']]);
    $loggedInUser = $userStmt->fetch();
    $profileComplete = $loggedInUser['profile_completed'] ?? false;
}

include 'includes/header.php';
?>

<!-- Main Content Section -->
<section class="py-16 bg-white">
    <div class="container mx-auto px-4">
        <div class="max-w-7xl mx-auto">
            <div class="grid md:grid-cols-2 gap-12 items-center">
                <!-- Left Column: Content -->
                <div class="space-y-8">
                    <div>
                        <h1 class="text-4xl md:text-5xl font-bold text-gray-900 mb-4">
                            🚗 Apply for Logbook Loans the Smart Way!
                        </h1>
                        <p class="text-lg text-gray-600 leading-relaxed">
                            Need quick cash without the hassle? Get a fast and affordable logbook loan with us today! 
                            We offer the best turnaround time and truly care about helping you move forward.
                        </p>
                    </div>
                    
                    <!-- Features -->
                    <div class="space-y-4">
                        <h2 class="text-2xl font-bold text-primary-blue mb-4">📊 Why Choose Us?</h2>
                        
                        <div class="grid grid-cols-1 gap-3">
                            <div class="flex items-start gap-3 bg-gray-50 p-4 rounded-lg">
                                <span class="text-2xl">✅</span>
                                <div>
                                    <h3 class="font-bold text-gray-900 text-sm mb-1">We Charge Less — Others Charge More!</h3>
                                    <p class="text-gray-600 text-xs">Get the most competitive rates in the market.</p>
                                </div>
                            </div>
                            
                            <div class="flex items-start gap-3 bg-gray-50 p-4 rounded-lg">
                                <span class="text-2xl">💰</span>
                                <div>
                                    <h3 class="font-bold text-gray-900 text-sm mb-1">Loans from KES 50,000 up to 1.5 Million</h3>
                                    <p class="text-gray-600 text-xs">Flexible loan amounts to meet your needs.</p>
                                </div>
                            </div>
                            
                            <div class="flex items-start gap-3 bg-gray-50 p-4 rounded-lg">
                                <span class="text-2xl">📈</span>
                                <div>
                                    <h3 class="font-bold text-gray-900 text-sm mb-1">Access up to 70% of your car's value</h3>
                                    <p class="text-gray-600 text-xs">Maximize the value of your vehicle.</p>
                                </div>
                            </div>
                            
                            <div class="flex items-start gap-3 bg-gray-50 p-4 rounded-lg">
                                <span class="text-2xl">⚡</span>
                                <div>
                                    <h3 class="font-bold text-gray-900 text-sm mb-1">Same-day approval — Drive and thrive!</h3>
                                    <p class="text-gray-600 text-xs">Quick processing with no hidden charges.</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Requirements -->
                    <div class="bg-gray-50 rounded-xl p-6">
                        <h3 class="text-xl font-bold text-gray-900 mb-4">📋 What You'll Need to Apply</h3>
                        <ul class="space-y-2">
                            <li class="flex items-start gap-2">
                                <svg class="w-5 h-5 text-primary-green mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                                </svg>
                                <span class="text-gray-700 text-sm">National ID & PIN copies (bring original ID for verification)</span>
                            </li>
                            <li class="flex items-start gap-2">
                                <svg class="w-5 h-5 text-primary-green mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                                </svg>
                                <span class="text-gray-700 text-sm">12 months' Bank or M-Pesa statements</span>
                            </li>
                            <li class="flex items-start gap-2">
                                <svg class="w-5 h-5 text-primary-green mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                                </svg>
                                <span class="text-gray-700 text-sm">Original logbook</span>
                            </li>
                            <li class="flex items-start gap-2">
                                <svg class="w-5 h-5 text-primary-green mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                                </svg>
                                <span class="text-gray-700 text-sm">2 passport-size photos</span>
                            </li>
                        </ul>
                    </div>
                    
                    <div class="bg-gradient-to-r from-primary-green to-primary-blue p-6 rounded-xl text-white">
                        <p class="text-lg font-semibold text-center">
                            Fast. Fair. Flexible.<br>
                            Get your loan approved today and keep your car while you use the cash!
                        </p>
                    </div>
                </div>
                
                <!-- Right Column: Image -->
                <div class="relative">
                    <img src="https://images.unsplash.com/photo-1449965408869-eaa3f722e40d?w=800&h=1000&fit=crop" 
                         alt="Logbook Loan" 
                         class="w-full h-auto rounded-2xl shadow-2xl object-cover">
                    <div class="absolute inset-0 bg-gradient-to-t from-black/20 to-transparent rounded-2xl"></div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Application Form Section -->
<section class="py-16 bg-gray-50">
    <div class="container mx-auto px-4">
        <div class="max-w-3xl mx-auto">
            <div class="text-center mb-8">
                <h2 class="text-3xl md:text-4xl font-bold text-gray-900 mb-4">Apply for Your Logbook Loan</h2>
                <p class="text-gray-600 mb-4">Fill out the form below and we'll get back to you within 24 hours</p>
                <button onclick="openCalculatorModal()" class="inline-flex items-center gap-2 bg-gradient-to-r from-primary-blue to-primary-green text-white px-6 py-3 rounded-full font-bold hover:shadow-xl transition-all transform hover:-translate-y-1">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 14h.01M12 14h.01M15 11h.01M12 11h.01M9 11h.01M7 21h10a2 2 0 002-2V5a2 2 0 00-2-2H7a2 2 0 00-2 2v14a2 2 0 002 2z"/>
                    </svg>
                    Calculate Your Loan
                </button>
            </div>
            
            <div class="bg-white rounded-2xl p-8 shadow-lg">
                    <form id="logbookLoanForm" class="space-y-4" novalidate>
                        <input type="hidden" name="loan_type" value="Logbook Loan">
                        <input type="hidden" name="loan_category" value="logbook_loan">
                        
                        <?php if ($loggedInUser): ?>
                        <!-- Logged in user - show read-only info -->
                        <div class="bg-green-50 border border-green-200 rounded-lg p-4 mb-4">
                            <div class="flex items-center gap-2 text-green-700">
                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                                <span class="font-semibold">Welcome back, <?php echo htmlspecialchars($loggedInUser['full_name']); ?>!</span>
                            </div>
                            <p class="text-green-600 text-sm mt-1">Your information has been pre-filled from your profile.</p>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Full Name</label>
                            <input type="text" value="<?php echo htmlspecialchars($loggedInUser['full_name']); ?>" readonly
                                   class="w-full px-4 py-3 border border-gray-200 rounded-lg bg-gray-100 text-gray-700 cursor-not-allowed">
                            <input type="hidden" name="full_name" value="<?php echo htmlspecialchars($loggedInUser['full_name']); ?>">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Phone Number</label>
                            <input type="text" value="<?php echo htmlspecialchars($loggedInUser['phone']); ?>" readonly
                                   class="w-full px-4 py-3 border border-gray-200 rounded-lg bg-gray-100 text-gray-700 cursor-not-allowed">
                            <input type="hidden" name="phone" value="<?php echo htmlspecialchars($loggedInUser['phone']); ?>">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Email Address</label>
                            <input type="text" value="<?php echo htmlspecialchars($loggedInUser['email']); ?>" readonly
                                   class="w-full px-4 py-3 border border-gray-200 rounded-lg bg-gray-100 text-gray-700 cursor-not-allowed">
                            <input type="hidden" name="email" value="<?php echo htmlspecialchars($loggedInUser['email']); ?>">
                        </div>
                        <input type="hidden" id="lbConsentName" name="consent_name" value="<?php echo htmlspecialchars($loggedInUser['full_name']); ?>">
                        <?php if (!empty($loggedInUser['id_number'])): ?>
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">ID / Passport Number</label>
                            <input type="text" value="<?php echo htmlspecialchars($loggedInUser['id_number']); ?>" readonly
                                   class="w-full px-4 py-3 border border-gray-200 rounded-lg bg-gray-100 text-gray-700 cursor-not-allowed">
                            <input type="hidden" id="lbConsentId" name="consent_id" value="<?php echo htmlspecialchars($loggedInUser['id_number']); ?>">
                        </div>
                        <?php else: ?>
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">ID / Passport Number *</label>
                            <input type="text" id="lbConsentId" name="consent_id" required
                                   class="w-full px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary-green focus:border-transparent"
                                   placeholder="National ID or Passport number">
                            <p class="text-xs text-amber-600 mt-1">⚠ Not on your profile yet. <a href="<?php echo SITE_URL; ?>/dashboard/profile.php" class="underline">Update profile</a></p>
                        </div>
                        <?php endif; ?>
                        <?php else: ?>
                        <!-- Guest user - show form fields -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Full Name *</label>
                            <input type="text" name="full_name" required 
                                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-green focus:border-transparent">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Phone Number *</label>
                            <input type="tel" name="phone" required 
                                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-green focus:border-transparent">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Email Address</label>
                            <input type="email" name="email" 
                                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-green focus:border-transparent">
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">ID / Passport Number *</label>
                            <input type="text" id="lbGuestIdNumber" name="consent_id" required
                                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-green focus:border-transparent"
                                   placeholder="National ID or Passport number">
                            <p class="text-xs text-red-500 mt-1 hidden" id="lbGuestIdError">Please enter your ID / Passport number</p>
                        </div>
                        <input type="hidden" id="lbConsentName" name="consent_name">
                        <input type="hidden" id="lbConsentId">
                        <?php endif; ?>
                        
                        <!-- Loan Purpose - Always required -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Loan Purpose *</label>
                            <textarea name="loan_purpose" required rows="2"
                                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-green focus:border-transparent"
                                   placeholder="Briefly describe the purpose of your loan"></textarea>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Loan Amount (KES) *</label>
                            <input type="number" id="logbookLoanAmount" name="loan_amount" required min="50000" max="1500000" step="1000" value="200000"
                                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-green focus:border-transparent">
                            <p class="text-xs text-gray-500 mt-1">From KES 50,000 to KES 1,500,000</p>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Loan Period (Months) *</label>
                            <select id="logbookLoanPeriod" name="loan_period" required 
                                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-green focus:border-transparent">
                                <option value="3">3 Months</option>
                                <option value="6">6 Months</option>
                                <option value="12" selected>12 Months</option>
                                <option value="18">18 Months</option>
                                <option value="24">24 Months</option>
                            </select>
                        </div>
                        
                        <!-- ===== Advanced Vehicle Details ===== -->
                        <div class="bg-blue-50 border-2 border-blue-200 rounded-xl p-5 space-y-4">
                            <h3 class="font-bold text-primary-blue flex items-center gap-2">
                                <span>🚗</span> Vehicle Details
                            </h3>

                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-semibold text-gray-700 mb-2">Vehicle Make *</label>
                                    <select id="vehicleMake" name="vehicleMake" required
                                            class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-blue bg-white"
                                            onchange="lbUpdateModels()">
                                        <option value="">Select Make</option>
                                        <?php foreach (array_keys($vehicleMakes) as $make): ?>
                                        <option value="<?php echo htmlspecialchars($make); ?>"><?php echo htmlspecialchars($make); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div>
                                    <label class="block text-sm font-semibold text-gray-700 mb-2">Vehicle Model *</label>
                                    <select id="vehicleModel" name="vehicleModel" required disabled
                                            class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-blue bg-white">
                                        <option value="">Select Make first</option>
                                    </select>
                                </div>
                            </div>

                            <div>
                                <label class="block text-sm font-semibold text-gray-700 mb-2">Vehicle Registration Number *</label>
                                <input type="text" id="vehicleRegistration" name="vehicleRegistration" required maxlength="10"
                                       class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-blue uppercase"
                                       placeholder="e.g. KDA 123A" oninput="this.value=this.value.toUpperCase()">
                                <p class="text-xs text-gray-500 mt-1">As it appears on your logbook</p>
                            </div>

                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-semibold text-gray-700 mb-2">Vehicle Type *</label>
                                    <select id="vehicleType" name="vehicleType" required
                                            class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-blue bg-white"
                                            onchange="lbUpdateQualifying()">
                                        <option value="">Select Type</option>
                                        <option value="private">🚘 Private Use</option>
                                        <option value="psv">🚌 PSV (Public Service)</option>
                                    </select>
                                </div>
                                <div>
                                    <label class="block text-sm font-semibold text-gray-700 mb-2">Year of Manufacture *</label>
                                    <select id="vehicleYear" name="vehicleYear" required
                                            class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-blue bg-white"
                                            onchange="lbUpdateQualifying()">
                                        <option value="">Select Year</option>
                                        <?php for ($y = (int)date('Y'); $y >= 1990; $y--): ?>
                                        <option value="<?php echo $y; ?>"><?php echo $y; ?></option>
                                        <?php endfor; ?>
                                    </select>
                                </div>
                            </div>

                            <div>
                                <label class="block text-sm font-semibold text-gray-700 mb-2">Estimated Vehicle Value (KES) *</label>
                                <input type="number" id="estimatedValue" name="estimatedValue" required min="50000" step="10000"
                                       class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-blue"
                                       placeholder="e.g. 1,500,000" oninput="lbUpdateQualifying()">
                            </div>

                            <!-- Qualifying Info Box -->
                            <div id="lbQualifyingBox" class="bg-white border border-blue-300 rounded-lg p-4 hidden">
                                <div class="flex items-center justify-between">
                                    <div>
                                        <p class="text-xs text-gray-500">Qualifying Percentage</p>
                                        <p class="text-2xl font-bold text-primary-blue" id="lbQualifyingPct">--%</p>
                                    </div>
                                    <div class="text-right">
                                        <p class="text-xs text-gray-500">Max Eligible Amount</p>
                                        <p class="text-xl font-bold text-green-600" id="lbMaxEligible">KES 0</p>
                                    </div>
                                </div>
                                <p class="text-xs text-gray-500 mt-2">Based on vehicle make, type, and age. Final amount subject to valuation.</p>
                                <div id="lbCapWarning" class="mt-3 bg-amber-50 border border-amber-300 rounded-lg p-3 hidden">
                                    <p class="text-sm text-amber-800 font-semibold">⚠️ Your loan amount exceeds the max eligible amount</p>
                                    <p class="text-xs text-amber-700 mt-1">Consider reducing your loan amount to match the maximum based on qualifying percentage.</p>
                                </div>
                            </div>
                        </div>
                        <!-- ===== End Vehicle Details ===== -->

                        <!-- ===== Terms & Consent ===== -->
                        <div class="bg-gray-50 rounded-xl border border-gray-200 p-5 space-y-4">
                            <div class="flex items-center gap-2 mb-1">
                                <span class="text-lg">📋</span>
                                <h4 class="font-semibold text-gray-800">Terms & Data Processing Consent</h4>
                            </div>

                            <div class="bg-white border border-gray-200 rounded-lg p-3 max-h-36 overflow-y-auto text-xs text-gray-600 leading-relaxed">
                                <p class="mb-2">By submitting this application, you acknowledge and agree to the following:</p>
                                <ol class="list-decimal pl-4 space-y-1">
                                    <li>All information provided is true and accurate to the best of your knowledge.</li>
                                    <li>You authorise Fantom Capital to verify all information and documents submitted.</li>
                                    <li>You consent to credit checks and CRB inquiries as part of the loan assessment.</li>
                                    <li>You understand approval is subject to eligibility criteria and vehicle valuation.</li>
                                    <li>You agree to the applicable interest rates, fees, and repayment terms as communicated.</li>
                                    <li>Your personal data will be processed in accordance with the Kenya Data Protection Act, 2019.</li>
                                </ol>
                            </div>

                            <label class="flex items-start gap-3 cursor-pointer">
                                <input type="checkbox" id="lbTerms" required class="mt-1 accent-primary-blue">
                                <span class="text-sm text-gray-700">
                                    I agree to the <a href="<?php echo SITE_URL; ?>/terms.php" target="_blank" class="text-primary-blue hover:underline font-semibold">Terms and Conditions</a> and 
                                    <a href="<?php echo SITE_URL; ?>/privacy.php" target="_blank" class="text-primary-blue hover:underline font-semibold">Privacy Policy</a>.
                                    <span class="block mt-1.5 text-xs text-gray-500">✍️ By ticking this box, I confirm that I am digitally signing this loan application with my full name and ID number as provided above.</span>
                                </span>
                            </label>
                        </div>
                        <!-- ===== End Terms & Consent ===== -->

                        <button type="button" onclick="lbHandleSubmit()"
                                class="w-full bg-gradient-to-r from-primary-green to-primary-blue text-white py-4 rounded-full font-bold text-lg hover:opacity-90 transition shadow-lg hover:shadow-xl flex items-center justify-center gap-2">
                            Submit Application
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7l5 5m0 0l-5 5m5-5H6"/>
                            </svg>
                        </button>
                    </form>
                    <div id="formMessage" class="mt-4 hidden"></div>
                </div>
        </div>
    </div>
</section>

<!-- Loading Modal -->
<div id="loadingModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden items-center justify-center">
    <div class="bg-white rounded-2xl p-8 text-center max-w-sm mx-4">
        <div class="animate-spin w-16 h-16 border-4 border-primary-blue border-t-transparent rounded-full mx-auto mb-4"></div>
        <h3 class="text-xl font-bold text-gray-900 mb-2">Submitting Application</h3>
        <p class="text-gray-600">Please wait while we process your application...</p>
    </div>
</div>

<!-- Success Modal -->
<div id="successModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden items-center justify-center">
    <div class="bg-white rounded-2xl shadow-2xl max-w-md mx-4 overflow-hidden">
        <div class="bg-gradient-to-r from-primary-blue to-primary-green p-6 text-center">
            <div class="w-20 h-20 bg-white rounded-full flex items-center justify-center mx-auto mb-4">
                <svg class="w-12 h-12 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"/>
                </svg>
            </div>
            <h3 class="text-2xl font-bold text-white">Application Submitted!</h3>
        </div>
        <div class="p-6 text-center">
            <p class="text-gray-700 mb-4" id="successMessage">Your loan application has been submitted successfully.</p>
            <div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
                <p class="text-blue-800 font-semibold">📧 Check Your Email</p>
                <p class="text-blue-600 text-sm mt-1">We've sent a verification email to your inbox. Please verify your email to upload documents and complete your application.</p>
            </div>
            <a href="<?php echo SITE_URL; ?>" class="block w-full bg-gradient-to-r from-primary-blue to-primary-green text-white py-3 rounded-lg font-semibold hover:opacity-90 transition text-center">
                Back to Home
            </a>
        </div>
    </div>
</div>

<!-- Error Modal -->
<div id="errorModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden items-center justify-center">
    <div class="bg-white rounded-2xl shadow-2xl max-w-md mx-4 overflow-hidden">
        <div class="bg-red-500 p-6 text-center">
            <div class="w-20 h-20 bg-white rounded-full flex items-center justify-center mx-auto mb-4">
                <svg class="w-12 h-12 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M6 18L18 6M6 6l12 12"/>
                </svg>
            </div>
            <h3 class="text-2xl font-bold text-white">Submission Failed</h3>
        </div>
        <div class="p-6 text-center">
            <p class="text-gray-700 mb-6" id="errorMessage">An error occurred while submitting your application.</p>
            <button onclick="closeErrorModal()" class="w-full bg-red-500 text-white py-3 rounded-lg font-semibold hover:bg-opacity-90 transition">
                Try Again
            </button>
        </div>
    </div>
</div>

<!-- Login Required Modal -->
<div id="loginModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden items-center justify-center">
    <div class="bg-white rounded-2xl shadow-2xl max-w-md mx-4 overflow-hidden">
        <div class="bg-gradient-to-r from-primary-blue to-primary-green p-6 text-center">
            <div class="w-20 h-20 bg-white rounded-full flex items-center justify-center mx-auto mb-4">
                <svg class="w-12 h-12 text-primary-blue" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/>
                </svg>
            </div>
            <h3 class="text-2xl font-bold text-white">Welcome Back!</h3>
        </div>
        <div class="p-6">
            <div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6 text-center">
                <p class="text-blue-800 font-semibold">✅ Application Submitted Successfully!</p>
                <p class="text-blue-600 text-sm mt-1">We found your existing account.</p>
            </div>
            <p class="text-gray-700 mb-6 text-center">Please login to upload your required documents and complete your application.</p>
            
            <form id="quickLoginForm" class="space-y-4">
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Email Address</label>
                    <input type="email" id="loginEmail" required class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-blue focus:border-transparent" placeholder="Enter your email">
                </div>
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Password</label>
                    <div class="relative">
                        <input type="password" id="loginPassword" required class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-blue focus:border-transparent pr-12" placeholder="Enter your password">
                        <button type="button" onclick="toggleLoginPassword()" class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700">
                            <svg id="loginPasswordIcon" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
                            </svg>
                        </button>
                    </div>
                </div>
                <div id="loginError" class="hidden bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg text-sm"></div>
                <button type="submit" id="loginSubmitBtn" class="w-full bg-primary-blue text-white py-3 rounded-lg font-semibold hover:bg-opacity-90 transition">
                    Login & Continue
                </button>
            </form>
            
            <div class="mt-4 text-center">
                <a href="<?php echo SITE_URL; ?>/forgot-password.php" class="text-primary-blue text-sm hover:underline">Forgot Password?</a>
            </div>
            
            <div class="mt-4 pt-4 border-t border-gray-100 text-center">
                <button onclick="closeLoginModal()" class="text-gray-500 text-sm hover:text-gray-700">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
const lbIsLoggedIn  = <?php echo $loggedInUser ? 'true' : 'false'; ?>;
const lbHasIdNumber = <?php echo ($loggedInUser && !empty($loggedInUser['id_number'])) ? 'true' : 'false'; ?>;
const lbSiteUrl     = '<?php echo SITE_URL; ?>';
// ---- Vehicle data for logbook form ----
var lbVehicleModels = {};
try { lbVehicleModels = <?php echo getVehicleDataJson() ?: '{}'; ?>; } catch(e) {}
var lbVehiclePercentages = {};
try { lbVehiclePercentages = <?php
    $pctData = [];
    foreach ($vehicleMakes as $make => $info) {
        $pctData[$make] = ['private' => $info['private'] ?? 0, 'psv' => $info['psv'] ?? 0];
    }
    echo json_encode($pctData) ?: '{}';
?>; } catch(e) {}

function lbUpdateModels() {
    const make = document.getElementById('vehicleMake').value;
    const modelSel = document.getElementById('vehicleModel');
    modelSel.innerHTML = '<option value="">Select Model</option>';
    modelSel.disabled = !make;
    if (make && lbVehicleModels[make]) {
        lbVehicleModels[make].forEach(m => {
            const opt = document.createElement('option');
            opt.value = m; opt.textContent = m;
            modelSel.appendChild(opt);
        });
    }
    lbUpdateQualifying();
}

function lbUpdateQualifying() {
    const make = document.getElementById('vehicleMake').value;
    const vType = document.getElementById('vehicleType').value;
    const vYear = parseInt(document.getElementById('vehicleYear').value);
    const estValue = parseFloat(document.getElementById('estimatedValue').value);
    const box = document.getElementById('lbQualifyingBox');

    if (!make || !vType || !vYear) { box.classList.add('hidden'); return; }

    const currentYear = new Date().getFullYear();
    const age = currentYear - vYear;
    const bracket = age <= 8 ? 0 : (age <= 15 ? 1 : 2);

    const pct = (lbVehiclePercentages[make] || lbVehiclePercentages['Other'])[vType][bracket];
    document.getElementById('lbQualifyingPct').textContent = pct + '%';

    if (estValue > 0) {
        const maxAmount = Math.round(estValue * pct / 100);
        document.getElementById('lbMaxEligible').textContent = 'KES ' + maxAmount.toLocaleString('en-KE');
        const loanAmt = parseFloat(document.getElementById('logbookLoanAmount').value) || 0;
        const capWarn = document.getElementById('lbCapWarning');
        loanAmt > maxAmount ? capWarn.classList.remove('hidden') : capWarn.classList.add('hidden');
    } else {
        document.getElementById('lbMaxEligible').textContent = 'Enter value above';
        document.getElementById('lbCapWarning').classList.add('hidden');
    }
    box.classList.remove('hidden');
}
// ---- End vehicle data ----

function showLoading() {
    document.getElementById('loadingModal').classList.remove('hidden');
    document.getElementById('loadingModal').classList.add('flex');
    document.body.style.overflow = 'hidden';
}

function hideLoading() {
    document.getElementById('loadingModal').classList.add('hidden');
    document.getElementById('loadingModal').classList.remove('flex');
}

function showSuccessModal(message) {
    hideLoading();
    document.getElementById('successMessage').textContent = message || 'Your loan application has been submitted successfully.';
    document.getElementById('successModal').classList.remove('hidden');
    document.getElementById('successModal').classList.add('flex');
}

function closeSuccessModal() {
    document.getElementById('successModal').classList.add('hidden');
    document.getElementById('successModal').classList.remove('flex');
    document.body.style.overflow = '';
}

function showErrorModal(message) {
    hideLoading();
    document.getElementById('errorMessage').textContent = message || 'An error occurred. Please try again.';
    document.getElementById('errorModal').classList.remove('hidden');
    document.getElementById('errorModal').classList.add('flex');
}

function closeErrorModal() {
    document.getElementById('errorModal').classList.add('hidden');
    document.getElementById('errorModal').classList.remove('flex');
    document.body.style.overflow = '';
}

function showLoginModal(email) {
    hideLoading();
    if (email) {
        document.getElementById('loginEmail').value = email;
    }
    document.getElementById('loginModal').classList.remove('hidden');
    document.getElementById('loginModal').classList.add('flex');
}

function closeLoginModal() {
    document.getElementById('loginModal').classList.add('hidden');
    document.getElementById('loginModal').classList.remove('flex');
    document.body.style.overflow = '';
}

function toggleLoginPassword() {
    const input = document.getElementById('loginPassword');
    const icon = document.getElementById('loginPasswordIcon');
    if (input.type === 'password') {
        input.type = 'text';
        icon.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"/>';
    } else {
        input.type = 'password';
        icon.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>';
    }
}

// Quick login form handler
var _qlf = document.getElementById('quickLoginForm');
if (_qlf) _qlf.addEventListener('submit', async function(e) {
    e.preventDefault();
    const email = document.getElementById('loginEmail').value;
    const password = document.getElementById('loginPassword').value;
    const submitBtn = document.getElementById('loginSubmitBtn');
    const errorDiv = document.getElementById('loginError');
    
    submitBtn.disabled = true;
    submitBtn.textContent = 'Logging in...';
    errorDiv.classList.add('hidden');
    
    try {
        const formData = new FormData();
        formData.append('email', email);
        formData.append('password', password);
        
        const response = await fetch('<?php echo SITE_URL; ?>/auth/login.php', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        
        if (result.success) {
            window.location.href = result.redirect || '<?php echo SITE_URL; ?>/dashboard';
        } else {
            errorDiv.textContent = result.message;
            errorDiv.classList.remove('hidden');
            submitBtn.disabled = false;
            submitBtn.textContent = 'Login & Continue';
        }
    } catch (error) {
        errorDiv.textContent = 'An error occurred. Please try again.';
        errorDiv.classList.remove('hidden');
        submitBtn.disabled = false;
        submitBtn.textContent = 'Login & Continue';
    }
});

// Re-check cap warning when loan amount changes
document.getElementById('logbookLoanAmount').addEventListener('input', function() {
    lbUpdateQualifying();
});

async function lbHandleSubmit() {
    var form = document.getElementById('logbookLoanForm');
    if (!form) { console.error('logbookLoanForm not found'); return; }

    // ── Helpers ──────────────────────────────────────────────────────────
    function markErr(el) {
        if (!el) return;
        el.style.borderColor = '#ef4444';
        el.style.boxShadow   = '0 0 0 3px rgba(239,68,68,0.25)';
        var ev = (el.tagName === 'SELECT') ? 'change' : 'input';
        el.addEventListener(ev, function clear() {
            el.style.borderColor = ''; el.style.boxShadow = '';
            el.removeEventListener(ev, clear);
        });
    }
    function goTo(el) {
        if (!el) return;
        el.scrollIntoView({ behavior: 'smooth', block: 'center' });
        setTimeout(function() { try { el.focus(); } catch(ignore) {} }, 400);
    }

    // ── Step 1: Guest personal fields ───────────────────────────────────
    if (!lbIsLoggedIn) {
        var nameEl  = form.querySelector('input[name="full_name"]');
        var phoneEl = form.querySelector('input[name="phone"]');
        var idEl    = form.querySelector('#lbGuestIdNumber');

        if (!nameEl || !nameEl.value.trim()) {
            markErr(nameEl); goTo(nameEl); return;
        }
        if (!phoneEl || !phoneEl.value.trim()) {
            markErr(phoneEl); goTo(phoneEl); return;
        }
        if (!idEl || !idEl.value.trim()) {
            markErr(idEl); goTo(idEl); return;
        }
        // Sync consent_name hidden field
        var cnEl = document.getElementById('lbConsentName');
        if (cnEl) cnEl.value = nameEl.value.trim();
    }

    // ── Step 2: Logged-in user missing ID number ─────────────────────────
    if (lbIsLoggedIn && !lbHasIdNumber) {
        var lbIdEl = document.getElementById('lbConsentId');
        if (!lbIdEl || !lbIdEl.value.trim()) {
            markErr(lbIdEl); goTo(lbIdEl); return;
        }
    }

    // ── Step 3: Terms checkbox ───────────────────────────────────────────
    if (!document.getElementById('lbTerms').checked) {
        document.getElementById('lbTerms').scrollIntoView({ behavior: 'smooth', block: 'center' });
        alert('Please agree to the Terms and Conditions to continue.');
        return;
    }

    // ── Step 4: Vehicle fields ───────────────────────────────────────────
    var vFields = [
        { id: 'vehicleMake',         label: 'Vehicle Make' },
        { id: 'vehicleModel',        label: 'Vehicle Model' },
        { id: 'vehicleRegistration', label: 'Vehicle Registration Number' },
        { id: 'vehicleType',         label: 'Vehicle Type' },
        { id: 'vehicleYear',         label: 'Year of Manufacture' },
        { id: 'estimatedValue',      label: 'Estimated Vehicle Value' }
    ];
    for (var vi = 0; vi < vFields.length; vi++) {
        var vEl = document.getElementById(vFields[vi].id);
        if (!vEl || !vEl.value.trim()) {
            markErr(vEl); goTo(vEl);
            alert('Please fill in: ' + vFields[vi].label);
            return;
        }
    }

    // ── Step 5: Build and submit ─────────────────────────────────────────
    var fd       = new FormData(form);
    var loanAmt  = parseFloat(fd.get('loan_amount')) || 0;
    var loanPer  = parseInt(fd.get('loan_period'))   || 12;
    var monthly  = (loanAmt * 0.04 * loanPer + loanAmt) / loanPer;
    var totalRep = loanAmt + loanAmt * 0.04 * loanPer;

    fd.append('monthly_payment', monthly.toFixed(2));
    fd.append('total_repayment', totalRep.toFixed(2));

    var pctEl = document.getElementById('lbQualifyingPct');
    if (pctEl && pctEl.textContent && pctEl.textContent !== '--%') {
        fd.append('qualifying_percentage', parseFloat(pctEl.textContent) || 0);
    }

    showLoading();

    try {
        fd.append('csrf_token', document.querySelector('meta[name="csrf-token"]')?.content || '');
        var resp   = await fetch(lbSiteUrl + '/api/submit_loan_application.php', { method: 'POST', body: fd });
        var result = await resp.json();

        if (result.success) {
            form.reset();
            if (lbIsLoggedIn && result.loan_id) {
                window.location.href = lbSiteUrl + '/dashboard/loan-documents.php?loan_id=' + result.loan_id + '&new=1';
            } else if (result.requires_login) {
                showLoginModal(fd.get('email'));
            } else {
                showSuccessModal(result.message || 'Application submitted successfully!');
            }
        } else {
            showErrorModal(result.message || 'Submission failed. Please try again.');
        }
    } catch (err) {
        showErrorModal('Network error. Please check your connection and try again.');
    }
}

// Calculator Modal Functions
function openCalculatorModal() {
    document.getElementById('calculatorModal').classList.remove('hidden');
    document.body.style.overflow = 'hidden';
    updateCalculator();
}

function closeCalculatorModal() {
    document.getElementById('calculatorModal').classList.add('hidden');
    document.body.style.overflow = '';
}

function updateCalculator() {
    const amount = parseFloat(document.getElementById('calcAmount').value);
    const period = parseFloat(document.getElementById('calcPeriod').value);
    const rate = 0.04;
    
    document.getElementById('calcAmountDisplay').textContent = 'KES ' + amount.toLocaleString('en-KE');
    document.getElementById('calcPeriodDisplay').textContent = period + ' Months';
    
    // Flat 4% monthly interest on principal
    const monthlyInterestAmount = amount * rate;
    const totalInterest = monthlyInterestAmount * period;
    const totalRepayment = amount + totalInterest;
    const monthlyPayment = totalRepayment / period;
    
    document.getElementById('calcMonthly').textContent = 'KES ' + monthlyPayment.toLocaleString('en-KE', {maximumFractionDigits: 0});
    document.getElementById('calcTotal').textContent = 'KES ' + totalRepayment.toLocaleString('en-KE', {maximumFractionDigits: 0});
    document.getElementById('calcInterest').textContent = 'KES ' + totalInterest.toLocaleString('en-KE', {maximumFractionDigits: 0});
}

function applyCalculatedLoan() {
    const amount = document.getElementById('calcAmount').value;
    const period = document.getElementById('calcPeriod').value;
    
    document.getElementById('logbookLoanAmount').value = amount;
    document.getElementById('logbookLoanPeriod').value = period;
    
    closeCalculatorModal();
    
    document.getElementById('logbookLoanAmount').scrollIntoView({ behavior: 'smooth', block: 'center' });
    document.getElementById('logbookLoanAmount').classList.add('ring-4', 'ring-primary-green');
    setTimeout(() => {
        document.getElementById('logbookLoanAmount').classList.remove('ring-4', 'ring-primary-green');
    }, 2000);
}

// Initialize calculator on page load + guest consent name auto-fill
document.addEventListener('DOMContentLoaded', function() {
    updateCalculator();

    <?php if (!$loggedInUser): ?>
    // For guests: mirror full_name → lbConsentName, lbGuestIdNumber → lbConsentId
    var _lbf = document.getElementById('logbookLoanForm');
    const guestName = _lbf ? _lbf.querySelector('input[name="full_name"]') : null;
    const lbCName   = document.getElementById('lbConsentName');
    const lbIdField = document.getElementById('lbGuestIdNumber');
    const lbCId     = document.getElementById('lbConsentId');
    if (guestName && lbCName) {
        const syncName = () => { lbCName.value = guestName.value; };
        guestName.addEventListener('input', syncName);
        guestName.addEventListener('change', syncName);
        syncName();
    }
    if (lbIdField && lbCId) {
        const syncId = () => { lbCId.value = lbIdField.value; };
        lbIdField.addEventListener('input', syncId);
        lbIdField.addEventListener('change', syncId);
        syncId();
    }
    <?php endif; ?>
});
</script>

<!-- Calculator Modal -->
<div id="calculatorModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl max-w-md w-full p-6 relative max-h-[90vh] overflow-y-auto">
        <button onclick="closeCalculatorModal()" class="absolute top-4 right-4 text-gray-400 hover:text-gray-600">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
        </button>
        
        <h2 class="text-2xl font-bold bg-gradient-to-r from-primary-blue to-primary-green bg-clip-text text-transparent mb-2">Logbook Loan Calculator</h2>
        <p class="text-sm text-gray-600 mb-6">Estimate your monthly payments</p>
        
        <div class="space-y-4">
            <div>
                <div class="flex justify-between items-center mb-2">
                    <label class="text-sm font-semibold text-gray-700">Loan Amount</label>
                    <span class="text-lg font-bold text-primary-blue" id="calcAmountDisplay">KES 200,000</span>
                </div>
                <input type="range" id="calcAmount" min="50000" max="1500000" step="10000" value="200000"
                       class="w-full h-2 bg-gradient-to-r from-primary-blue/20 to-primary-blue/40 rounded-lg appearance-none cursor-pointer accent-primary-blue"
                       oninput="updateCalculator()">
                <div class="flex justify-between text-xs text-gray-500 mt-1">
                    <span>50K</span>
                    <span>1.5M</span>
                </div>
            </div>
            
            <div>
                <div class="flex justify-between items-center mb-2">
                    <label class="text-sm font-semibold text-gray-700">Loan Period</label>
                    <span class="text-lg font-bold text-primary-green" id="calcPeriodDisplay">12 Months</span>
                </div>
                <input type="range" id="calcPeriod" min="3" max="24" value="12"
                       class="w-full h-2 bg-gradient-to-r from-primary-green/20 to-primary-green/40 rounded-lg appearance-none cursor-pointer accent-primary-green"
                       oninput="updateCalculator()">
                <div class="flex justify-between text-xs text-gray-500 mt-1">
                    <span>3 Months</span>
                    <span>24 Months</span>
                </div>
            </div>
            
            <div class="bg-gradient-to-br from-primary-blue/5 via-white to-primary-green/5 rounded-xl p-4 border border-gray-100">
                <div class="space-y-3">
                    <div class="flex justify-between items-center">
                        <p class="text-sm text-gray-600">Monthly Payment</p>
                        <p class="text-xl font-bold text-primary-blue" id="calcMonthly">KES 0</p>
                    </div>
                    <div class="border-t border-gray-200 pt-2 flex justify-between items-center">
                        <p class="text-sm text-gray-600">Total Repayment</p>
                        <p class="text-lg font-bold text-gray-800" id="calcTotal">KES 0</p>
                    </div>
                    <div class="flex justify-between items-center">
                        <p class="text-sm text-gray-600">Interest (4% Flat Rate)</p>
                        <p class="text-sm font-semibold text-primary-green" id="calcInterest">KES 0</p>
                    </div>
                </div>
            </div>
            
            <button onclick="applyCalculatedLoan()" 
                    class="w-full bg-gradient-to-r from-primary-blue to-primary-green text-white py-3 rounded-full font-bold hover:shadow-xl transition-all transform hover:-translate-y-1">
                Apply for This Loan
            </button>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
