<?php session_start();
// loan_details.php
include 'includes/head.php';

$user_id = $_SESSION['user_id'];
$account_id = isset($_GET['account_id']) ? intval($_GET['account_id']) : 0;

// Get account details
$account_sql = "SELECT ba.*, u.phone, u.first_name, u.last_name 
                FROM bank_accounts ba 
                JOIN users u ON ba.user_id = u.id 
                WHERE ba.id = '$account_id' AND ba.user_id = '$user_id'";
$account_result = mysqli_query($conn, $account_sql);
$account = mysqli_fetch_assoc($account_result);

if (!$account) {
    $_SESSION['error'] = "Bank account not found.";
    header("Location: bank_linking.php");
    exit();
}

if ($account['is_verified']) {
    $_SESSION['success'] = "This bank account is already verified.";
    header("Location: bank_linking.php");
    exit();
}

// Get user's recent verification attempts
$verification_sql = "SELECT * FROM payment_verifications 
                     WHERE user_id = '$user_id' AND status = 'pending' AND expires_at > NOW()
                     ORDER BY created_at DESC LIMIT 1";
$verification_result = mysqli_query($conn, $verification_sql);
$active_verification = mysqli_fetch_assoc($verification_result);

// Handle OTP verification
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST['verify_otp'])) {
        $otp_code = $conn->real_escape_string($_POST['otp_code']);
        
        if (verifyOTP($conn, $user_id, $otp_code)) {
            // Mark bank account as verified
            $update_sql = "UPDATE bank_accounts SET is_verified = 1, verification_method = 'otp' 
                          WHERE id = '$account_id' AND user_id = '$user_id'";
            
            if (mysqli_query($conn, $update_sql)) {
                // Update verification record
                $update_verification = "UPDATE payment_verifications SET status = 'verified', verified_at = NOW() 
                                      WHERE user_id = '$user_id' AND reference_code = '{$active_verification['reference_code']}'";
                mysqli_query($conn, $update_verification);
                
                // Log transaction
                logTransaction($conn, $user_id, 'verification', null, $active_verification['reference_code'], 'Bank account OTP verification successful', 'completed');
                
                $_SESSION['success'] = "Bank account verified successfully!";
                header("Location: bank_linking.php");
                exit();
            }
        } else {
            $error = "Invalid OTP code. Please try again.";
            
            // Increment attempt counter
            if ($active_verification) {
                $new_attempts = $active_verification['attempts'] + 1;
                $update_attempts = "UPDATE payment_verifications SET attempts = $new_attempts 
                                  WHERE id = '{$active_verification['id']}'";
                mysqli_query($conn, $update_attempts);
                
                // Check if max attempts reached
                if ($new_attempts >= 3) {
                    $expire_verification = "UPDATE payment_verifications SET status = 'expired' 
                                          WHERE id = '{$active_verification['id']}'";
                    mysqli_query($conn, $update_attempts);
                    $error = "Maximum OTP attempts reached. Please request a new OTP.";
                    $active_verification = null;
                }
            }
        }
    } 
    elseif (isset($_POST['send_otp'])) {
        handleOTPRequest($conn, $user_id, $account);
    }
    elseif (isset($_POST['verify_micro_deposit'])) {
        handleMicroDepositVerification($conn, $user_id, $account_id);
    }
    elseif (isset($_POST['request_micro_deposit'])) {
        handleMicroDepositRequest($conn, $user_id, $account);
    }
}

function handleOTPRequest($conn, $user_id, $account) {
    // Generate OTP
    $otp = generateOTP();
    $reference_code = 'OTP_' . time() . '_' . rand(1000, 9999);
    
    // Expire any existing pending verifications
    $expire_sql = "UPDATE payment_verifications SET status = 'expired' 
                   WHERE user_id = '$user_id' AND status = 'pending'";
    mysqli_query($conn, $expire_sql);
    
    // Create new verification record
    $verification_sql = "INSERT INTO payment_verifications (user_id, verification_type, reference_code, status, expires_at) 
                       VALUES ('$user_id', 'otp', '$reference_code', 'pending', DATE_ADD(NOW(), INTERVAL 10 MINUTE))";
    
    if (mysqli_query($conn, $verification_sql)) {
        // In a real application, send SMS via gateway
        // sendSMS($account['phone'], "Your E-Finance Loans verification code is: $otp");
        
        // For demo, we'll store the OTP in session
        $_SESSION['demo_otp'] = $otp;
        $_SESSION['otp_reference'] = $reference_code;
        
        // Log OTP sent
        logTransaction($conn, $user_id, 'verification', null, $reference_code, 'OTP sent for bank verification', 'pending');
        
        return true;
    }
    return false;
}

