<?php
ini_set('display_errors', 1);
ini_set('log_errors', 1);
error_reporting(E_ALL);
// guarantor-requests-api.php - REST API for Guarantor Requests management

// Load CORS configuration FIRST
require_once __DIR__ . '/includes/cors.php';
configureCors();

// Load environment variables
require_once __DIR__ . '/includes/config_loader.php';

// Load dependencies
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/auth_functions.php';
require_once __DIR__ . '/includes/sms_helper.php';
require_once __DIR__ . '/auth/AuditLogger.php';
require_once __DIR__ . '/auth/JWTManager.php';
require_once __DIR__ . '/includes/internal_notification_helper.php';

// Load PhpMailer for email
require_once __DIR__ . '/vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Verify PDO connection exists and is valid
if (!isset($pdo) || !($pdo instanceof PDO)) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Database connection not properly initialized'
    ]);
    exit();
}

// Set response headers
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

// Security headers
header('X-Frame-Options: DENY');
header('X-Content-Type-Options: nosniff');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');

// Generate CSRF token for session if not exists
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// ============================================
// AUTHENTICATION
// ============================================

// Check if user is logged in
if (!isset($_SESSION['member_id'])) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'error' => 'Authentication required',
        'code' => 'UNAUTHORIZED'
    ]);
    exit();
}

$memberId = (int)$_SESSION['member_id'];
$userRole = $_SESSION['role'] ?? 'member';

// ============================================
// EMAIL AND SMS FUNCTIONS
// ============================================

/**
 * Get SMTP settings from JSON file or database
 */
function getGuarantorSmtpSettings() {
    global $pdo;
    
    // Try JSON file first
    $jsonFilePath = __DIR__ . '/smtp_settings_data.json';
    
    if (file_exists($jsonFilePath)) {
        $json = file_get_contents($jsonFilePath);
        $settings = json_decode($json, true);
        
        if (json_last_error() === JSON_ERROR_NONE && !empty($settings['smtp_host'])) {
            return $settings;
        }
    }
    
    // Fallback to database
    try {
        $stmt = $pdo->query("SELECT * FROM email_settings LIMIT 1");
        $dbSettings = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($dbSettings) {
            return [
                'smtp_host' => $dbSettings['smtp_host'],
                'smtp_username' => $dbSettings['smtp_username'],
                'smtp_password' => $dbSettings['smtp_password'],
                'smtp_port' => $dbSettings['smtp_port'],
                'smtp_encryption' => $dbSettings['smtp_encryption'],
                'from_name' => $dbSettings['from_name']
            ];
        }
    } catch (Exception $e) {
        error_log("Database SMTP settings failed: " . $e->getMessage());
    }
    
    // Return default settings for development
    return [
        'smtp_host' => 'smtp.gmail.com',
        'smtp_username' => '',
        'smtp_password' => '',
        'smtp_port' => 587,
        'smtp_encryption' => 'tls',
        'from_name' => 'Guarantor System'
    ];
}

/**
 * Send OTP email using PHPMailer
 */
