<?php
require_once 'config/config.php';
$pageTitle = 'Check Off Loans';

// 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">
                            💵 Get Instant Check-Off Loans
                        </h1>
                        <p class="text-lg text-gray-600 leading-relaxed">
                            Fast, Flexible & Affordable! Get instant approval with flexible limits from Ksh 5,000 to Ksh 500,000.
                        </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">Flexible Limits</h3>
                                    <p class="text-gray-600 text-xs">From Ksh 5,000 to 500,000</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">Instant Approval</h3>
                                    <p class="text-gray-600 text-xs">Get funds within 24 hours</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">Easy Repayment</h3>
                                    <p class="text-gray-600 text-xs">3-12 months flexible payment terms</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">Age: 23-60 years</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">National ID & PIN copy</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">3 months' payslips</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 Mpesa or bank statements</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. Simple. Reliable.<br>
                            Get your check-off loan approved today!
                        </p>
                    </div>
                </div>
                
                <!-- Right Column: Image -->
                <div class="relative">
                    <img src="https://images.unsplash.com/photo-1554224155-8d04cb21cd6c?w=800&h=1000&fit=crop" 
                         alt="Check-Off 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 Check-Off 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="checkoffLoanForm" class="space-y-4" novalidate>
                        <input type="hidden" name="loan_type" value="Check-Off Loan">
                        <input type="hidden" name="loan_category" value="checkoff_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>
                    <?php else: ?>
                    <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>
                    <?php endif; ?>
                    
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Age *</label>
                        <input type="number" name="age" required min="23" max="60" 
                               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">Must be between 23-60 years</p>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Employer *</label>
                        <input type="text" name="employer" 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">Loan Amount (KES) *</label>
                        <input type="number" id="checkoffLoanAmount" name="loan_amount" required min="5000" max="500000" value="50000" step="1000"
                               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">Min: KES 5,000 | Max: KES 500,000</p>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Loan Period *</label>
                        <select id="checkoffLoanPeriod" 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" selected>6 Months</option>
                            <option value="9">9 Months</option>
                            <option value="12">12 Months</option>
                        </select>
                    </div>
                    
                    <?php include 'includes/consent-section.php'; ?>

                    <button type="button" onclick="checkoffHandleSubmit()"
                            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="loadingOverlay" class="fixed inset-0 bg-black bg-opacity-50 z-[9999] hidden items-center justify-center">
    <div class="bg-white rounded-2xl p-8 text-center max-w-sm mx-4 shadow-2xl">
        <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="successOverlay" class="fixed inset-0 bg-black bg-opacity-50 z-[9999] 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-green to-primary-blue 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-2">Your checkoff loan application has been submitted successfully!</p>
            <p class="text-gray-600 text-sm mb-6">Please check your email to verify your account and upload required documents.</p>
            <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>

<!-- 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>
function showLoadingModal() {
    document.getElementById('loadingOverlay').classList.remove('hidden');
    document.getElementById('loadingOverlay').classList.add('flex');
    document.body.style.overflow = 'hidden';
}

function hideLoadingModal() {
    document.getElementById('loadingOverlay').classList.add('hidden');
    document.getElementById('loadingOverlay').classList.remove('flex');
}

function showSuccessModal() {
    hideLoadingModal();
    document.getElementById('successOverlay').classList.remove('hidden');
    document.getElementById('successOverlay').classList.add('flex');
}

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

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 _coQlf = document.getElementById('quickLoginForm');
if (_coQlf) _coQlf.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';
    }
});

const coIsLoggedIn  = <?php echo $loggedInUser ? 'true' : 'false'; ?>;
const coHasIdNumber = <?php echo ($loggedInUser && !empty($loggedInUser['id_number'])) ? 'true' : 'false'; ?>;
const coSiteUrl     = '<?php echo SITE_URL; ?>';

async function checkoffHandleSubmit() {
    var form = document.getElementById('checkoffLoanForm');
    if (!form) return;

    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 clr() { el.style.borderColor=''; el.style.boxShadow=''; el.removeEventListener(ev,clr); });
    }
    function goTo(el) {
        if (!el) return;
        el.scrollIntoView({ behavior:'smooth', block:'center' });
        setTimeout(function(){ try{ el.focus(); }catch(e){} }, 400);
    }

    if (!coIsLoggedIn) {
        var nameEl  = form.querySelector('input[name="full_name"]');
        var phoneEl = form.querySelector('input[name="phone"]');
        if (!nameEl || !nameEl.value.trim()) { markErr(nameEl); goTo(nameEl); return; }
        if (!phoneEl || !phoneEl.value.trim()) { markErr(phoneEl); goTo(phoneEl); return; }
        var cnEl = document.getElementById('consentNameHidden');
        if (cnEl && nameEl) cnEl.value = nameEl.value.trim();
    }

    if (!coHasIdNumber) {
        var idEl = document.getElementById('consentIdInput');
        if (!idEl || !idEl.value.trim()) { markErr(idEl); goTo(idEl); return; }
    }

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

    var formData = new FormData(form);
    var loanAmount = parseFloat(formData.get('loan_amount'));
    var loanPeriod = parseInt(formData.get('loan_period'));
    var totalRepayment = loanAmount + loanAmount * 0.04 * loanPeriod;
    var monthlyPayment = totalRepayment / loanPeriod;
    formData.append('monthly_payment', monthlyPayment.toFixed(2));
    formData.append('total_repayment', totalRepayment.toFixed(2));

    showLoadingModal();
    try {
        formData.append('csrf_token', document.querySelector('meta[name="csrf-token"]')?.content || '');
        var resp   = await fetch(coSiteUrl + '/api/submit_loan_application.php', { method:'POST', body:formData });
        var result = await resp.json();
        if (result.success) {
            form.reset();
            if (result.requires_login) { showLoginModal(formData.get('email')); }
            else { showSuccessModal(); }
        } else {
            hideLoadingModal();
            alert('\u274c ' + (result.message || 'Failed to submit. Please try again.'));
        }
    } catch(err) {
        hideLoadingModal();
        alert('\u274c Network error. Please 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('checkoffLoanAmount').value = amount;
    document.getElementById('checkoffLoanPeriod').value = period;
    
    closeCalculatorModal();
    
    document.getElementById('checkoffLoanAmount').scrollIntoView({ behavior: 'smooth', block: 'center' });
    document.getElementById('checkoffLoanAmount').classList.add('ring-4', 'ring-primary-green');
    setTimeout(() => {
        document.getElementById('checkoffLoanAmount').classList.remove('ring-4', 'ring-primary-green');
    }, 2000);
}

// Initialize calculator on page load
document.addEventListener('DOMContentLoaded', function() {
    updateCalculator();
});
</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">Check-Off 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 50,000</span>
                </div>
                <input type="range" id="calcAmount" min="5000" max="500000" step="1000" value="50000"
                       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>5K</span>
                    <span>500K</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">6 Months</span>
                </div>
                <input type="range" id="calcPeriod" min="3" max="12" value="6"
                       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>12 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'; ?>