function handleMicroDepositRequest($conn, $user_id, $account) {
    // Generate random micro-deposit amounts
    $amount1 = rand(1, 9) / 100; // R0.01 to R0.09
    $amount2 = rand(1, 9) / 100; // R0.01 to R0.09
    
    $reference_code = 'MICRO_' . time() . '_' . rand(1000, 9999);
    
    // Expire any existing pending verifications
    $expire_sql = "UPDATE payment_verifications SET status = 'expired' 
                   WHERE user_id = '$user_id' AND status = 'pending'";
    mysqli_query($conn, $expire_sql);
    
    // Create micro-deposit verification record
    $verification_sql = "INSERT INTO payment_verifications (user_id, verification_type, reference_code, amount, status, expires_at) 
                       VALUES ('$user_id', 'micro_deposit', '$reference_code', '$amount1', 'pending', DATE_ADD(NOW(), INTERVAL 24 HOUR))";
    
    if (mysqli_query($conn, $verification_sql)) {
        // In real application, initiate bank transfer
        // initiateMicroDeposit($account['bank_name'], $account['account_number'], $amount1);
        // initiateMicroDeposit($account['bank_name'], $account['account_number'], $amount2);
        
        // Store amounts in session for demo
        $_SESSION['micro_deposit_1'] = $amount1;
        $_SESSION['micro_deposit_2'] = $amount2;
        $_SESSION['micro_reference'] = $reference_code;
        
        // Log micro-deposit initiated
        logTransaction($conn, $user_id, 'verification', $amount1, $reference_code, 'Micro-deposit verification initiated', 'pending');
        
        return true;
    }
    return false;
}

function handleMicroDepositVerification($conn, $user_id, $account_id) {
    $amount1 = floatval($_POST['amount1']);
    $amount2 = floatval($_POST['amount2']);
    
    // Check against stored amounts (in real app, verify with bank statement)
    if (isset($_SESSION['micro_deposit_1']) && isset($_SESSION['micro_deposit_2'])) {
        $expected1 = $_SESSION['micro_deposit_1'];
        $expected2 = $_SESSION['micro_deposit_2'];
        
        if (abs($amount1 - $expected1) < 0.001 && abs($amount2 - $expected2) < 0.001) {
            // Mark bank account as verified
            $update_sql = "UPDATE bank_accounts SET is_verified = 1, verification_method = 'micro_deposit' 
                          WHERE id = '$account_id' AND user_id = '$user_id'";
            
            if (mysqli_query($conn, $update_sql)) {
                // Update verification record
                $update_verification = "UPDATE payment_verifications SET status = 'verified', verified_at = NOW() 
                                      WHERE user_id = '$user_id' AND reference_code = '{$_SESSION['micro_reference']}'";
                mysqli_query($conn, $update_verification);
                
                // Log successful verification
                logTransaction($conn, $user_id, 'verification', null, $_SESSION['micro_reference'], 'Micro-deposit verification successful', 'completed');
                
                // Clear session data
                unset($_SESSION['micro_deposit_1'], $_SESSION['micro_deposit_2'], $_SESSION['micro_reference']);
                
                $_SESSION['success'] = "Bank account verified successfully!";
                header("Location: bank_linking.php");
                exit();
            }
        } else {
            $error = "Incorrect amounts entered. Please check your bank statement and try again.";
        }
    } else {
        $error = "Micro-deposit verification session expired. Please request new deposits.";
    }
}

function verifyOTP($conn, $user_id, $entered_otp) {
    // For demo purposes, check against session
    if (isset($_SESSION['demo_otp']) && $_SESSION['demo_otp'] == $entered_otp) {
        return true;
    }
    
    // In real application, verify against database and SMS gateway
    $verify_sql = "SELECT * FROM payment_verifications 
                   WHERE user_id = '$user_id' AND status = 'pending' 
                   AND expires_at > NOW() AND verification_type = 'otp'
                   ORDER BY created_at DESC LIMIT 1";
    $result = mysqli_query($conn, $verify_sql);
    
    if ($row = mysqli_fetch_assoc($result)) {
        // Here you would verify with your SMS gateway
        // For now, we'll use session-based demo
        return false;
    }
    
    return false;
}

function generateOTP() {
    return sprintf("%06d", rand(0, 999999));
}

function logTransaction($conn, $user_id, $type, $amount, $reference, $description, $status) {
    $sql = "INSERT INTO transaction_logs (user_id, transaction_type, amount, reference, status, description) 
            VALUES ('$user_id', '$type', " . ($amount ?: 'NULL') . ", '$reference', '$status', '$description')";
    return mysqli_query($conn, $sql);
}