function sendGuarantorOTPEmail($recipientEmail, $firstName, $otp, $action) {
    try {
        $smtpSettings = getGuarantorSmtpSettings();
        
        if (empty($smtpSettings['smtp_username']) || empty($smtpSettings['smtp_password'])) {
            error_log("SMTP not configured: Missing credentials");
            return false;
        }
        
        $mail = new PHPMailer(true);
        
        // Server settings
        $mail->isSMTP();
        $mail->Host = $smtpSettings['smtp_host'];
        $mail->SMTPAuth = true;
        $mail->Username = $smtpSettings['smtp_username'];
        $mail->Password = $smtpSettings['smtp_password'];
        $mail->SMTPSecure = $smtpSettings['smtp_encryption'];
        $mail->Port = $smtpSettings['smtp_port'];
        
        // Disable SSL verification for testing (remove in production)
        $mail->SMTPOptions = array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );
        
        $mail->setFrom($smtpSettings['smtp_username'], $smtpSettings['from_name'] ?? 'Guarantor System');
        $mail->addAddress($recipientEmail);
        
        $actionText = $action === 'guarantor_approve' ? 'APPROVE' : 'DECLINE';
        
        $mail->isHTML(true);
        $mail->Subject = "Guarantor Request - OTP Verification Required";
        $mail->Body = "
            <html>
            <head>
                <style>
                    body { font-family: Arial, sans-serif; }
                    .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                    .header { background-color: #4CAF50; color: white; padding: 10px; text-align: center; }
                    .otp-code { font-size: 32px; font-weight: bold; color: #4CAF50; text-align: center; padding: 20px; }
                    .footer { font-size: 12px; color: #666; text-align: center; margin-top: 20px; }
                </style>
            </head>
            <body>
                <div class='container'>
                    <div class='header'>
                        <h2>Guarantor Request Verification</h2>
                    </div>
                    <p>Dear {$firstName},</p>
                    <p>You have requested to <strong>{$actionText}</strong> a guarantor request. Please use the following OTP code to complete this action:</p>
                    <div class='otp-code'>{$otp}</div>
                    <p>This OTP code is valid for <strong>15 minutes</strong>.</p>
                    <p>If you did not initiate this request, please ignore this email or contact support.</p>
                    <div class='footer'>
                        <p>This is an automated message, please do not reply to this email.</p>
                    </div>
                </div>
            </body>
            </html>
        ";
        
        $mail->AltBody = "Dear {$firstName},\n\nYou have requested to {$actionText} a guarantor request. Your OTP code is: {$otp}\n\nThis code is valid for 15 minutes.\n\nIf you did not initiate this request, please ignore this message.";
        
        return $mail->send();
        
    } catch (Exception $e) {
        error_log("OTP Email Failed: " . $e->getMessage());
        return false;
    }
}

/**
 * Send OTP SMS
 */
function sendGuarantorOTPSMS($phoneNumber, $otp, $action) {
    try {
        if (empty($phoneNumber)) {
            error_log("No phone number provided for SMS");
            return false;
        }
        
        $actionText = $action === 'guarantor_approve' ? 'APPROVE' : 'DECLINE';
        $message = "Your OTP code to $actionText guarantor request is: $otp. Valid for 15 minutes.";
        
        // Use existing sendSms function
        if (function_exists('sendSms')) {
            global $pdo;
            return sendSms($pdo, $phoneNumber, $message);
        } else {
            error_log("sendSms function not available");
            return false;
        }
        
    } catch (Exception $e) {
        error_log("OTP SMS Failed: " . $e->getMessage());
        return false;
    }
}

/**
 * Generate and store OTP
 */
function generateAndStoreOTP($memberId, $action) {
    global $pdo;
    
    try {
        // Generate 6-digit OTP
        $otp = sprintf("%06d", mt_rand(0, 999999));
        $expiresAt = date('Y-m-d H:i:s', strtotime('+15 minutes'));
        
        // Clean up old OTPs for this member and action
        $cleanupStmt = $pdo->prepare("
            DELETE FROM otp_verifications 
            WHERE member_id = ? AND action = ? AND used = 0 AND expires_at < NOW()
        ");
        $cleanupStmt->execute([$memberId, $action]);
        
        // Store new OTP
        $stmt = $pdo->prepare("
            INSERT INTO otp_verifications (member_id, otp_code, action, expires_at, created_at) 
            VALUES (?, ?, ?, ?, NOW())
        ");
        $stmt->execute([$memberId, $otp, $action, $expiresAt]);
        
        return [
            'success' => true,
            'otp' => $otp,
            'expires_at' => $expiresAt
        ];
        
    } catch (PDOException $e) {
        error_log("Failed to generate OTP: " . $e->getMessage());
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

/**
 * Verify OTP
 */
function verifyStoredOTP($memberId, $otp, $action) {
    global $pdo;
    
    try {
        $stmt = $pdo->prepare("
            SELECT id, expires_at 
            FROM otp_verifications 
            WHERE member_id = ? AND otp_code = ? AND action = ? 
            AND used = 0 
            AND expires_at > NOW()
            ORDER BY created_at DESC 
            LIMIT 1
        ");
        $stmt->execute([$memberId, $otp, $action]);
        $otpRecord = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$otpRecord) {
            error_log("OTP verification failed: No valid OTP found for member $memberId");
            return false;
        }
        
        // Mark OTP as used
        $stmt = $pdo->prepare("UPDATE otp_verifications SET used = 1, verified_at = NOW() WHERE id = ?");
        $stmt->execute([$otpRecord['id']]);
        
        return true;
        
    } catch (PDOException $e) {
        error_log("OTP verification error: " . $e->getMessage());
        return false;
    }
}

// ============================================
// HELPER FUNCTIONS
// ============================================

/**
 * Send OTP to guarantor using email/SMS
 */
function sendGuarantorOTP($memberId, $action, $requestId, $pdo) {
    try {
        // Get member details for OTP sending
        $stmt = $pdo->prepare("
            SELECT m.id as member_id, m.first_name, m.last_name, 
                   m.communication_preference, m.phone_number,
                   mp.email
            FROM members m
            LEFT JOIN member_portal_accounts mp ON m.id = mp.member_id
            WHERE m.id = ?
        ");
        $stmt->execute([$memberId]);
        $member = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$member) {
            throw new Exception("Member not found");
        }
        
        // Generate and store OTP
        $otpResult = generateAndStoreOTP($memberId, $action);
        if (!$otpResult['success']) {
            throw new Exception("Failed to generate OTP");
        }
        
        $otp = $otpResult['otp'];
        $preference = $member['communication_preference'] ?? 'both';
        $smsSent = false;
        $emailSent = false;
        
        // Send via SMS if preferred
        if (($preference === 'sms' || $preference === 'both') && !empty($member['phone_number'])) {
            $smsSent = sendGuarantorOTPSMS($member['phone_number'], $otp, $action);
            error_log("OTP SMS to {$member['phone_number']}: " . ($smsSent ? 'Success' : 'Failed'));
        }
        
        // Send via email if preferred
        if (($preference === 'email' || $preference === 'both') && !empty($member['email'])) {
            $emailSent = sendGuarantorOTPEmail($member['email'], $member['first_name'], $otp, $action);
            error_log("OTP Email to {$member['email']}: " . ($emailSent ? 'Success' : 'Failed'));
        }
        
        $sent = ($smsSent || $emailSent);
        
        if ($sent) {
            logSecurityEvent($memberId, 'guarantor_otp_sent', [
                'method' => $preference,
                'action' => $action,
                'request_id' => $requestId,
                'sms_sent' => $smsSent,
                'email_sent' => $emailSent
            ]);
            return true;
        } else {
            throw new Exception("Failed to send OTP via any method");
        }
        
    } catch (Exception $e) {
        error_log("Guarantor OTP sending error: " . $e->getMessage());
        logSecurityEvent($memberId, 'guarantor_otp_failed', [
            'error' => $e->getMessage(),
            'action' => $action,
            'request_id' => $requestId
        ]);
        return false;
    }
}

/**
 * Verify OTP using stored verification
 */
function verifyGuarantorOTP($memberId, $otp, $action, $requestId) {
    try {
        $verified = verifyStoredOTP($memberId, $otp, $action);
        
        if ($verified) {
            logSecurityEvent($memberId, 'guarantor_otp_verified', [
                'action' => $action,
                'request_id' => $requestId
            ]);
            return true;
        } else {
            logSecurityEvent($memberId, 'guarantor_otp_invalid', [
                'action' => $action,
                'request_id' => $requestId
            ]);
            return false;
        }
        
    } catch (Exception $e) {
        error_log("Guarantor OTP verification error: " . $e->getMessage());
        return false;
    }
}

/**
 * Get pending guarantor requests for member
 */
function getPendingGuarantorRequests($pdo, $memberId) {
    try {
        $sql = "
            SELECT 
                lg.id, 
                lg.loan_id, 
                lg.requested_amount,
                lg.guarantee_amount,
                lg.guarantor_request_status, 
                lg.status, 
                lg.created_at,
                l.loan_number, 
                l.loan_amount,
                m.first_name, 
                m.last_name, 
                m.personal_number,
                at.account_name as savings_account,
                ma.available_balance,
                m.communication_preference,
                mp.email,
                m.phone_number
            FROM loan_guarantors lg
            JOIN loans l ON lg.loan_id = l.id
            JOIN members m ON l.member_id = m.id
            JOIN member_accounts ma ON lg.savings_account_id = ma.id
            JOIN account_types at ON ma.account_type_id = at.id
            LEFT JOIN member_portal_accounts mp ON m.id = mp.member_id
            WHERE lg.guarantor_member_id = ? AND lg.guarantor_request_status = 'pending'
            ORDER BY lg.created_at DESC
        ";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$memberId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        error_log("Error fetching guarantor requests: " . $e->getMessage());
        return [];
    }
}

/**
 * Validate request ownership
 */
function validateRequestOwnership($requestId, $memberId, $pdo) {
    try {
        $stmt = $pdo->prepare("
            SELECT id FROM loan_guarantors 
            WHERE id = ? AND guarantor_member_id = ?
        ");
        $stmt->execute([$requestId, $memberId]);
        return $stmt->fetch() !== false;
    } catch (PDOException $e) {
        return false;
    }
}

/**
 * Validate guarantee amount
 */
function validateGuaranteeAmount($guaranteeAmount, $requestId, $memberId, $pdo) {
    try {
        $stmt = $pdo->prepare("
            SELECT 
                lg.requested_amount,
                ma.available_balance
            FROM loan_guarantors lg
            JOIN member_accounts ma ON lg.savings_account_id = ma.id
            WHERE lg.id = ? AND lg.guarantor_member_id = ? AND ma.member_id = ?
        ");
        $stmt->execute([$requestId, $memberId, $memberId]);
        $requestData = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$requestData) {
            return ['valid' => false, 'error' => 'Invalid request'];
        }
        
        $errors = [];
        
        if ($guaranteeAmount <= 0) {
            $errors[] = "Guarantee amount must be greater than zero";
        }
        
        if ($guaranteeAmount > $requestData['available_balance']) {
            $errors[] = "Guarantee amount cannot exceed your available balance (Ksh " . number_format($requestData['available_balance'], 2) . ")";
        }
        
        if ($guaranteeAmount > $requestData['requested_amount']) {
            $errors[] = "Guarantee amount cannot exceed the requested amount (Ksh " . number_format($requestData['requested_amount'], 2) . ")";
        }
        
        if (!empty($errors)) {
            return ['valid' => false, 'errors' => $errors];
        }
        
        return [
            'valid' => true,
            'data' => $requestData
        ];
    } catch (PDOException $e) {
        error_log("Error validating guarantee amount: " . $e->getMessage());
        return ['valid' => false, 'error' => 'Validation error'];
    }
}

/**
 * Get updated loan coverage summary
 */
function getLoanCoverageSummary($loanId, $pdo) {
    try {
        $stmt = $pdo->prepare("
            SELECT 
                l.loan_amount,
                l.self_guaranteed_amount,
                COALESCE(SUM(CASE WHEN lg.guarantor_request_status = 'approved' THEN lg.guarantee_amount ELSE 0 END), 0) as total_approved_guarantee,
                COUNT(CASE WHEN lg.guarantor_request_status = 'pending' THEN 1 END) as pending_count,
                COUNT(CASE WHEN lg.guarantor_request_status = 'approved' THEN 1 END) as approved_count,
                COUNT(CASE WHEN lg.guarantor_request_status = 'rejected' THEN 1 END) as rejected_count
            FROM loans l
            LEFT JOIN loan_guarantors lg ON l.id = lg.loan_id
            WHERE l.id = ?
            GROUP BY l.id
        ");
        $stmt->execute([$loanId]);
        $coverage = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$coverage) {
            return null;
        }
        
        $totalCoverage = ($coverage['self_guaranteed_amount'] ?? 0) + ($coverage['total_approved_guarantee'] ?? 0);
        $remainingAmount = max(0, $coverage['loan_amount'] - $totalCoverage);
        $percentageCovered = $coverage['loan_amount'] > 0 ? ($totalCoverage / $coverage['loan_amount']) * 100 : 0;
        
        return [
            'loan_amount' => $coverage['loan_amount'],
            'self_guaranteed' => $coverage['self_guaranteed_amount'] ?? 0,
            'total_guarantee_approved' => $coverage['total_approved_guarantee'],
            'total_coverage' => $totalCoverage,
            'remaining_amount' => $remainingAmount,
            'percentage_covered' => $percentageCovered,
            'pending_count' => $coverage['pending_count'] ?? 0,
            'approved_count' => $coverage['approved_count'] ?? 0,
            'rejected_count' => $coverage['rejected_count'] ?? 0,
            'is_fully_covered' => $totalCoverage >= $coverage['loan_amount']
        ];
    } catch (PDOException $e) {
        error_log("Error getting loan coverage summary: " . $e->getMessage());
        return null;
    }
}

/**
 * Send enhanced notifications about guarantor decision
 */
function sendGuarantorDecisionNotifications($guarantorId, $loanId, $action, $guaranteeAmount, $originalRequestedAmount, $pdo) {
    try {
        // Get comprehensive loan and applicant details
        $stmt = $pdo->prepare("
            SELECT 
                l.member_id, 
                l.loan_number, 
                l.loan_amount,
                l.status as loan_status,
                m.first_name, 
                m.last_name, 
                m.email_address, 
                m.phone_number,
                g.first_name as guarantor_first_name, 
                g.last_name as guarantor_last_name,
                g.phone_number as guarantor_phone,
                mp.email as guarantor_email
            FROM loans l
            JOIN members m ON l.member_id = m.id
            JOIN members g ON ? = g.id
            LEFT JOIN member_portal_accounts mp ON g.id = mp.member_id
            WHERE l.id = ?
        ");
        $stmt->execute([$guarantorId, $loanId]);
        $loanInfo = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$loanInfo) {
            throw new Exception("Loan information not found");
        }
        
        // Get updated coverage summary
        $coverageSummary = getLoanCoverageSummary($loanId, $pdo);
        
        if ($action === 'approve') {
            $isPartial = $guaranteeAmount < $originalRequestedAmount;
            $guarantorName = $loanInfo['guarantor_first_name'] . ' ' . $loanInfo['guarantor_last_name'];
            
            // Send detailed approval notification to loan applicant
            if (!empty($loanInfo['email_address'])) {
                sendDetailedApprovalEmail(
                    $loanInfo['email_address'],
                    $loanInfo['first_name'],
                    $loanInfo,
                    $guarantorName,
                    $guaranteeAmount,
                    $originalRequestedAmount,
                    $isPartial,
                    $coverageSummary
                );
            }
            
            // Send SMS notification -->> come back here mbeca
            if (!empty($loanInfo['phone_number'])) {
                sendDetailedApprovalSMS(
                    $loanInfo['phone_number'],
                    $loanInfo['first_name'],
                    $guarantorName,
                    $loanInfo['loan_number'],
                    $guaranteeAmount,
                    $originalRequestedAmount,
                    $isPartial
                );
            }
            
            $title = $isPartial ? "Partial Guarantor Approval" : "Guarantor Request Approved";
            $message = $isPartial 
                ? "{$guarantorName} has approved Ksh " . number_format($guaranteeAmount, 2) . " out of Ksh " . number_format($originalRequestedAmount, 2) . " requested for loan #{$loanInfo['loan_number']}."
                : "{$guarantorName} has fully approved your guarantor request of Ksh " . number_format($guaranteeAmount, 2) . " for loan #{$loanInfo['loan_number']}.";
            
        } else {
            // Send detailed rejection notification to loan applicant
            $guarantorName = $loanInfo['guarantor_first_name'] . ' ' . $loanInfo['guarantor_last_name'];
            
            if (!empty($loanInfo['email_address'])) {
                sendDetailedRejectionEmail(
                    $loanInfo['email_address'],
                    $loanInfo['first_name'],
                    $loanInfo,
                    $guarantorName,
                    $originalRequestedAmount,
                    $coverageSummary
                );
            }
            
            // Send rejection SMS
            if (!empty($loanInfo['phone_number'])) {
                sendDetailedRejectionSMS(
                    $loanInfo['phone_number'],
                    $loanInfo['first_name'],
                    $loanInfo['loan_number'],
                    $guarantorName
                );
            }
            
            $title = "Guarantor Request Rejected";
            $message = "{$guarantorName} has rejected your guarantor request for loan #{$loanInfo['loan_number']}. You need to find alternative guarantors.";
        }
        
        // Add internal notification with detailed summary
        $notificationMessage = $message;
        if ($coverageSummary && $coverageSummary['remaining_amount'] > 0) {
            $notificationMessage .= " Remaining amount to cover: Ksh " . number_format($coverageSummary['remaining_amount'], 2);
        }
        
        addInternalNotification(
            $pdo,
            $loanInfo['member_id'],
            $title,
            $notificationMessage,
            $action === 'approve' ? 'success' : 'warning',
            "loan_status.php?id=" . $loanId,
            $action === 'approve' ? 'carbon:checkmark' : 'carbon:warning'
        );
        
        return true;
        
    } catch (Exception $e) {
        error_log("Error sending guarantor notifications: " . $e->getMessage());
        return false;
    }
}

/**
 * Send detailed approval email with partial/full approval info
 */
function sendDetailedApprovalEmail(
    $recipientEmail,
    $firstName,
    $loanInfo,
    $guarantorName,
    $guaranteeAmount,
    $requestedAmount,
    $isPartial,
    $coverageSummary = null
) {
    try {
        $smtpSettings = getGuarantorSmtpSettings();

        if (empty($smtpSettings['smtp_username'])) {
            error_log("SMTP not configured for approval email");
            return false;
        }

        // -----------------------------
        // Initialize Mailer
        // -----------------------------
        $mail = new PHPMailer(true);

        $mail->isSMTP();
        $mail->Host       = $smtpSettings['smtp_host'];
        $mail->SMTPAuth   = true;
        $mail->Username   = $smtpSettings['smtp_username'];
        $mail->Password   = $smtpSettings['smtp_password'];

        // SMTP Encryption
        $mail->SMTPSecure = (
            ($smtpSettings['smtp_encryption'] ?? '') === 'ssl'
        )
            ? PHPMailer::ENCRYPTION_SMTPS
            : PHPMailer::ENCRYPTION_STARTTLS;

        $mail->Port = (int) $smtpSettings['smtp_port'];

        // SSL Options
        $mail->SMTPOptions = [
            'ssl' => [
                'verify_peer'       => false,
                'verify_peer_name'  => false,
                'allow_self_signed' => true
            ]
        ];

        // Sender & Recipient
        $mail->setFrom(
            $smtpSettings['smtp_username'],
            $smtpSettings['from_name'] ?? 'Loan System'
        );

        $mail->addAddress($recipientEmail);

        // -----------------------------
        // Safe Variables
        // -----------------------------
        $loanNumber      = $loanInfo['loan_number'] ?? 'N/A';
        $requestedAmount = (float) $requestedAmount;
        $guaranteeAmount = (float) $guaranteeAmount;

        $shortfallAmount = max(0, $requestedAmount - $guaranteeAmount);

        $statusColor = $isPartial ? '#FF9800' : '#4CAF50';
        $statusText  = $isPartial ? 'PARTIALLY APPROVED' : 'FULLY APPROVED';

        // -----------------------------
        // Partial / Full Approval Block
        // -----------------------------
        if ($isPartial) {

            $approvalMessage = "
                <div class='warning'>
                    <h3>Decision Summary:</h3>

                    <ul style='margin-bottom: 0;'>
                        <li><strong>Requested Amount:</strong> Ksh " . number_format($requestedAmount, 2) . "</li>
                        <li><strong>Approved Amount:</strong> Ksh " . number_format($guaranteeAmount, 2) . "</li>
                        <li><strong>Shortfall:</strong> Ksh " . number_format($shortfallAmount, 2) . "</li>
                    </ul>
                </div>

                <div class='info-box'>
                    <h4 style='margin-top:0;'>⚠️ Partial Approval Notice</h4>

                    <p>The guarantor approved only part of the requested amount.</p>

                    <ul>
                        <li>Find additional guarantors for the remaining amount</li>
                        <li>Increase your self-guarantee if possible</li>
                        <li>Or adjust your requested loan amount</li>
                    </ul>
                </div>
            ";

        } else {

            $approvalMessage = "
                <div class='success'>
                    <h3>Decision Summary:</h3>

                    <ul style='margin-bottom:0;'>
                        <li><strong>Requested Amount:</strong> Ksh " . number_format($requestedAmount, 2) . "</li>
                        <li><strong>Approved Amount:</strong> Ksh " . number_format($guaranteeAmount, 2) . "</li>
                    </ul>
                </div>

                <div class='success'>
                    <p><strong>✓ Good News!</strong> Your guarantor fully approved the request.</p>
                </div>
            ";
        }

        // -----------------------------
        // Coverage Summary
        // -----------------------------
        $coverageHtml = '';

        if (!empty($coverageSummary) && is_array($coverageSummary)) {

            $loanAmount        = (float) ($coverageSummary['loan_amount'] ?? 0);
            $totalCoverage     = (float) ($coverageSummary['total_coverage'] ?? 0);
            $remainingAmount   = (float) ($coverageSummary['remaining_amount'] ?? 0);
            $percentageCovered = min(
                100,
                (float) ($coverageSummary['percentage_covered'] ?? 0)
            );

            $remainingClass = $remainingAmount > 0
                ? 'text-warning'
                : 'text-success';

            $coverageHtml = "
                <div class='info-box'>
                    <h4 style='margin-top:0;'>📊 Updated Loan Coverage Status</h4>

                    <table style='width:100%; border-collapse:collapse;'>

                        <tr>
                            <td><strong>Total Loan Amount:</strong></td>
                            <td style='text-align:right;'>
                                Ksh " . number_format($loanAmount, 2) . "
                            </td>
                        </tr>

                        <tr>
                            <td><strong>Total Guaranteed:</strong></td>
                            <td style='text-align:right;'>
                                <strong>Ksh " . number_format($totalCoverage, 2) . "</strong>
                            </td>
                        </tr>

                        <tr>
                            <td><strong>Remaining to Cover:</strong></td>
                            <td class='{$remainingClass}' style='text-align:right;'>
                                <strong>Ksh " . number_format($remainingAmount, 2) . "</strong>
                            </td>
                        </tr>

                        <tr>
                            <td><strong>Coverage Percentage:</strong></td>

                            <td style='text-align:right;'>

                                <div style='background:#e0e0e0; border-radius:10px; overflow:hidden;'>

                                    <div style='
                                        background-color: {$statusColor};
                                        width: {$percentageCovered}%;
                                        height: 20px;
                                        line-height: 20px;
                                        text-align: center;
                                        color: white;
                                        font-size: 12px;
                                    '>

                                        " . number_format($percentageCovered, 1) . "%

                                    </div>

                                </div>

                            </td>
                        </tr>

                    </table>
                </div>
            ";
        }

        // -----------------------------
        // Next Steps
        // -----------------------------
        $nextSteps = '';

        if (
            !empty($coverageSummary) &&
            (($coverageSummary['remaining_amount'] ?? 0) > 0)
        ) {

            $nextSteps = "
                <li>Login to your account to review guarantor responses</li>
                <li>Find additional guarantors</li>
                <li>Increase self-guarantee if possible</li>
            ";

        } else {

            $nextSteps = "
                <li>✓ Your loan is fully guaranteed</li>
                <li>Your application will proceed for processing</li>
                <li>You will receive loan status updates</li>
            ";
        }

        // -----------------------------
        // Email Body
        // -----------------------------
        $mail->isHTML(true);

        $mail->Subject = "Guarantor Request Update - Loan #{$loanNumber}";

        $mail->Body = <<<HTML
        <html>

        <head>
            <style>

                body {
                    font-family: Arial, sans-serif;
                    line-height: 1.6;
                }

                .container {
                    max-width: 600px;
                    margin: 0 auto;
                    padding: 20px;
                }

                .header {
                    background-color: {$statusColor};
                    color: white;
                    padding: 20px;
                    text-align: center;
                    border-radius: 5px 5px 0 0;
                }

                .content {
                    padding: 20px;
                    background-color: #f9f9f9;
                    border: 1px solid #ddd;
                    border-top: none;
                    border-radius: 0 0 5px 5px;
                }

                .warning {
                    background-color: #FFF3E0;
                    border-left: 4px solid #FF9800;
                    padding: 10px;
                    margin: 15px 0;
                }

                .success {
                    background-color: #E8F5E9;
                    border-left: 4px solid #4CAF50;
                    padding: 10px;
                    margin: 15px 0;
                }

                .info-box {
                    background-color: #E3F2FD;
                    padding: 15px;
                    border-radius: 5px;
                    margin: 15px 0;
                }

                .text-warning {
                    color: #FF9800;
                }

                .text-success {
                    color: #4CAF50;
                }

                .footer {
                    margin-top: 20px;
                    text-align: center;
                    font-size: 12px;
                    color: #666;
                }

            </style>
        </head>

        <body>

            <div class="container">

                <div class="header">
                    <h2>Guarantor Request {$statusText}</h2>
                </div>

                <div class="content">

                    <p>
                        Dear <strong>{$firstName}</strong>,
                    </p>

                    <p>
                        <strong>{$guarantorName}</strong> has responded to your guarantor request
                        for loan <strong>#{$loanNumber}</strong>.
                    </p>

                    {$approvalMessage}

                    {$coverageHtml}

                    <div class="info-box">

                        <h4 style="margin-top:0;">📋 Next Steps</h4>

                        <ul>
                            {$nextSteps}
                        </ul>

                    </div>

                    <p>Thank you for using our services.</p>

                    <div class="footer">

                        <p>
                            This is an automated message. Please do not reply to this email.
                        </p>

                        <p>
                            If you have questions, contact our support team.
                        </p>

                    </div>

                </div>

            </div>

        </body>

        </html>
        HTML;

        return $mail->send();

    } catch (Exception $e) {

        error_log(
            "Detailed approval email failed: " . $e->getMessage()
        );

        return false;
    }
}
/**
 * Send detailed approval SMS --> mbeca
 */
function sendDetailedApprovalSMS($phoneNumber, $firstName,  $guarantorName, $loanNumber, $guaranteeAmount, $requestedAmount, $isPartial) {
    try {
        if ($isPartial) {
            $shortfall = $requestedAmount - $guaranteeAmount;
            $message = "Dear $firstName,  $guarantorName, has APPROVED Ksh " . number_format($guaranteeAmount, 2) . 
                      " out of Ksh " . number_format($requestedAmount, 2) . " requested for loan #$loanNumber. " .
                      "Shortfall: Ksh " . number_format($shortfall, 2) . ". Login to find more guarantors.";
        } else {
            $message = "Dear $firstName,  $guarantorName, has FULLY APPROVED Ksh " . number_format($guaranteeAmount, 2) . 
                      " for loan #$loanNumber. Login to check your loan status.";
        }
        
        if (function_exists('sendSms')) {
            global $pdo;
            return sendSms($pdo, $phoneNumber, $message);
        }
        return false;
        
    } catch (Exception $e) {
        error_log("Detailed approval SMS failed: " . $e->getMessage());
        return false;
    }
}

/**
 * Send detailed rejection email
 */
function sendDetailedRejectionEmail($recipientEmail, $firstName, $loanInfo, $guarantorName, $requestedAmount, $coverageSummary) {
    try {
        $smtpSettings = getGuarantorSmtpSettings();
        
        if (empty($smtpSettings['smtp_username'])) {
            return false;
        }
        
        $mail = new PHPMailer(true);
        $mail->isSMTP();
        $mail->Host = $smtpSettings['smtp_host'];
        $mail->SMTPAuth = true;
        $mail->Username = $smtpSettings['smtp_username'];
        $mail->Password = $smtpSettings['smtp_password'];
        $mail->SMTPSecure = $smtpSettings['smtp_encryption'];
        $mail->Port = $smtpSettings['smtp_port'];
        
        $mail->SMTPOptions = array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );
        
        $mail->setFrom($smtpSettings['smtp_username'], $smtpSettings['from_name'] ?? 'Loan System');
        $mail->addAddress($recipientEmail);
        
        $mail->isHTML(true);
        $mail->Subject = "Guarantor Request Rejected - Loan #{$loanInfo['loan_number']}";
        $mail->Body = "
            <html>
            <head>
                <style>
                    body { font-family: Arial, sans-serif; line-height: 1.6; }
                    .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                    .header { background-color: #f44336; color: white; padding: 20px; text-align: center; border-radius: 5px 5px 0 0; }
                    .content { padding: 20px; background-color: #f9f9f9; border: 1px solid #ddd; border-top: none; border-radius: 0 0 5px 5px; }
                    .warning-box { background-color: #FFEBEE; border-left: 4px solid #f44336; padding: 15px; margin: 15px 0; }
                    .info-box { background-color: #E3F2FD; padding: 15px; border-radius: 5px; margin: 15px 0; }
                    .action-box { background-color: #FFF3E0; padding: 15px; border-radius: 5px; margin: 15px 0; }
                    .footer { margin-top: 20px; text-align: center; font-size: 12px; color: #666; }
                </style>
            </head>
            <body>
                <div class='container'>
                    <div class='header'>
                        <h2>Guarantor Request Rejected</h2>
                    </div>
                    <div class='content'>
                        <p>Dear <strong>{$firstName}</strong>,</p>
                        
                        <div class='warning-box'>
                            <h3 style='margin-top: 0; color: #f44336;'>⚠️ Request Declined</h3>
                            <p><strong>{$guarantorName}</strong> has declined your guarantor request for loan <strong>#{$loanInfo['loan_number']}</strong>.</p>
                            <p><strong>Requested Amount:</strong> Ksh " . number_format($requestedAmount, 2) . "</p>
                        </div>
                        
                        " . ($coverageSummary ? "
                        <div class='info-box'>
                            <h4 style='margin-top: 0;'>📊 Current Loan Status</h4>
                            <table style='width: 100%; border-collapse: collapse;'>
                                <tr>
                                    <td style='padding: 5px 0;'><strong>Total Loan Amount:</strong></td>
                                    <td style='padding: 5px 0; text-align: right;'>Ksh " . number_format($coverageSummary['loan_amount'], 2) . "</td>
                                </tr>
                                <tr style='border-top: 1px solid #ccc;'>
                                    <td style='padding: 5px 0;'><strong>Total Guaranteed So Far:</strong></td>
                                    <td style='padding: 5px 0; text-align: right;'><strong>Ksh " . number_format($coverageSummary['total_coverage'], 2) . "</strong></td>
                                </tr>
                                <tr style='background-color: #FFF3E0;'>
                                    <td style='padding: 5px 0;'><strong>Remaining to Cover:</strong></td>
                                    <td style='padding: 5px 0; text-align: right;'><strong>Ksh " . number_format($coverageSummary['remaining_amount'], 2) . "</strong></td>
                                </tr>
                                <tr>
                                    <td style='padding: 5px 0;'><strong>Approved Guarantors:</strong></td>
                                    <td style='padding: 5px 0; text-align: right;'>{$coverageSummary['approved_count']}</td>
                                </tr>
                                <tr>
                                    <td style='padding: 5px 0;'><strong>Pending Guarantors:</strong></td>
                                    <td style='padding: 5px 0; text-align: right;'>{$coverageSummary['pending_count']}</td>
                                </tr>
                            </table>
                        </div>
                        " : "") . "
                        
                        <div class='action-box'>
                            <h4 style='margin-top: 0;'>📋 Recommended Actions</h4>
                            <ul>
                                <li>Find alternative guarantors to replace the one who declined</li>
                                <li>Consider increasing your self-guarantee if possible</li>
                                <li>Contact the declined guarantor to understand their concerns</li>
                                <li>Review your loan application details</li>
                                " . ($coverageSummary && $coverageSummary['pending_count'] > 0 ? "
                                <li>Wait for responses from remaining pending guarantors</li>" : "") . "
                            </ul>
                        </div>
                        
                        <div class='info-box'>
                            <h4 style='margin-top: 0;'>💡 Tips for Finding Guarantors</h4>
                            <ul>
                                <li>Choose guarantors with sufficient savings balance</li>
                                <li>Ensure they understand their obligations</li>
                                <li>Communicate clearly about the loan terms</li>
                                <li>Select trusted family members or colleagues</li>
                            </ul>
                        </div>
                        
                        <p>We understand this is disappointing, but don't give up! Login to your account to manage your guarantor requests.</p>
                        
                        <div class='footer'>
                            <p>This is an automated message. Please do not reply to this email.</p>
                            <p>For assistance, contact our support team.</p>
                        </div>
                    </div>
                </div>
            </body>
            </html>
        ";
        
        return $mail->send();
        
    } catch (Exception $e) {
        error_log("Detailed rejection email failed: " . $e->getMessage());
        return false;
    }
}

/**
 * Send detailed rejection SMS
 */
function sendDetailedRejectionSMS($phoneNumber, $firstName, $loanNumber, $guarantorName) {
    try {
        $message = "Dear $firstName, $guarantorName has REJECTED your guarantor request for loan #$loanNumber. Login to find alternative guarantors or adjust your loan application.";
        
        if (function_exists('sendSms')) {
            global $pdo;
            return sendSms($pdo, $phoneNumber, $message);
        }
        return false;
        
    } catch (Exception $e) {
        error_log("Detailed rejection SMS failed: " . $e->getMessage());
        return false;
    }
}

/**
 * Check if loan is fully covered after approval
 */
function checkLoanCoverage($loanId, $pdo) {
    try {
        $stmt = $pdo->prepare("
            SELECT 
                l.loan_amount,
                l.self_guaranteed_amount,
                COALESCE(SUM(CASE WHEN lg.guarantor_request_status = 'approved' THEN lg.guarantee_amount ELSE 0 END), 0) as total_approved_guarantee,
                COUNT(CASE WHEN lg.guarantor_request_status = 'pending' THEN 1 END) as pending_count
            FROM loans l
            LEFT JOIN loan_guarantors lg ON l.id = lg.loan_id
            WHERE l.id = ?
            GROUP BY l.id
        ");
        $stmt->execute([$loanId]);
        $coverage = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$coverage) {
            return false;
        }
        
        $totalCoverage = ($coverage['self_guaranteed_amount'] ?? 0) + ($coverage['total_approved_guarantee'] ?? 0);
        $isFullyCovered = $totalCoverage >= $coverage['loan_amount'];
        $pendingCount = $coverage['pending_count'] ?? 0;
        
        return [
            'fully_covered' => $isFullyCovered,
            'pending_count' => $pendingCount,
            'total_coverage' => $totalCoverage,
            'loan_amount' => $coverage['loan_amount']
        ];
    } catch (PDOException $e) {
        error_log("Error checking loan coverage: " . $e->getMessage());
        return false;
    }
}

// ============================================
// REQUEST ROUTING
// ============================================

$method = $_SERVER['REQUEST_METHOD'];
$requestUri = $_SERVER['REQUEST_URI'];

// Initialize OTP session if not exists
if (!isset($_SESSION['guarantor_otp_step'])) {
    $_SESSION['guarantor_otp_step'] = 'form';
    $_SESSION['guarantor_otp_data'] = [];
}

try {
    switch ($method) {
        case 'GET':
            handleGetRequest();
            break;
            
        case 'POST':
            // Check if this is a resend OTP request
            if (isset($_GET['resend_otp'])) {
                handleResendOTP();
            } else {
                handlePostRequest();
            }
            break;
            
        case 'PUT':
            handlePutRequest();
            break;
            
        case 'DELETE':
            handleDeleteRequest();
            break;
            
        default:
            http_response_code(405);
            echo json_encode([
                'success' => false,
                'error' => 'Method not allowed',
                'allowed_methods' => ['GET', 'POST', 'PUT', 'DELETE']
            ]);
            break;
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Internal server error',
        'message' => 'Something went wrong'
    ]);
    error_log("Guarantor Requests API Error: " . $e->getMessage());
    error_log("Stack trace: " . $e->getTraceAsString());
}

// ============================================
// REQUEST HANDLERS
// ============================================

/**
 * Handle GET requests
 */
function handleGetRequest() {
    global $pdo, $memberId;
    
    // Check for specific request ID
    if (isset($_GET['id'])) {
        $requestId = (int)$_GET['id'];
        
        if (!validateRequestOwnership($requestId, $memberId, $pdo)) {
            http_response_code(404);
            echo json_encode([
                'success' => false,
                'error' => 'Guarantor request not found'
            ]);
            return;
        }
        
        try {
            $sql = "
                SELECT 
                    lg.id, 
                    lg.loan_id, 
                    lg.requested_amount,
                    lg.guarantee_amount,
                    lg.guarantor_request_status, 
                    lg.status, 
                    lg.created_at,
                    l.loan_number, 
                    l.loan_amount,
                    m.first_name, 
                    m.last_name, 
                    m.personal_number,
                    at.account_name as savings_account,
                    ma.available_balance,
                    m.communication_preference,
                    mp.email,
                    m.phone_number
                FROM loan_guarantors lg
                JOIN loans l ON lg.loan_id = l.id
                JOIN members m ON l.member_id = m.id
                JOIN member_accounts ma ON lg.savings_account_id = ma.id
                JOIN account_types at ON ma.account_type_id = at.id
                LEFT JOIN member_portal_accounts mp ON m.id = mp.member_id
                WHERE lg.id = ? AND lg.guarantor_member_id = ?
            ";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$requestId, $memberId]);
            $request = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$request) {
                http_response_code(404);
                echo json_encode([
                    'success' => false,
                    'error' => 'Guarantor request not found'
                ]);
                return;
            }
            
            // Calculate available guarantee range
            $maxGuarantee = min($request['requested_amount'], $request['available_balance']);
            $request['max_guarantee_amount'] = $maxGuarantee;
            $request['can_approve'] = $request['available_balance'] >= $request['requested_amount'];
            
            echo json_encode([
                'success' => true,
                'data' => $request
            ]);
            
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode([
                'success' => false,
                'error' => 'Failed to fetch guarantor request details'
            ]);
        }
        
        return;
    }
    
    // Check OTP verification status
    if (isset($_GET['otp_status'])) {
        echo json_encode([
            'success' => true,
            'data' => [
                'otp_step' => $_SESSION['guarantor_otp_step'],
                'otp_data' => $_SESSION['guarantor_otp_data'],
                'has_otp_session' => !empty($_SESSION['guarantor_otp_data'])
            ]
        ]);
        return;
    }
    
    // Get all pending requests
    try {
        $requests = getPendingGuarantorRequests($pdo, $memberId);
        
        // Enhance data with calculations
        foreach ($requests as &$request) {
            $maxGuarantee = min($request['requested_amount'], $request['available_balance']);
            $request['max_guarantee_amount'] = $maxGuarantee;
            $request['can_approve'] = $request['available_balance'] >= $request['requested_amount'];
            $request['balance_percentage'] = $request['available_balance'] > 0 ? 
                min(100, ($request['requested_amount'] / $request['available_balance']) * 100) : 0;
        }
        
        echo json_encode([
            'success' => true,
            'data' => [
                'requests' => $requests,
                'summary' => [
                    'total_pending' => count($requests),
                    'total_requested' => array_sum(array_column($requests, 'requested_amount')),
                    'total_available' => array_sum(array_column($requests, 'available_balance'))
                ]
            ]
        ], JSON_NUMERIC_CHECK);
        
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'error' => 'Failed to fetch guarantor requests'
        ]);
        error_log("Database error: " . $e->getMessage());
    }
}

/**
 * Handle POST requests (Initiate approval/decline process)
 */
function handlePostRequest() {
    global $pdo, $memberId;
    
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error' => 'Invalid JSON input',
            'json_error' => json_last_error_msg()
        ]);
        return;
    }
    
    // Validate required fields
    if (!isset($input['request_id']) || !isset($input['action']) || !isset($input['agree_terms'])) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error' => 'Missing required fields',
            'required_fields' => ['request_id', 'action', 'agree_terms']
        ]);
        return;
    }
    
    if ($input['agree_terms'] !== true && $input['agree_terms'] !== 1) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error' => 'You must agree to the terms and conditions to proceed'
        ]);
        return;
    }
    
    $requestId = (int)$input['request_id'];
    $action = $input['action'];
    
    // Validate action
    if (!in_array($action, ['approve', 'decline'])) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error' => 'Invalid action',
            'allowed_actions' => ['approve', 'decline']
        ]);
        return;
    }
    
    // Validate request ownership
    if (!validateRequestOwnership($requestId, $memberId, $pdo)) {
        http_response_code(404);
        echo json_encode([
            'success' => false,
            'error' => 'Guarantor request not found'
        ]);
        return;
    }
    
    // For approval, validate guarantee amount
    if ($action === 'approve') {
        if (!isset($input['guarantee_amount'])) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => 'Guarantee amount is required for approval'
            ]);
            return;
        }
        
        $guaranteeAmount = (float)$input['guarantee_amount'];
        $validation = validateGuaranteeAmount($guaranteeAmount, $requestId, $memberId, $pdo);
        
        if (!$validation['valid']) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => 'Validation failed',
                'errors' => $validation['errors'] ?? [$validation['error']]
            ]);
            return;
        }
    } else {
        $guaranteeAmount = 0;
    }
    
    // Get loan ID and requested amount for notification
    try {
        $stmt = $pdo->prepare("
            SELECT lg.loan_id, lg.requested_amount, ma.available_balance
            FROM loan_guarantors lg
            JOIN member_accounts ma ON lg.savings_account_id = ma.id
            WHERE lg.id = ? AND lg.guarantor_member_id = ?
        ");
        $stmt->execute([$requestId, $memberId]);
        $requestData = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$requestData) {
            throw new Exception("Request data not found");
        }
        
        // Store data in session for OTP verification
        $_SESSION['guarantor_otp_data'] = [
            'request_id' => $requestId,
            'action' => $action,
            'guarantee_amount' => $guaranteeAmount,
            'loan_id' => $requestData['loan_id'],
            'requested_amount' => $requestData['requested_amount'],
            'available_balance' => $requestData['available_balance']
        ];
        
        // Send OTP
        $otpAction = $action === 'approve' ? 'guarantor_approve' : 'guarantor_decline';
        $sent = sendGuarantorOTP($memberId, $otpAction, $requestId, $pdo);
        
        if ($sent) {
            $_SESSION['guarantor_otp_step'] = 'verify_otp';
            
            echo json_encode([
                'success' => true,
                'message' => 'OTP sent to your registered contact method',
                'data' => [
                    'otp_step' => 'verify_otp',
                    'action' => $action,
                    'request_id' => $requestId,
                    'guarantee_amount' => $guaranteeAmount,
                    'expires_in' => 900 // 15 minutes
                ]
            ]);
            
        } else {
            http_response_code(500);
            echo json_encode([
                'success' => false,
                'error' => 'Failed to send OTP. Please try again.'
            ]);
        }
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'error' => 'Failed to initiate OTP process',
            'details' => 'Internal server error'
        ]);
        error_log("OTP initiation error: " . $e->getMessage());
    }
}

