<?php
require_once './includes/session_init.php';
require_once 'includes/config.php';
require_once '../cbs.creativewebsolutions.co.ke/includes/sms_helper.php';
require_once '../cbs.creativewebsolutions.co.ke/includes/email_helper.php';

// Check if member is logged in and has an active loan application
if (!isset($_SESSION['member_id']) || !isset($_SESSION['loan_application'])) {
    header("Location: loan_application.php");
    exit();
}

$memberId = $_SESSION['member_id'];
$loanApp = $_SESSION['loan_application'];

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

// Get notification templates
try {
    $notificationTemplates = $pdo->query("
        SELECT type, template_name, template_sms, template_email 
        FROM notification_templates 
        WHERE type IN ('guarantor_request', 'guarantors_added')
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    // Prepare templates
    $templates = [];
    foreach ($notificationTemplates as $template) {
        $templates[$template['type']] = $template;
    }
} catch (PDOException $e) {
    error_log("Database error loading templates: " . $e->getMessage());
    $templates = [];
}

/**
 * Secure placeholder processing with context-aware sanitization
 */
function processMessagePlaceholders($message, $memberData, $context = 'email') {
    // Format dates
    $registration_date = !empty($memberData['registration_date']) ? date('jS F Y', strtotime($memberData['registration_date'])) : '';
    $application_date = !empty($memberData['application_date']) ? date('jS F Y', strtotime($memberData['application_date'])) : '';
    
    // Context-aware sanitization
    $sanitize = function($value, $context) {
        if ($context === 'email') {
            return htmlspecialchars($value ?? '', ENT_QUOTES, 'UTF-8');
        }
        // For SMS - remove line breaks and special chars that could cause SMS injection
        return preg_replace('/[\r\n]+/', ' ', $value ?? '');
    };
    
    $placeholders = [
        // Basic info
        '{id}' => $sanitize($memberData['id'] ?? '', $context),
        '{personal_number}' => $sanitize($memberData['personal_number'] ?? '', $context),
        '{member_number}' => $sanitize($memberData['member_number'] ?? '', $context),
        
        // Names
        '{first_name}' => $sanitize($memberData['first_name'] ?? '', $context),
        '{middle_name}' => $sanitize($memberData['middle_name'] ?? '', $context),
        '{last_name}' => $sanitize($memberData['last_name'] ?? '', $context),
        '{full_name}' => $sanitize(
            trim(($memberData['first_name'] ?? '') . ' ' . 
            ($memberData['middle_name'] ?? '') . ' ' . 
            ($memberData['last_name'] ?? '')), 
            $context
        ),
        
        // Contact info - additional validation
        '{phone_number}' => preg_replace('/[^0-9+]/', '', $memberData['phone_number'] ?? ''),
        '{email_address}' => filter_var($memberData['email_address'] ?? '', FILTER_SANITIZE_EMAIL),
        
        // Loan info - formatted numbers
        '{loan_number}' => $sanitize($memberData['loan_number'] ?? '', $context),
        '{loan_amount}' => isset($memberData['loan_amount']) ? 
            number_format((float)$memberData['loan_amount'], 2) : '0.00',
        '{guarantee_amount}' => isset($memberData['guarantee_amount']) ? 
            number_format((float)$memberData['guarantee_amount'], 2) : '0.00',
        '{application_date}' => $application_date,
        '{registration_date}' => $registration_date,
        
        // Current date/time
        '{current_date}' => date('jS F Y'),
        '{current_time}' => date('H:i'),
        '{today}' => date('jS F Y'),
        '{now}' => date('jS F Y H:i')
    ];
    
    return str_replace(
        array_keys($placeholders),
        array_values($placeholders),
        $message
    );
}

/**
 * Mask sensitive information for display
 */
function maskContactInfo($data, $type) {
    if (empty($data)) return 'Not provided';
    
    switch ($type) {
        case 'phone':
            // Keep first 3 and last 2 digits, mask the rest: +254712345678 -> +254******78
            if (strlen($data) >= 7) {
                $prefix = substr($data, 0, 4); // +254 or similar
                $suffix = substr($data, -2);
                return $prefix . '******' . $suffix;
            }
            return substr($data, 0, 4) . '******';
            
        case 'email':
            // Keep first 3 characters and domain: john.doe@example.com -> joh***@example.com
            $parts = explode('@', $data);
            if (count($parts) === 2) {
                $username = $parts[0];
                $domain = $parts[1];
                if (strlen($username) > 3) {
                    $maskedUsername = substr($username, 0, 3) . '***';
                } else {
                    $maskedUsername = substr($username, 0, 1) . '***';
                }
                return $maskedUsername . '@' . $domain;
            }
            return substr($data, 0, 3) . '***@****';
            
        default:
            return $data;
    }
}

/**
 * Enhanced notification function with validation and logging
 */
function sendLoanNotification($pdo, $memberId, $templateType, $loanData, $guaranteeAmount = null) {
    global $templates;
    
    // Get member details with additional validation
    $stmt = $pdo->prepare("
        SELECT 
            m.id, m.first_name, m.middle_name, m.last_name, 
            m.personal_number, m.phone_number, m.email_address, 
            m.communication_preference
        FROM members m
        WHERE m.id = ?
    ");
    $stmt->execute([$memberId]);
    $member = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$member) {
        error_log("Notification failed: Member $memberId not found");
        return false;
    }
    
    // Get template with validation
    $template = $templates[$templateType] ?? null;
    if (!$template) {
        error_log("Notification template $templateType not found");
        return false;
    }
    
    // Prepare data with additional validation
    $notificationData = array_merge($member, [
        'loan_number' => $loanData['loan_number'] ?? '',
        'loan_amount' => $loanData['loan_amount'] ?? 0,
        'application_date' => $loanData['application_date'] ?? date('Y-m-d H:i:s'),
        'guarantee_amount' => $guaranteeAmount
    ]);
    
    $results = [];
    $communicationPref = strtolower($member['communication_preference'] ?? 'both');
    
    // Process SMS notification
    if (($communicationPref === 'sms' || $communicationPref === 'both') && !empty($member['phone_number'])) {
        $phone = preg_replace('/[^0-9+]/', '', $member['phone_number']);
        if (preg_match('/^\+?[0-9]{10,15}$/', $phone)) {
            $smsContent = processMessagePlaceholders($template['template_sms'], $notificationData, 'sms');
            $smsContent = substr($smsContent, 0, 160); // Enforce SMS length limit
            
            try {
                $results['sms'] = sendSms($pdo, $phone, $smsContent);
                logNotification($pdo, $memberId, 'sms', $templateType, $results['sms']);
            } catch (Exception $e) {
                error_log("SMS send failed: " . $e->getMessage());
                $results['sms'] = false;
            }
        } else {
            error_log("Invalid phone number format for member $memberId");
        }
    }
    
    // Process Email notification
    if (($communicationPref === 'email' || $communicationPref === 'both') && !empty($member['email_address'])) {
        $email = filter_var($member['email_address'], FILTER_SANITIZE_EMAIL);
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailSubject = processMessagePlaceholders(
                "Loan Notification: #{loan_number}", 
                $notificationData,
                'email'
            );
            $emailContent = processMessagePlaceholders(
                $template['template_email'], 
                $notificationData,
                'email'
            );
            
            try {
                $results['email'] = sendEmail($email, $emailSubject, $emailContent);
                logNotification($pdo, $memberId, 'email', $templateType, $results['email']);
            } catch (Exception $e) {
                error_log("Email send failed: " . $e->getMessage());
                $results['email'] = false;
            }
        } else {
            error_log("Invalid email address for member $memberId");
        }
    }
    
    return $results;
}

