<?php
require_once './includes/session_init.php';
require_once 'includes/config.php';

// Check if member is logged in
if (!isset($_SESSION['member_id'])) {
    header("Location: login.php");
    exit();
}

$memberId = $_SESSION['member_id'];
$title = 'loan application';
$subTitle = 'loan application';

// Get member details
$stmt = $pdo->prepare("SELECT * FROM members WHERE id = ?");
$stmt->execute([$memberId]);
$member = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$member) {
    session_destroy();
    header("Location: login.php");
    exit();
}

// Generate CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Get available savings accounts for this member (where sub_account_code = 1)
$savingsAccounts = $pdo->prepare("
    SELECT ma.id, at.account_name, ma.available_balance
    FROM member_accounts ma
    JOIN account_types at ON ma.account_type_id = at.id
    WHERE ma.member_id = ? 
    AND at.account_type = 'savings'
    AND ma.sub_account_code = 1
");
$savingsAccounts->execute([$memberId]);
$savingsAccounts = $savingsAccounts->fetchAll();

// Get loan account types (not purposes)
$loanAccountTypes = $pdo->query("
    SELECT id, account_name, max_loan_factor 
    FROM account_types 
    WHERE account_type = 'loan'
")->fetchAll();

// Get loan purposes
$loanPurposes = $pdo->query("
    SELECT id, purpose_name 
    FROM loan_purposes
")->fetchAll();
// Process loan application
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['apply_loan'])) {
    try {
        // Verify CSRF token
        if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
            throw new Exception("Invalid form submission");
        }

        $pdo->beginTransaction();

        // Validate inputs
        $accountTypeId = (int)$_POST['account_type_id'];
        $savingsAccountId = (int)$_POST['savings_account_id'];
        $loanPurposeId = (int)$_POST['loan_purpose_id'];
        $loanAmount = (float)$_POST['loanAmount'];
        $loanPeriod = (int)$_POST['loan_period'];

        // Validate loan period
        $allowedPeriods = [6, 12, 24, 36];
        if (!in_array($loanPeriod, $allowedPeriods)) {
            throw new Exception("Invalid loan period selected");
        }

        // Get selected savings account details
        $selectedAccount = null;
        foreach ($savingsAccounts as $account) {
            if ($account['id'] == $savingsAccountId) {
                $selectedAccount = $account;
                break;
            }
        }

        if (!$selectedAccount) {
            throw new Exception("Invalid savings account selected");
        }

        // Get loan type multiplier
        $stmt = $pdo->prepare("SELECT max_loan_factor FROM account_types WHERE id = ?");
        $stmt->execute([$accountTypeId]);
        $accountType = $stmt->fetch();

        if (!$accountType) {
            throw new Exception("Invalid loan account type selected");
        }

        // Get loan purpose
        $stmt = $pdo->prepare("SELECT purpose_name FROM loan_purposes WHERE id = ?");
        $stmt->execute([$loanPurposeId]);
        $loanPurpose = $stmt->fetch();

        if (!$loanPurpose) {
            throw new Exception("Invalid loan purpose selected");
        }

        // Determine maximum eligibility
        $maxLoanAmount = $selectedAccount['available_balance'] * $accountType['max_loan_factor'];
        if ($loanAmount > $maxLoanAmount) {
            throw new Exception("Loan amount exceeds your maximum eligibility of Ksh " . number_format($maxLoanAmount, 2));
        }

        if ($loanAmount < 1000) {
            throw new Exception("Minimum loan amount is Ksh 1,000");
        }

        // Create loan record
        $loanNumber = 'LN' . time() . rand(100, 999);
        $stmt = $pdo->prepare("
            INSERT INTO loans (
                member_id, loan_number, account_type_id, 
                savings_account_id, loan_purpose_id, loan_amount, 
                loan_period, status, application_date
            ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', NOW())
        ");
        $stmt->execute([
            $memberId, $loanNumber, $accountTypeId,
            $savingsAccountId, $loanPurposeId, $loanAmount,
            $loanPeriod
        ]);
        $loanId = $pdo->lastInsertId();

        // Calculate provisional self-guarantee
        $availableBalance = $selectedAccount['available_balance'];
        $selfGuaranteeAmount = min($loanAmount, $availableBalance);
        $remainingAmount = $loanAmount - $selfGuaranteeAmount;

        // Store in session for the next step
        $_SESSION['loan_application'] = [
            'loan_id' => $loanId,
            'loan_number' => $loanNumber,
            'loan_amount' => $loanAmount,
            'self_guarantee_amount' => $selfGuaranteeAmount, // provisional only
            'available_balance' => $availableBalance,
            'remaining_amount' => $remainingAmount,
            'need_guarantors' => $remainingAmount > 0,
            'savings_account_id' => $savingsAccountId,
            'basis_account_id' => $savingsAccountId,
            'account_name' => $selectedAccount['account_name']
        ];

        $pdo->commit();

        // Redirect to guarantor step or confirmation
        if ($remainingAmount > 0) {
            header("Location: specify_guarantors.php");
        } else {
            $_SESSION['success'] = "Loan application submitted successfully! Pending approval.";
            header("Location: loan_status.php?id=" . $loanId);
        }
        exit();

    } catch (Exception $e) {
        $pdo->rollBack();
        $_SESSION['error'] = "Error: " . $e->getMessage();
        header("Location: loan_application.php");
        exit();
    }
}


// Display any errors
$error = isset($_SESSION['error']) ? $_SESSION['error'] : null;
unset($_SESSION['error']);

$success = isset($_SESSION['success']) ? $_SESSION['success'] : null;
unset($_SESSION['success']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Loan Application</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .form-container {
            max-width: 800px;
            margin: 0 auto;
        }
        .account-details {
            background-color: #f8f9fa;
            border-radius: 5px;
            padding: 15px;
            margin: 15px 0;
            border-left: 4px solid #0d6efd;
        }
        .guarantee-details {
            background-color: #e7f3ff;
            border-radius: 5px;
            padding: 15px;
            margin: 15px 0;
            border-left: 4px solid #198754;
        }
        .hidden {
            display: none;
        }
        .calculation-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
            padding: 5px 0;
            border-bottom: 1px solid #dee2e6;
        }
        .calculation-total {
            font-weight: bold;
            border-top: 2px solid #000;
            margin-top: 10px;
            padding-top: 10px;
        }
    </style>
</head>
<body>
    <?php include './partials/layouts/layoutTop.php'; ?>
    
    <div class="container py-5">
        <div class="form-container">
            <div class="card shadow">
                <div class="card-header bg-primary text-white">
                    <h3 class="mb-0"><i class="fas fa-hand-holding-usd me-2"></i>Loan Application</h3>
                </div>
                
                <div class="card-body">
                    <?php if ($error): ?>
                        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
                    <?php endif; ?>
                    
                    <?php if ($success): ?>
                        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
                    <?php endif; ?>
                    
                    <form method="POST" id="loanForm">
                        <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                        
                        <!-- Savings Account Selection -->
                        <div class="mb-3">
                            <label class="form-label">Select Savings Account <span class="text-danger">*</span></label>
                            <select name="savings_account_id" id="savingsAccount" class="form-select" required>
                                <option value="">-- Select Account --</option>
                                <?php foreach ($savingsAccounts as $account): ?>
                                    <option value="<?= $account['id'] ?>" 
                                        data-balance="<?= $account['available_balance'] ?>"
                                        data-account-name="<?= htmlspecialchars($account['account_name']) ?>">
                                        <?= htmlspecialchars($account['account_name']) ?> 
                                        (Ksh <?= number_format($account['available_balance'], 2) ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <!-- Account Details (shown after selection) -->
                        <div id="accountDetails" class="account-details hidden">
                            <h5>Account Details</h5>
                            <p>Available Balance: <strong id="accountBalance">Ksh 0.00</strong></p>
                            <p>Account Name: <strong id="accountName">-</strong></p>
                        </div>

                        <!-- Loan Account Type Selection -->
                        <div class="mb-3">
                            <label class="form-label">Loan Account Type <span class="text-danger">*</span></label>
                            <select name="account_type_id" id="accountType" class="form-select" required>
                                <option value="">-- Select Loan Account Type --</option>
                                <?php foreach ($loanAccountTypes as $type): ?>
                                    <option value="<?= $type['id'] ?>" 
                                        data-factor="<?= $type['max_loan_factor'] ?>">
                                        <?= htmlspecialchars($type['account_name']) ?> 
                                        (Max: <?= $type['max_loan_factor'] ?>x savings)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <!-- Loan Purpose Selection -->
                        <div class="mb-3">
                            <label class="form-label">Loan Purpose <span class="text-danger">*</span></label>
                            <select name="loan_purpose_id" class="form-select" required>
                                <option value="">-- Select Loan Purpose --</option>
                                <?php foreach ($loanPurposes as $purpose): ?>
                                    <option value="<?= $purpose['id'] ?>">
                                        <?= htmlspecialchars($purpose['purpose_name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <!-- Maximum Eligibility (calculated after selections) -->
                        <div id="eligibilityDetails" class="account-details hidden">
                            <h5>Loan Eligibility</h5>
                            <p>Maximum Loan Amount: <strong id="maxLoanAmount">Ksh 0.00</strong></p>
                            <p><small>Calculated as: <span id="calculationFormula">[Balance] × [Multiplier]</span></small></p>
                        </div>

                        <!-- Loan Amount -->
                        <div class="mb-3">
                            <label class="form-label">Amount (Ksh) <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text">Ksh</span>
                                <input type="number" name="loanAmount" id="loanAmount" class="form-control" 
                                       min="1000" step="100" required 
                                       placeholder="Enter amount">
                            </div>
                            <small class="text-muted">Minimum: Ksh 1,000</small>
                        </div>
                        
                        <!-- Repayment Period -->
                        <div class="mb-3">
                            <label class="form-label">Repayment Period (Months) <span class="text-danger">*</span></label>
                            <select name="loan_period" class="form-select" required>
                                <option value="">-- Select Period --</option>
                                <option value="6">6 Months</option>
                                <option value="12">12 Months</option>
                                <option value="24">24 Months</option>
                                <option value="36">36 Months</option>
                            </select>
                        </div>

                        <!-- Guarantee Calculation (Auto-calculated) -->
                        <div id="guaranteeDetails" class="guarantee-details hidden">
                            <h5><i class="fas fa-shield-alt me-2"></i>Guarantee Breakdown</h5>
                            <div id="guaranteeCalculations">
                                <!-- Calculations will be populated by JavaScript -->
                            </div>
                            <div class="mt-3">
                                <small class="text-muted">
                                    <i class="fas fa-info-circle me-1"></i>
                                    Your available balance will automatically be used as self-guarantee. Any remaining amount will require external guarantors.
                                </small>
                            </div>
                        </div>
                        
                        <div class="d-grid">
                            <button type="submit" name="apply_loan" class="btn btn-primary btn-lg">
                                <i class="fas fa-paper-plane me-2"></i>Submit Application
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <?php include './partials/layouts/layoutBottom.php'; ?>
    
    <script>
        // Get DOM elements
        const savingsAccountSelect = document.getElementById('savingsAccount');
        const accountTypeSelect = document.getElementById('accountType');
        const accountDetails = document.getElementById('accountDetails');
        const eligibilityDetails = document.getElementById('eligibilityDetails');
        const guaranteeDetails = document.getElementById('guaranteeDetails');
        const accountBalance = document.getElementById('accountBalance');
        const accountName = document.getElementById('accountName');
        const maxLoanAmount = document.getElementById('maxLoanAmount');
        const calculationFormula = document.getElementById('calculationFormula');
        const loanAmountInput = document.getElementById('loanAmount');
        const guaranteeCalculations = document.getElementById('guaranteeCalculations');

        // Update calculations when selections change
        function updateCalculations() {
            const selectedAccount = savingsAccountSelect.options[savingsAccountSelect.selectedIndex];
            const selectedAccountType = accountTypeSelect.options[accountTypeSelect.selectedIndex];
            const loanAmount = parseFloat(loanAmountInput.value) || 0;
            
            // Show/hide account details
            if (savingsAccountSelect.value) {
                const balance = parseFloat(selectedAccount.dataset.balance);
                const accountNameText = selectedAccount.dataset.accountName;
                accountBalance.textContent = 'Ksh ' + balance.toLocaleString('en-US');
                accountName.textContent = accountNameText;
                accountDetails.classList.remove('hidden');
            } else {
                accountDetails.classList.add('hidden');
                eligibilityDetails.classList.add('hidden');
                guaranteeDetails.classList.add('hidden');
                return;
            }
            
            // Show/hide eligibility details
            if (accountTypeSelect.value) {
                const multiplier = parseFloat(selectedAccountType.dataset.factor);
                const balance = parseFloat(selectedAccount.dataset.balance);
                const maxLoan = balance * multiplier;
                
                maxLoanAmount.textContent = 'Ksh ' + maxLoan.toLocaleString('en-US');
                calculationFormula.textContent = `${balance.toLocaleString('en-US')} × ${multiplier}`;
                eligibilityDetails.classList.remove('hidden');
                
                // Set max attribute on amount input
                loanAmountInput.setAttribute('max', maxLoan);
                
                // Update guarantee calculations if loan amount is entered
                if (loanAmount > 0) {
                    updateGuaranteeCalculations(balance, loanAmount);
                }
            } else {
                eligibilityDetails.classList.add('hidden');
                guaranteeDetails.classList.add('hidden');
            }
        }

        // Update guarantee calculations
        function updateGuaranteeCalculations(availableBalance, loanAmount) {
            // Calculate self-guarantee (automatic - use full available balance up to loan amount)
            const selfGuarantee = Math.min(loanAmount, availableBalance);
            const remainingAmount = Math.max(0, loanAmount - selfGuarantee);
            const needGuarantors = remainingAmount > 0;

            // Build calculations HTML
            let calculationsHTML = `
                <div class="calculation-row">
                    <span>Loan Amount:</span>
                    <span>Ksh ${loanAmount.toLocaleString('en-US')}</span>
                </div>
                <div class="calculation-row">
                    <span>Available Balance (Self-Guarantee):</span>
                    <span>Ksh ${availableBalance.toLocaleString('en-US')}</span>
                </div>
                <div class="calculation-row">
                    <span>Applied Self-Guarantee:</span>
                    <span>Ksh ${selfGuarantee.toLocaleString('en-US')}</span>
                </div>
                <div class="calculation-row calculation-total">
                    <span>Remaining Amount:</span>
                    <span class="${needGuarantors ? 'text-danger' : 'text-success'}">
                        Ksh ${remainingAmount.toLocaleString('en-US')}
                    </span>
                </div>
            `;

            // Add guarantor requirement message
            if (needGuarantors) {
                calculationsHTML += `
                    <div class="alert alert-warning mt-3 mb-0">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <strong>Guarantors Required:</strong> You will need to add guarantors for the remaining Ksh ${remainingAmount.toLocaleString('en-US')}
                    </div>
                `;
            } else {
                calculationsHTML += `
                    <div class="alert alert-success mt-3 mb-0">
                        <i class="fas fa-check-circle me-2"></i>
                        <strong>Fully Covered:</strong> Your loan is fully covered by your available balance. No guarantors needed.
                    </div>
                `;
            }

            guaranteeCalculations.innerHTML = calculationsHTML;
            guaranteeDetails.classList.remove('hidden');
        }

        // Add event listeners
        savingsAccountSelect.addEventListener('change', updateCalculations);
        accountTypeSelect.addEventListener('change', updateCalculations);
        loanAmountInput.addEventListener('input', function() {
            const selectedAccount = savingsAccountSelect.options[savingsAccountSelect.selectedIndex];
            const loanAmount = parseFloat(this.value) || 0;
            
            if (selectedAccount && loanAmount > 0) {
                const balance = parseFloat(selectedAccount.dataset.balance);
                updateGuaranteeCalculations(balance, loanAmount);
            } else {
                guaranteeDetails.classList.add('hidden');
            }
        });

        // Form validation
        document.getElementById('loanForm').addEventListener('submit', function(e) {
            const loanAmount = parseFloat(loanAmountInput.value);
            const maxAmount = parseFloat(loanAmountInput.getAttribute('max')) || 0;
            
            if (loanAmount > maxAmount) {
                e.preventDefault();
                alert(`Loan amount cannot exceed your maximum eligibility of Ksh ${maxAmount.toLocaleString('en-US')}`);
                loanAmountInput.focus();
                return false;
            }
            
            if (loanAmount < 1000) {
                e.preventDefault();
                alert('Minimum loan amount is Ksh 1,000');
                loanAmountInput.focus();
                return false;
            }
            
            return true;
        });

        // Initialize calculations if values are pre-selected (for form re-display after error)
        document.addEventListener('DOMContentLoaded', function() {
            if (savingsAccountSelect.value || accountTypeSelect.value) {
                updateCalculations();
            }
            
            // If loan amount is already entered, trigger guarantee calculation
            if (loanAmountInput.value) {
                const selectedAccount = savingsAccountSelect.options[savingsAccountSelect.selectedIndex];
                if (selectedAccount) {
                    const balance = parseFloat(selectedAccount.dataset.balance);
                    const loanAmount = parseFloat(loanAmountInput.value);
                    updateGuaranteeCalculations(balance, loanAmount);
                }
            }
        });
    </script>
</body>
</html>