/**
 * Handle PUT requests (Verify OTP and process decision)
 */
function handlePutRequest() {
    global $pdo, $memberId;
    
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error' => 'Invalid JSON input',
            'json_error' => json_last_error_msg()
        ]);
        return;
    }
    
    // Check if we're in OTP verification step
    if (!isset($_SESSION['guarantor_otp_step']) || $_SESSION['guarantor_otp_step'] !== 'verify_otp') {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error' => 'No OTP verification in progress'
        ]);
        return;
    }
    
    // Validate OTP
    if (!isset($input['otp']) || strlen($input['otp']) !== 6) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error' => 'Please enter a valid 6-digit OTP'
        ]);
        return;
    }
    
    $otpData = $_SESSION['guarantor_otp_data'];
    $enteredOtp = $input['otp'];
    
    // Verify OTP
    $otpAction = $otpData['action'] === 'approve' ? 'guarantor_approve' : 'guarantor_decline';
    $verified = verifyGuarantorOTP($memberId, $enteredOtp, $otpAction, $otpData['request_id']);
    
    if (!$verified) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error' => 'Invalid OTP. Please try again.'
        ]);
        return;
    }
    
    try {
        // Begin transaction
        $pdo->beginTransaction();
        
        if ($otpData['action'] === 'approve') {
            // Update guarantor request status to approved
            $stmt = $pdo->prepare("
                UPDATE loan_guarantors 
                SET guarantor_request_status = 'approved', 
                    guarantee_amount = ?,
                    responded_at = NOW()
                WHERE id = ? AND guarantor_member_id = ?
            ");
            $stmt->execute([
                $otpData['guarantee_amount'],
                $otpData['request_id'],
                $memberId
            ]);
            
            if ($stmt->rowCount() === 0) {
                throw new Exception("Failed to update guarantor request");
            }
            
            // Check loan coverage
            $coverage = checkLoanCoverage($otpData['loan_id'], $pdo);
            
            if ($coverage && $coverage['pending_count'] == 0 && $coverage['fully_covered']) {
                // Update loan status to approved
                $stmt = $pdo->prepare("UPDATE loans SET status = 'pending', updated_at = NOW() WHERE id = ?");
                $stmt->execute([$otpData['loan_id']]);
                
                // Add notification for full approval
                addInternalNotification(
                    $pdo,
                    $memberId,
                    'Loan Fully Approved',
                    "All guarantors have approved your loan. Your loan has been fully approved and will be disbursed shortly.",
                    'success',
                    "loan_status.php?id=" . $otpData['loan_id'],
                    'carbon:checkmark'
                );
            }
            
            $message = "Guarantor request approved successfully. Ksh " . 
                number_format($otpData['guarantee_amount'], 2) . " will be guaranteed when the loan is disbursed.";
            
        } else {
            // Process decline
            $stmt = $pdo->prepare("
                UPDATE loan_guarantors 
                SET guarantor_request_status = 'rejected', 
                    responded_at = NOW()
                WHERE id = ? AND guarantor_member_id = ?
            ");
            $stmt->execute([$otpData['request_id'], $memberId]);
            
            if ($stmt->rowCount() === 0) {
                throw new Exception("Failed to update guarantor request");
            }
            
            // Update loan status back to pending if it was in guarantor review
            $stmt = $pdo->prepare("
                UPDATE loans 
                SET status = 'pending', 
                    notes = CONCAT(COALESCE(notes, ''), ' Guarantor rejected on ', NOW(), '.')
                WHERE id = ? AND status = 'guarantor_review'
            ");
            $stmt->execute([$otpData['loan_id']]);
            
            $message = "Guarantor request rejected successfully.";
        }
        
        // Send enhanced notifications to loan applicant
        sendGuarantorDecisionNotifications(
            $memberId,
            $otpData['loan_id'],
            $otpData['action'],
            $otpData['guarantee_amount'],
            $otpData['requested_amount'], // Pass the original requested amount
            $pdo
        );
        
        // Commit transaction
        $pdo->commit();
        
        // Clear OTP session data
        $_SESSION['guarantor_otp_step'] = 'form';
        $_SESSION['guarantor_otp_data'] = [];
        
        echo json_encode([
            'success' => true,
            'message' => $message,
            'data' => [
                'action' => $otpData['action'],
                'guarantee_amount' => $otpData['guarantee_amount'],
                'request_id' => $otpData['request_id']
            ]
        ]);
        
    } catch (Exception $e) {
        $pdo->rollBack();
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'error' => 'Failed to process guarantor decision',
            'details' => 'Internal server error'
        ]);
        error_log("Guarantor decision processing error: " . $e->getMessage());
        error_log("Stack trace: " . $e->getTraceAsString());
    }
}