/**
 * Log notification attempts
 */
function logNotification($pdo, $memberId, $channel, $templateType, $success) {
    try {
        $stmt = $pdo->prepare("
            INSERT INTO notification_logs 
            (member_id, channel, template_type, status, created_at)
            VALUES (?, ?, ?, ?, NOW())
        ");
        $stmt->execute([
            $memberId, 
            $channel, 
            $templateType, 
            $success ? 'sent' : 'failed'
        ]);
    } catch (PDOException $e) {
        error_log("Failed to log notification: " . $e->getMessage());
    }
}

// Handle AJAX requests for dynamic guarantors
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    switch ($_POST['action']) {
        case 'verify_guarantor':
            try {
                $memberNumber = trim($_POST['member_number']);
                $guaranteeAmount = (float)$_POST['guarantee_amount'];
                
                // Validate amount
                if ($guaranteeAmount < 100) {
                    echo json_encode(['success' => false, 'message' => 'Minimum guarantee amount is Ksh 100']);
                    exit;
                }
                
                // Verify guarantor exists and is not the applicant
                $stmt = $pdo->prepare("
                    SELECT id, first_name, last_name, email_address, phone_number, communication_preference 
                    FROM members 
                    WHERE personal_number = ? AND id != ?
                ");
                $stmt->execute([$memberNumber, $memberId]);
                $guarantor = $stmt->fetch();
                
                if (!$guarantor) {
                    echo json_encode(['success' => false, 'message' => "Member number $memberNumber not found or invalid"]);
                    exit;
                }
                
                // Verify guarantor has sufficient savings
                $stmt = $pdo->prepare("
                    SELECT a.id, a.available_balance, t.account_name
                    FROM member_accounts a
                    JOIN account_types t ON a.account_type_id = t.id
                    WHERE a.member_id = ? AND t.account_type = 'savings' AND a.available_balance >= ?
                    LIMIT 1
                ");
                $stmt->execute([$guarantor['id'], $guaranteeAmount]);
                $account = $stmt->fetch();
                
                if (!$account) {
                    echo json_encode([
                        'success' => false, 
                        'message' => "Member $memberNumber doesn't have sufficient savings to guarantee Ksh ".number_format($guaranteeAmount, 2)
                    ]);
                    exit;
                }
                
                echo json_encode([
                    'success' => true,
                    'guarantor' => [
                        'id' => $guarantor['id'],
                        'name' => $guarantor['first_name'].' '.$guarantor['last_name'],
                        'email' => maskContactInfo($guarantor['email_address'], 'email'),
                        'phone' => maskContactInfo($guarantor['phone_number'], 'phone'),
                        'available_balance' => $account['available_balance'],
                        'account_name' => $account['account_name']
                    ]
                ]);
            } catch (Exception $e) {
                echo json_encode(['success' => false, 'message' => 'Error verifying guarantor: ' . $e->getMessage()]);
            }
            exit;
            
        case 'add_guarantor':
            try {
                $memberNumber = trim($_POST['member_number']);
                $guaranteeAmount = (float)$_POST['guarantee_amount'];
                
                // Verify guarantor exists and is not the applicant
                $stmt = $pdo->prepare("
                    SELECT id, first_name, last_name, email_address, phone_number, communication_preference 
                    FROM members 
                    WHERE personal_number = ? AND id != ?
                ");
                $stmt->execute([$memberNumber, $memberId]);
                $guarantor = $stmt->fetch();
                
                if (!$guarantor) {
                    echo json_encode(['success' => false, 'message' => "Member number $memberNumber not found or invalid"]);
                    exit;
                }
                
                // Verify guarantor has sufficient savings
                $stmt = $pdo->prepare("
                    SELECT a.id, a.available_balance, t.account_name
                    FROM member_accounts a
                    JOIN account_types t ON a.account_type_id = t.id
                    WHERE a.member_id = ? AND t.account_type = 'savings' AND a.available_balance >= ?
                    LIMIT 1
                ");
                $stmt->execute([$guarantor['id'], $guaranteeAmount]);
                $account = $stmt->fetch();
                
                if (!$account) {
                    echo json_encode([
                        'success' => false, 
                        'message' => "Member $memberNumber doesn't have sufficient savings to guarantee Ksh ".number_format($guaranteeAmount, 2)
                    ]);
                    exit;
                }
                
                // Add to session
                if (!isset($_SESSION['temp_guarantors'])) {
                    $_SESSION['temp_guarantors'] = [];
                }
                
                $guarantorData = [
                    'id' => $guarantor['id'],
                    'member_number' => $memberNumber,
                    'name' => $guarantor['first_name'].' '.$guarantor['last_name'],
                    'email' => maskContactInfo($guarantor['email_address'], 'email'),
                    'phone' => maskContactInfo($guarantor['phone_number'], 'phone'),
                    'amount' => $guaranteeAmount,
                    'account_id' => $account['id'],
                    'account_name' => $account['account_name'],
                    'available_balance' => $account['available_balance']
                ];
                
                $_SESSION['temp_guarantors'][] = $guarantorData;
                
                echo json_encode(['success' => true, 'guarantors' => $_SESSION['temp_guarantors']]);
            } catch (Exception $e) {
                echo json_encode(['success' => false, 'message' => 'Error adding guarantor: ' . $e->getMessage()]);
            }
            exit;
            
        case 'remove_guarantor':
            try {
                $index = (int)$_POST['index'];
                
                if (isset($_SESSION['temp_guarantors'][$index])) {
                    array_splice($_SESSION['temp_guarantors'], $index, 1);
                    echo json_encode(['success' => true, 'guarantors' => $_SESSION['temp_guarantors']]);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Guarantor not found']);
                }
            } catch (Exception $e) {
                echo json_encode(['success' => false, 'message' => 'Error removing guarantor: ' . $e->getMessage()]);
            }
            exit;
            
        case 'get_guarantors':
            echo json_encode([
                'success' => true, 
                'guarantors' => $_SESSION['temp_guarantors'] ?? []
            ]);
            exit;
    }
}
// Process final guarantor submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_guarantors'])) {
    try {
        // Verify CSRF token
        if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
            throw new Exception("Invalid form submission");
        }

        $pdo->beginTransaction();

        $totalGuaranteed = 0;
        $guarantors = $_SESSION['temp_guarantors'] ?? [];
        $loanApp = $_SESSION['loan_application'] ?? null;

        if (!$loanApp) {
            throw new Exception("Missing loan application data.");
        }

        // ✅ 1. DO NOT update or deduct loanee's balance here
        // ✅ 2. DO NOT insert self-guarantee into loan_guarantors table
        // Self-guarantee will be handled at disbursement stage

        // ✅ 3. Process external guarantors (unchanged logic)
        foreach ($guarantors as $guarantor) {
            $totalGuaranteed += $guarantor['amount'];

            // Record guarantor relationship
            $stmt = $pdo->prepare("
                INSERT INTO loan_guarantors 
                (loan_id, guarantor_member_id, requested_amount, savings_account_id, 
                 added_by, status, original_balance, created_at)
                VALUES (?, ?, ?, ?, ?, 'pending', ?, NOW())
            ");
            $stmt->execute([
                $loanApp['loan_id'],
                $guarantor['id'],
                $guarantor['amount'],
                $guarantor['account_id'],
                $memberId,
                $guarantor['available_balance']
            ]);

            // Notify guarantor
            $loanData = [
                'loan_number' => $loanApp['loan_number'],
                'loan_amount' => $loanApp['loan_amount'],
                'application_date' => date('Y-m-d H:i:s')
            ];
            sendLoanNotification(
                $pdo,
                $guarantor['id'],
                'guarantor_request',
                $loanData,
                $guarantor['amount']
            );
        }

        // ✅ 4. Verify guarantor requirements
        if ($loanApp['need_guarantors'] && count($guarantors) === 0) {
            throw new Exception("You need at least one guarantor for this loan.");
        }

        $selfGuaranteeAmount = $loanApp['self_guarantee_amount'] ?? 0;
        $totalCoverage = $selfGuaranteeAmount + $totalGuaranteed;

        if ($totalCoverage < $loanApp['loan_amount']) {
            throw new Exception("Insufficient coverage. You need additional Ksh " . 
                number_format($loanApp['loan_amount'] - $totalCoverage, 2));
        }

        // ✅ 5. Update loan details (no balance deduction yet)
        $stmt = $pdo->prepare("
            UPDATE loans 
            SET status = 'pending',
                total_guaranteed_amount = ?,
                self_guaranteed_amount = ?,
                guarantor_count = ?
            WHERE id = ? AND status = 'pending'
        ");
        $stmt->execute([
            $totalGuaranteed,
            $selfGuaranteeAmount,
            count($guarantors),
            $loanApp['loan_id']
        ]);

        // ✅ 6. Notify applicant
        sendLoanNotification(
            $pdo,
            $memberId,
            'guarantors_added',
            [
                'loan_number' => $loanApp['loan_number'],
                'loan_amount' => $loanApp['loan_amount'],
                'application_date' => date('Y-m-d H:i:s'),
                'guarantor_count' => count($guarantors)
            ]
        );

        $pdo->commit();

        // ✅ 7. Clean up and redirect
        unset($_SESSION['loan_application'], $_SESSION['temp_guarantors']);
        $_SESSION['success'] = "Loan application submitted successfully! Guarantor requests sent for approval.";
        header("Location: loan_status.php?id=" . $loanApp['loan_id']);
        exit();

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


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

// Initialize temp guarantors if not set
if (!isset($_SESSION['temp_guarantors'])) {
    $_SESSION['temp_guarantors'] = [];
}

// Get data from session storage
$loanAmount = $loanApp['loan_amount'] ?? 0;
$selfGuaranteeAmount = $loanApp['self_guarantee_amount'] ?? 0;
$availableBalance = $loanApp['available_balance'] ?? 0;
$remainingAmount = $loanApp['remaining_amount'] ?? 0;
$needGuarantors = $loanApp['need_guarantors'] ?? false;
$accountName = $loanApp['account_name'] ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Specify Guarantors</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>
        .guarantor-box {
            background-color: #f8f9fa;
            border-radius: 5px;
            padding: 20px;
            margin-bottom: 20px;
            border-left: 4px solid #0d6efd;
            transition: all 0.3s ease;
        }
        .guarantor-box:hover {
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1);
        }
        .form-container {
            max-width: 800px;
            margin: 0 auto;
        }
        .coverage-display {
            font-size: 1.1rem;
            padding: 10px;
            border-radius: 5px;
        }
        .coverage-good {
            background-color: #d1e7dd;
            color: #0f5132;
        }
        .coverage-warning {
            background-color: #fff3cd;
            color: #664d03;
        }
        .guarantor-item {
            background-color: #f8f9fa;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 10px;
            border-left: 4px solid #28a745;
        }
        .guarantor-item-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .guarantor-actions {
            display: flex;
            gap: 10px;
        }
        #guarantorsList {
            max-height: 400px;
            overflow-y: auto;
        }
        .self-guarantee-box {
            background-color: #e7f3ff;
            border-left: 4px solid #0d6efd;
        }
        .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-user-friends me-2"></i>Specify Guarantors</h3>
                </div>
                
                <div class="card-body">
                    <?php if ($error): ?>
                        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
                    <?php endif; ?>
                    
                    <div class="alert alert-info mb-4">
                        <div class="d-flex align-items-center">
                            <i class="fas fa-info-circle fa-2x me-3"></i>
                            <div>
                                <h5 class="mb-1">Loan Application Details</h5>
                                <p class="mb-1">Loan Number: <strong><?= htmlspecialchars($loanApp['loan_number']) ?></strong></p>
                                <p class="mb-1">Amount: <strong>Ksh <?= number_format($loanAmount, 2) ?></strong></p>
                                <p class="mb-1">Account: <strong><?= htmlspecialchars($accountName) ?></strong></p>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Self Guarantee Section (Read from Session) -->
                    <div class="guarantor-box self-guarantee-box mb-4">
                        <h5><i class="fas fa-user me-2"></i>Self Guarantee (Auto-Applied)</h5>
                        <div id="selfGuaranteeCalculations">
                            <div class="calculation-row">
                                <span>Available Balance:</span>
                                <span>Ksh <?= number_format($availableBalance, 2) ?></span>
                            </div>
                            <div class="calculation-row">
                                <span>Applied Self-Guarantee:</span>
                                <span>Ksh <?= number_format($selfGuaranteeAmount, 2) ?></span>
                            </div>
                            <div class="calculation-row calculation-total">
                                <span>Remaining Amount:</span>
                                <span class="<?= $remainingAmount > 0 ? 'text-danger' : 'text-success' ?>">
                                    Ksh <?= number_format($remainingAmount, 2) ?>
                                </span>
                            </div>
                        </div>
                        <div class="mt-3">
                            <small class="text-muted">
                                <i class="fas fa-info-circle me-1"></i>
                                Your available balance has been automatically applied as self-guarantee.
                            </small>
                        </div>
                    </div>
                    
                    <div class="alert <?= $remainingAmount > 0 ? 'alert-warning' : 'alert-success' ?> mb-4">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <i class="fas fa-<?= $remainingAmount > 0 ? 'exclamation-triangle' : 'check-circle' ?> me-2"></i>
                                <span id="coverage-status">
                                    <?= $remainingAmount > 0 ? 
                                        'Additional Guarantee Needed: Ksh '.number_format($remainingAmount, 2) : 
                                        'Your loan is fully covered!' ?>
                                </span>
                            </div>
                            <div id="remaining-display" class="coverage-display <?= $remainingAmount > 0 ? 'coverage-warning' : 'coverage-good' ?>">
                                <?= $remainingAmount > 0 ? 
                                    'Remaining: Ksh '.number_format($remainingAmount, 2) : 
                                    'Fully Covered' ?>
                            </div>
                        </div>
                    </div>

                    <?php if ($needGuarantors): ?>
                    <div class="mb-4">
                        <h5><i class="fas fa-question-circle me-2"></i>How Guarantors Work</h5>
                        <ul>
                            <li>Guarantors must be existing members with sufficient savings</li>
                            <li>Each guarantor will receive a notification to approve the request</li>
                            <li>The guaranteed amount will be held in their account until loan repayment</li>
                            <li>Minimum guarantee amount is Ksh 100</li>
                            <li>Guarantors must have sufficient available balance</li>
                            <li>You can add or remove guarantors as needed</li>
                            <li>Contact information is masked for data protection</li>
                        </ul>
                    </div>
                    
                    <!-- Add Guarantor Form -->
                    <div class="guarantor-box mb-4">
                        <h5><i class="fas fa-user-plus me-2"></i>Add New Guarantor</h5>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Member Number <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-id-card"></i></span>
                                    <input type="text" id="guarantor_member_number" class="form-control" 
                                           placeholder="Enter member's personal number" pattern="[A-Za-z0-9]+" title="Alphanumeric characters only">
                                </div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Amount to Guarantee (Ksh) <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <span class="input-group-text">Ksh</span>
                                    <input type="number" id="guarantor_amount" class="form-control" 
                                           min="100" step="100" placeholder="Enter amount" max="<?= $remainingAmount ?>">
                                </div>
                                <small class="text-muted">Minimum: Ksh 100 | Maximum: Ksh <?= number_format($remainingAmount, 2) ?></small>
                            </div>
                        </div>
                        <div class="d-flex gap-2">
                            <button type="button" id="verifyGuarantor" class="btn btn-outline-primary">
                                <i class="fas fa-search me-2"></i>Verify Guarantor
                            </button>
                            <button type="button" id="addGuarantor" class="btn btn-success" disabled>
                                <i class="fas fa-plus me-2"></i>Add Guarantor
                            </button>
                        </div>
                        <div id="verificationResult" class="mt-3"></div>
                    </div>
                    
                    <!-- Guarantors List -->
                    <div class="mb-4">
                        <h5><i class="fas fa-list me-2"></i>Current Guarantors</h5>
                        <div id="guarantorsList">
                            <div id="noGuarantorsMessage" class="text-center py-4 text-muted">
                                <i class="fas fa-users fa-2x mb-2"></i>
                                <p>No guarantors added yet. Use the form above to add guarantors.</p>
                            </div>
                        </div>
                    </div>
                    <?php else: ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle me-2"></i>
                        <strong>No Guarantors Needed:</strong> Your loan is fully covered by your available balance.
                    </div>
                    <?php endif; ?>
                    
                    <!-- Submit Form -->
                    <form method="POST" id="guarantorForm">
                        <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                        <input type="hidden" id="guarantorsData" name="guarantors_data">
                        
                        <div class="d-grid gap-2 d-md-flex justify-content-md-end mt-4">
                            <a href="loan_application.php" class="btn btn-secondary me-md-2">
                                <i class="fas fa-arrow-left me-2"></i>Back
                            </a>
                            <?php if ($needGuarantors): ?>
                            <button type="submit" name="submit_guarantors" class="btn btn-primary" id="submitButton" disabled>
                                <i class="fas fa-paper-plane me-2"></i>Submit Guarantor Requests
                            </button>
                            <?php else: ?>
                            <a href="loan_status.php" class="btn btn-success">
                                <i class="fas fa-check me-2"></i>View Loan Status
                            </a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <?php include './partials/layouts/layoutBottom.php'; ?>
    
    
    <script>
        let guarantors = [];
        const selfGuaranteeAmount = <?= $selfGuaranteeAmount ?>;
        const loanAmount = <?= $loanAmount ?>;
        const remainingAmount = <?= $remainingAmount ?>;
        const needGuarantors = <?= $needGuarantors ? 'true' : 'false' ?>;
        
        // Load existing guarantors from session
        function loadGuarantors() {
            if (!needGuarantors) return;
            
            fetch('?', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=get_guarantors'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    guarantors = data.guarantors;
                    updateGuarantorsList();
                    updateCoverage();
                    updateSubmitButton();
                }
            })
            .catch(error => console.error('Error loading guarantors:', error));
        }
        
        // Update guarantors list display
        function updateGuarantorsList() {
            const list = document.getElementById('guarantorsList');
            const noGuarantorsMessage = document.getElementById('noGuarantorsMessage');
            
            if (guarantors.length === 0) {
                list.innerHTML = '<div id="noGuarantorsMessage" class="text-center py-4 text-muted"><i class="fas fa-users fa-2x mb-2"></i><p>No guarantors added yet. Use the form above to add guarantors.</p></div>';
                return;
            }
            
            noGuarantorsMessage?.remove();
            
            list.innerHTML = guarantors.map((guarantor, index) => `
                <div class="guarantor-item">
                    <div class="guarantor-item-header">
                        <div>
                            <h6 class="mb-1">${guarantor.name}</h6>
                            <p class="mb-1 text-muted">Member #: ${guarantor.member_number}</p>
                            <p class="mb-1">Amount: <strong>Ksh ${parseFloat(guarantor.amount).toLocaleString()}</strong></p>
                            <p class="mb-1 text-muted">Phone: ${guarantor.phone}</p>
                            <p class="mb-0 text-muted">Email: ${guarantor.email}</p>
                        </div>
                        <div class="guarantor-actions">
                            <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeGuarantor(${index})">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                </div>
            `).join('');
        }
        
        // Verify guarantor
        document.getElementById('verifyGuarantor')?.addEventListener('click', function() {
            const memberNumber = document.getElementById('guarantor_member_number').value.trim();
            const amount = parseFloat(document.getElementById('guarantor_amount').value);
            const resultDiv = document.getElementById('verificationResult');
            
            if (!memberNumber || !amount || amount < 100) {
                resultDiv.innerHTML = '<div class="alert alert-warning">Please enter a valid member number and amount (minimum Ksh 100)</div>';
                return;
            }
            
            if (amount > remainingAmount) {
                resultDiv.innerHTML = `<div class="alert alert-warning">Guarantee amount cannot exceed remaining amount of Ksh ${remainingAmount.toLocaleString()}</div>`;
                return;
            }
            
            // Check if guarantor is already added
            if (guarantors.some(g => g.member_number === memberNumber)) {
                resultDiv.innerHTML = '<div class="alert alert-warning">This member is already added as a guarantor</div>';
                return;
            }
            
            resultDiv.innerHTML = '<div class="alert alert-info">Verifying guarantor...</div>';
            
            fetch('?', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `action=verify_guarantor&member_number=${encodeURIComponent(memberNumber)}&guarantee_amount=${amount}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    resultDiv.innerHTML = `
                        <div class="alert alert-success">
                            <strong>Guarantor Verified!</strong><br>
                            Name: ${data.guarantor.name}<br>
                            Email: ${data.guarantor.email}<br>
                            Phone: ${data.guarantor.phone}<br>
                            Available Balance: Ksh ${parseFloat(data.guarantor.available_balance).toLocaleString()}<br>
                            Account: ${data.guarantor.account_name}
                        </div>
                    `;
                    document.getElementById('addGuarantor').disabled = false;
                } else {
                    resultDiv.innerHTML = `<div class="alert alert-danger">${data.message}</div>`;
                    document.getElementById('addGuarantor').disabled = true;
                }
            })
            .catch(error => {
                resultDiv.innerHTML = '<div class="alert alert-danger">Error verifying guarantor</div>';
                console.error('Error:', error);
            });
        });
        
        // Add guarantor
        document.getElementById('addGuarantor')?.addEventListener('click', function() {
            const memberNumber = document.getElementById('guarantor_member_number').value.trim();
            const amount = parseFloat(document.getElementById('guarantor_amount').value);
            
            fetch('?', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `action=add_guarantor&member_number=${encodeURIComponent(memberNumber)}&guarantee_amount=${amount}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    guarantors = data.guarantors;
                    updateGuarantorsList();
                    updateCoverage();
                    updateSubmitButton();
                    
                    // Reset form
                    document.getElementById('guarantor_member_number').value = '';
                    document.getElementById('guarantor_amount').value = '';
                    document.getElementById('verificationResult').innerHTML = '';
                    document.getElementById('addGuarantor').disabled = true;
                } else {
                    document.getElementById('verificationResult').innerHTML = `<div class="alert alert-danger">${data.message}</div>`;
                }
            })
            .catch(error => {
                document.getElementById('verificationResult').innerHTML = '<div class="alert alert-danger">Error adding guarantor</div>';
                console.error('Error:', error);
            });
        });
        
        // Remove guarantor
        function removeGuarantor(index) {
            if (!confirm('Are you sure you want to remove this guarantor?')) {
                return;
            }
            
            fetch('?', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `action=remove_guarantor&index=${index}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    guarantors = data.guarantors;
                    updateGuarantorsList();
                    updateCoverage();
                    updateSubmitButton();
                } else {
                    alert('Error removing guarantor: ' + data.message);
                }
            })
            .catch(error => {
                alert('Error removing guarantor');
                console.error('Error:', error);
            });
        }
        
        // Calculate total guaranteed amount
        function updateCoverage() {
            let totalGuaranteed = 0;
            guarantors.forEach(guarantor => {
                totalGuaranteed += parseFloat(guarantor.amount) || 0;
            });
            
            const totalCoverage = selfGuaranteeAmount + totalGuaranteed;
            const newRemainingAmount = Math.max(0, loanAmount - totalCoverage);
            
            const coverageStatus = document.getElementById('coverage-status');
            const remainingDisplay = document.getElementById('remaining-display');
            
            if (newRemainingAmount <= 0) {
                coverageStatus.textContent = 'Your loan is fully covered!';
                remainingDisplay.textContent = 'Fully Covered';
                remainingDisplay.className = 'coverage-display coverage-good';
                coverageStatus.parentElement.parentElement.className = 'alert alert-success';
            } else {
                coverageStatus.textContent = 'Additional Guarantee Needed: Ksh ' + newRemainingAmount.toLocaleString();
                remainingDisplay.textContent = 'Remaining: Ksh ' + newRemainingAmount.toLocaleString();
                remainingDisplay.className = 'coverage-display coverage-warning';
                coverageStatus.parentElement.parentElement.className = 'alert alert-warning';
            }
        }
        
        // Update submit button state
        function updateSubmitButton() {
            let totalGuaranteed = 0;
            
            guarantors.forEach(guarantor => {
                totalGuaranteed += parseFloat(guarantor.amount) || 0;
            });
            
            const totalCoverage = selfGuaranteeAmount + totalGuaranteed;
            const newRemainingAmount = loanAmount - totalCoverage;
            const submitButton = document.getElementById('submitButton');
            
            if (submitButton) {
                if (newRemainingAmount <= 0) {
                    submitButton.disabled = false;
                } else {
                    submitButton.disabled = true;
                }
            }
        }
        
        // Form validation
        document.getElementById('guarantorForm')?.addEventListener('submit', function(e) {
            let totalGuaranteed = 0;
            
            guarantors.forEach(guarantor => {
                totalGuaranteed += parseFloat(guarantor.amount) || 0;
            });
            
            const totalCoverage = selfGuaranteeAmount + totalGuaranteed;
            const newRemainingAmount = loanAmount - totalCoverage;
            
            if (newRemainingAmount > 0) {
                e.preventDefault();
                alert(`Insufficient guarantor coverage. You still need Ksh ${newRemainingAmount.toLocaleString()}`);
                return false;
            }
            
            // Store guarantors in hidden field for form submission
            document.getElementById('guarantorsData').value = JSON.stringify(guarantors);
        });
        
        // Initialize
        document.addEventListener('DOMContentLoaded', function() {
            if (needGuarantors) {
                loadGuarantors();
                updateCoverage();
            }
        });
    </script>
</body>
</html>