// Get active verification
$active_verification_sql = "SELECT * FROM payment_verifications 
                           WHERE user_id = '$user_id' AND status = 'pending' AND expires_at > NOW()
                           ORDER BY created_at DESC LIMIT 1";
$active_verification_result = mysqli_query($conn, $active_verification_sql);
$active_verification = mysqli_fetch_assoc($active_verification_result);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verify Bank Account - E-Finance Loans</title>
    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <style>
    .verification-method-card {
        border: 2px solid #e9ecef;
        border-radius: 10px;
        transition: all 0.3s ease;
        cursor: pointer;
    }
    .verification-method-card:hover {
        border-color: #4CAF50;
        background-color: #f8f9fa;
    }
    .verification-method-card.selected {
        border-color: #4CAF50;
        background-color: #e8f5e8;
    }
    .countdown-timer {
        font-size: 0.9em;
        font-weight: bold;
        color: #dc3545;
    }
    .otp-input {
        letter-spacing: 10px;
        font-size: 1.5em;
        font-weight: bold;
        text-align: center;
    }
    .verification-steps {
        border-left: 3px solid #4CAF50;
        padding-left: 20px;
    }
    </style>
</head>
<body class="dashboard">
    <div id="main-wrapper">
        <?php include('includes/header.php');?>
        <?php include('includes/sidebar.php');?>

        <div class="content-body">
            <div class="container">
                <div class="row">
                    <div class="col-12">
                        <div class="page-title">
                            <div class="row align-items-center justify-content-between">
                                <div class="col-xl-4">
                                    <div class="page-title-content">
                                        <h3>Verify Bank Account</h3>
                                        <p class="mb-2">Confirm ownership of your bank account</p>
                                    </div>
                                </div>
                                <div class="col-auto">
                                    <div class="breadcrumbs">
                                        <a href="dashboard.php">Home</a>
                                        <span><i class="fi fi-rr-angle-small-right"></i></span>
                                        <a href="bank_linking.php">Bank Accounts</a>
                                        <span><i class="fi fi-rr-angle-small-right"></i></span>
                                        <a href="#">Verify Account</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Success/Error Messages -->
                <?php if(isset($_SESSION['success'])): ?>
                    <div class="alert alert-success alert-dismissible fade show">
                        <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>
                
                <?php if(isset($error)): ?>
                    <div class="alert alert-danger alert-dismissible fade show">
                        <?php echo $error; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <div class="row justify-content-center">
                    <div class="col-xl-8">
                        <!-- Account Information -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Account to Verify</h5>
                            </div>
                            <div class="card-body">
                                <div class="row align-items-center">
                                    <div class="col-auto">
                                        <div class="bank-logo" style="width: 50px; height: 50px;">
                                            <?php echo substr($account['bank_name'], 0, 2); ?>
                                        </div>
                                    </div>
                                    <div class="col">
                                        <h6 class="mb-1"><?php echo $account['bank_name']; ?></h6>
                                        <p class="text-muted mb-1">Account: ●●●● <?php echo substr($account['account_number'], -4); ?></p>
                                        <p class="text-muted mb-0">Holder: <?php echo $account['first_name'] . ' ' . $account['last_name']; ?></p>
                                    </div>
                                    <div class="col-auto">
                                        <span class="badge bg-warning">Pending Verification</span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Verification Methods -->
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Choose Verification Method</h5>
                            </div>
                            <div class="card-body">
                                <!-- OTP Verification Method -->
                                <div class="verification-method-card p-4 mb-4" id="otpMethod">
                                    <div class="row align-items-center">
                                        <div class="col-auto">
                                            <i class="fi fi-rr-smartphone fs-1 text-primary"></i>
                                        </div>
                                        <div class="col">
                                            <h6>Instant OTP Verification</h6>
                                            <p class="text-muted mb-2">
                                                We'll send a 6-digit code to your registered mobile number ending in 
                                                <?php echo substr($account['phone'], -3); ?>
                                            </p>
                                            <small class="text-success">✓ Fastest method - usually completed in minutes</small>
                                        </div>
                                        <div class="col-auto">
                                            <button type="button" class="btn btn-outline-primary" 
                                                    onclick="selectMethod('otp')" id="selectOtpBtn">
                                                Select Method
                                            </button>
                                        </div>
                                    </div>
                                </div>

                                <!-- Micro-deposit Verification Method -->
                                <div class="verification-method-card p-4" id="microMethod">
                                    <div class="row align-items-center">
                                        <div class="col-auto">
                                            <i class="fi fi-rr-bank fs-1 text-success"></i>
                                        </div>
                                        <div class="col">
                                            <h6>Micro-deposit Verification</h6>
                                            <p class="text-muted mb-2">
                                                We'll make two small deposits to your account. Verify the amounts within 24 hours.
                                            </p>
                                            <small class="text-warning">⏳ Takes 1-2 business days to complete</small>
                                        </div>
                                        <div class="col-auto">
                                            <button type="button" class="btn btn-outline-success" 
                                                    onclick="selectMethod('micro')" id="selectMicroBtn">
                                                Select Method
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- OTP Verification Form -->
                        <div class="card mt-4" id="otpForm" style="display: none;">
                            <div class="card-header">
                                <h5 class="card-title mb-0">OTP Verification</h5>
                            </div>
                            <div class="card-body">
                                <div class="verification-steps mb-4">
                                    <h6>Verification Steps:</h6>
                                    <ol>
                                        <li>Click "Send OTP" to receive a 6-digit code via SMS</li>
                                        <li>Enter the code in the field below</li>
                                        <li>Click "Verify Account" to complete the process</li>
                                    </ol>
                                </div>

                                <?php if($active_verification && $active_verification['verification_type'] == 'otp'): ?>
                                <div class="alert alert-info">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <span>OTP sent to your mobile number</span>
                                        <span class="countdown-timer" id="otpTimer"></span>
                                    </div>
                                </div>
                                <?php endif; ?>

                                <form method="POST" action="">
                                    <div class="row justify-content-center">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">Enter 6-digit OTP</label>
                                                <input type="text" class="form-control otp-input" name="otp_code" 
                                                       maxlength="6" pattern="[0-9]{6}" placeholder="123456" required
                                                       oninput="this.value = this.value.replace(/[^0-9]/g, '')">
                                            </div>
                                            
                                            <div class="d-grid gap-2">
                                                <button type="submit" name="verify_otp" class="btn btn-primary btn-lg">
                                                    <i class="fi fi-rr-check me-2"></i>
                                                    Verify Account
                                                </button>
                                                
                                                <?php if(!$active_verification || $active_verification['verification_type'] != 'otp'): ?>
                                                <button type="submit" name="send_otp" class="btn btn-outline-primary">
                                                    <i class="fi fi-rr-paper-plane me-2"></i>
                                                    Send OTP
                                                </button>
                                                <?php endif; ?>
                                            </div>
                                            
                                            <?php if(isset($_SESSION['demo_otp'])): ?>
                                            <div class="alert alert-warning mt-3">
                                                <strong>Demo Mode:</strong> Use OTP: <code><?php echo $_SESSION['demo_otp']; ?></code>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <!-- Micro-deposit Verification Form -->
                        <div class="card mt-4" id="microForm" style="display: none;">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Micro-deposit Verification</h5>
                            </div>
                            <div class="card-body">
                                <div class="verification-steps mb-4">
                                    <h6>Verification Steps:</h6>
                                    <ol>
                                        <li>Click "Request Micro-deposits" to initiate transfers</li>
                                        <li>Check your bank account in 1-2 business days for two small deposits</li>
                                        <li>Enter the exact amounts below (e.g., 0.05 for 5 cents)</li>
                                        <li>Click "Verify Amounts" to complete the process</li>
                                    </ol>
                                </div>

                                <?php if($active_verification && $active_verification['verification_type'] == 'micro_deposit'): ?>
                                <div class="alert alert-info">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <span>Micro-deposits initiated. Check your bank account.</span>
                                        <span class="countdown-timer" id="microTimer"></span>
                                    </div>
                                </div>
                                <?php endif; ?>

                                <form method="POST" action="">
                                    <div class="row justify-content-center">
                                        <div class="col-md-8">
                                            <div class="row g-3">
                                                <div class="col-md-6">
                                                    <label class="form-label">First Deposit Amount (R)</label>
                                                    <input type="number" class="form-control" name="amount1" 
                                                           step="0.01" min="0.01" max="0.99" placeholder="0.05" required>
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="form-label">Second Deposit Amount (R)</label>
                                                    <input type="number" class="form-control" name="amount2" 
                                                           step="0.01" min="0.01" max="0.99" placeholder="0.08" required>
                                                </div>
                                            </div>
                                            
                                            <div class="d-grid gap-2 mt-3">
                                                <button type="submit" name="verify_micro_deposit" class="btn btn-success btn-lg">
                                                    <i class="fi fi-rr-check me-2"></i>
                                                    Verify Amounts
                                                </button>
                                                
                                                <?php if(!$active_verification || $active_verification['verification_type'] != 'micro_deposit'): ?>
                                                <button type="submit" name="request_micro_deposit" class="btn btn-outline-success">
                                                    <i class="fi fi-rr-bank me-2"></i>
                                                    Request Micro-deposits
                                                </button>
                                                <?php endif; ?>
                                            </div>
                                            
                                            <?php if(isset($_SESSION['micro_deposit_1']) && isset($_SESSION['micro_deposit_2'])): ?>
                                            <div class="alert alert-warning mt-3">
                                                <strong>Demo Mode:</strong> Use amounts: 
                                                <code>R <?php echo number_format($_SESSION['micro_deposit_1'], 2); ?></code> and 
                                                <code>R <?php echo number_format($_SESSION['micro_deposit_2'], 2); ?></code>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <!-- Help Section -->
                        <div class="card mt-4">
                            <div class="card-body">
                                <h6>Need Help?</h6>
                                <ul class="list-unstyled">
                                    <li><i class="fi fi-rr-phone-call text-primary me-2"></i> Contact Support: 0861 111 111</li>
                                    <li><i class="fi fi-rr-envelope text-primary me-2"></i> Email: support@E-Financeloans.co.za</li>
                                    <li><i class="fi fi-rr-clock text-primary me-2"></i> Support Hours: Mon-Fri 8:00-17:00</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

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

    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
    let selectedMethod = '';

    function selectMethod(method) {
        selectedMethod = method;
        
        // Update UI
        $('.verification-method-card').removeClass('selected');
        $(`#${method}Method`).addClass('selected');
        
        // Show selected form, hide others
        $('.card[id$="Form"]').hide();
        $(`#${method}Form`).show();
        
        // Update button texts
        $('#selectOtpBtn').text(method === 'otp' ? 'Selected' : 'Select Method');
        $('#selectMicroBtn').text(method === 'micro' ? 'Selected' : 'Select Method');
    }

    // Countdown timer for OTP
    <?php if($active_verification && $active_verification['verification_type'] == 'otp'): ?>
    function startOTPTimer() {
        const expiresAt = new Date('<?php echo $active_verification['expires_at']; ?>').getTime();
        
        function updateTimer() {
            const now = new Date().getTime();
            const distance = expiresAt - now;
            
            if (distance < 0) {
                document.getElementById('otpTimer').innerHTML = "EXPIRED";
                clearInterval(timerInterval);
                return;
            }
            
            const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((distance % (1000 * 60)) / 1000);
            
            document.getElementById('otpTimer').innerHTML = 
                minutes.toString().padStart(2, '0') + ":" + seconds.toString().padStart(2, '0');
        }
        
        updateTimer();
        const timerInterval = setInterval(updateTimer, 1000);
    }
    startOTPTimer();
    <?php endif; ?>

    // Countdown timer for micro-deposits
    <?php if($active_verification && $active_verification['verification_type'] == 'micro_deposit'): ?>
    function startMicroTimer() {
        const expiresAt = new Date('<?php echo $active_verification['expires_at']; ?>').getTime();
        
        function updateTimer() {
            const now = new Date().getTime();
            const distance = expiresAt - now;
            
            if (distance < 0) {
                document.getElementById('microTimer').innerHTML = "EXPIRED";
                clearInterval(timerInterval);
                return;
            }
            
            const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            
            document.getElementById('microTimer').innerHTML = 
                hours + "h " + minutes.toString().padStart(2, '0') + "m";
        }
        
        updateTimer();
        const timerInterval = setInterval(updateTimer, 60000); // Update every minute
    }
    startMicroTimer();
    <?php endif; ?>

    // Auto-select method if there's an active verification
    <?php if($active_verification): ?>
    $(document).ready(function() {
        selectMethod('<?php echo $active_verification['verification_type'] == 'micro_deposit' ? 'micro' : 'otp'; ?>');
    });
    <?php endif; ?>

    // OTP input formatting
    $('input[name="otp_code"]').on('input', function() {
        if (this.value.length === 6) {
            $(this).addClass('is-valid');
        } else {
            $(this).removeClass('is-valid');
        }
    });

    // Micro-deposit input validation
    $('input[name="amount1"], input[name="amount2"]').on('input', function() {
        const value = parseFloat(this.value);
        if (value >= 0.01 && value <= 0.99) {
            $(this).addClass('is-valid');
        } else {
            $(this).removeClass('is-valid');
        }
    });
    </script>
</body>
</html>
<?php mysqli_close($conn); ?>