/**
 * Handle DELETE requests (Cancel OTP process)
 */
function handleDeleteRequest() {
    global $memberId;
    
    // Clear OTP session data
    $_SESSION['guarantor_otp_step'] = 'form';
    $_SESSION['guarantor_otp_data'] = [];
    
    echo json_encode([
        'success' => true,
        'message' => 'OTP verification cancelled',
        'data' => [
            'otp_step' => 'form',
            'has_otp_session' => false
        ]
    ]);
}

/**
 * Resend OTP (special endpoint)
 */
function handleResendOTP() {
    global $pdo, $memberId;
    
    if (!isset($_SESSION['guarantor_otp_step']) || $_SESSION['guarantor_otp_step'] !== 'verify_otp') {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error' => 'No OTP verification in progress'
        ]);
        return;
    }
    
    $otpData = $_SESSION['guarantor_otp_data'];
    $otpAction = $otpData['action'] === 'approve' ? 'guarantor_approve' : 'guarantor_decline';
    
    $sent = sendGuarantorOTP($memberId, $otpAction, $otpData['request_id'], $pdo);
    
    if ($sent) {
        echo json_encode([
            'success' => true,
            'message' => 'OTP resent successfully'
        ]);
    } else {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'error' => 'Failed to resend OTP'
        ]);
    }
}
?>