<?php
// Strict error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
ob_start();

// Session hardening
ini_set('session.use_strict_mode', 1);
ini_set('session.use_only_cookies', 1);
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_secure', 1);
ini_set('session.cookie_samesite', 'Strict');
ini_set('session.cookie_lifetime', 3600);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

require_once './includes/config.php';
require_once './includes/auth_functions.php';

// Verify 2FA member exists in session
if (!isset($_SESSION['2fa_member_id'])) {
    header("Location: login.php");
    exit;
}

// Initialize OTP attempts counter
$_SESSION['otp_attempts'] = $_SESSION['otp_attempts'] ?? 0;

// Handle OTP resend request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'resend_otp') {
    // CSRF validation
    if (empty($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $response = [
            'success' => false,
            'message' => "Invalid request. Please try again."
        ];
        header('Content-Type: application/json');
        echo json_encode($response);
        exit;
    }
    
    // Rate limiting for OTP resend (max 3 resends per session)
    $_SESSION['otp_resend_attempts'] = $_SESSION['otp_resend_attempts'] ?? 0;
    
    if ($_SESSION['otp_resend_attempts'] >= 3) {
        $response = [
            'success' => false,
            'message' => "Maximum resend attempts exceeded. Please try again later."
        ];
        header('Content-Type: application/json');
        echo json_encode($response);
        exit;
    }
    
    $member_id = $_SESSION['2fa_member_id'];
    
    // Generate and send new OTP
    if (generateAndSendOTP($member_id, 'login')) {
        $_SESSION['otp_resend_attempts']++;
        
        // Log OTP resend activity
        $logStmt = $pdo->prepare("
            INSERT INTO member_activity_logs 
            (member_id, action_type, details, ip_address, user_agent, created_at)
            VALUES (?, 'otp_resent', ?, ?, ?, NOW())
        ");
        $logStmt->execute([
            $member_id,
            json_encode(['resend_count' => $_SESSION['otp_resend_attempts']]),
            $_SERVER['REMOTE_ADDR'] ?? null,
            $_SERVER['HTTP_USER_AGENT'] ?? null
        ]);
        
        $response = [
            'success' => true,
            'message' => "A new verification code has been sent to your device.",
            'resend_count' => $_SESSION['otp_resend_attempts'],
            'remaining_attempts' => 3 - $_SESSION['otp_resend_attempts']
        ];
    } else {
        $response = [
            'success' => false,
            'message' => "Failed to send verification code. Please try again."
        ];
    }
    
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

// Handle OTP verification (existing code)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['action'])) {
    // CSRF validation
    if (empty($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $_SESSION['error'] = "Invalid request. Please try again.";
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }

    // Rate limiting: max 5 attempts
    if ($_SESSION['otp_attempts'] >= 5) {
        $lockStmt = $pdo->prepare("
            UPDATE member_portal_accounts 
            SET status = 'suspended', lock_expires = DATE_ADD(NOW(), INTERVAL 15 MINUTE) 
            WHERE member_id = ?
        ");
        $lockStmt->execute([$_SESSION['2fa_member_id']]);

        // Log account lock
        $logStmt = $pdo->prepare("
            INSERT INTO member_activity_logs 
            (member_id, action_type, details, ip_address, user_agent, created_at)
            VALUES (?, 'account_locked', ?, ?, ?, NOW())
        ");
        $logStmt->execute([
            $_SESSION['2fa_member_id'],
            json_encode(['reason' => 'Too many OTP failures']),
            $_SERVER['REMOTE_ADDR'] ?? null,
            $_SERVER['HTTP_USER_AGENT'] ?? null
        ]);

        session_destroy();
        header("Location: login.php?error=account_locked");
        exit;
    }

    // Validate OTP
    $otp = filter_var(trim($_POST['otp']), FILTER_SANITIZE_FULL_SPECIAL_CHARS);

    if (verifyOTP($_SESSION['2fa_member_id'], $otp, 'login')) {
        $member_id = $_SESSION['2fa_member_id'];
        $ip        = $_SERVER['REMOTE_ADDR'] ?? null;
        $agent     = $_SERVER['HTTP_USER_AGENT'] ?? null;

        // Reset session
        session_unset();
        session_destroy();

        session_start();
        session_regenerate_id(true);

        // New clean session
        $_SESSION = [
            'member_id'     => $member_id,
            'last_activity' => time(),
            'csrf_token'    => bin2hex(random_bytes(32)),
            'authenticated' => true
        ];

        // Log successful login
        $logStmt = $pdo->prepare("
            INSERT INTO member_activity_logs 
            (member_id, action_type, details, ip_address, user_agent, created_at)
            VALUES (?, 'login_success', ?, ?, ?, NOW())
        ");
        $logStmt->execute([
            $member_id,
            json_encode(['method' => 'otp']),
            $ip,
            $agent
        ]);

        ob_end_clean();
        header("Location: dashboard.php");
        exit;
    } else {
        // Log failed OTP attempt
        $logStmt = $pdo->prepare("
            INSERT INTO member_activity_logs 
            (member_id, action_type, details, ip_address, user_agent, created_at)
            VALUES (?, 'otp_failed', ?, ?, ?, NOW())
        ");
        $logStmt->execute([
            $_SESSION['2fa_member_id'],
            json_encode(['otp' => $otp]),
            $_SERVER['REMOTE_ADDR'] ?? null,
            $_SERVER['HTTP_USER_AGENT'] ?? null
        ]);

        $_SESSION['otp_attempts']++;
        $_SESSION['error'] = "Invalid verification code. You have " . (5 - $_SESSION['otp_attempts']) . " attempts remaining.";

        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }
}

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

// Initialize OTP resend attempts if not set
$_SESSION['otp_resend_attempts'] = $_SESSION['otp_resend_attempts'] ?? 0;

ob_end_flush();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Secure Login Verification - Member Portal</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #1a2a6c, #b21f1f, #fdbb2d);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }
        
        .container {
            width: 100%;
            max-width: 450px;
        }
        
        .card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            overflow: hidden;
        }
        
        .header {
            background: #2c3e50;
            color: white;
            padding: 25px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 24px;
            margin-bottom: 10px;
        }
        
        .header p {
            opacity: 0.8;
            font-size: 14px;
        }
        
        .form-container {
            padding: 30px;
        }
        
        .logo {
            text-align: center;
            margin-bottom: 20px;
        }
        
        .logo i {
            font-size: 42px;
            color: #3498db;
            background: #f8f9fa;
            width: 80px;
            height: 80px;
            line-height: 80px;
            border-radius: 50%;
            text-align: center;
            margin-bottom: 15px;
            border: 3px solid #e9ecef;
        }
        
        .input-group {
            margin-bottom: 20px;
            position: relative;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #2c3e50;
            font-size: 14px;
        }
        
        input[type="text"] {
            width: 100%;
            padding: 15px 15px 15px 45px;
            border: 2px solid #e1e5eb;
            border-radius: 8px;
            font-size: 16px;
            transition: all 0.3s;
            letter-spacing: 8px;
            font-weight: bold;
            text-align: center;
        }
        
        input[type="text"]:focus {
            border-color: #3498db;
            outline: none;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
        }
        
        .input-icon {
            position: absolute;
            left: 15px;
            top: 40px;
            color: #6c757d;
        }
        
        .error-message {
            background: #fee;
            color: #c33;
            padding: 12px;
            border-radius: 6px;
            margin-bottom: 20px;
            font-size: 14px;
            border-left: 4px solid #c33;
            display: none;
        }
        
        .error-message.show {
            display: block;
        }
        
        .success-message {
            background: #efe;
            color: #363;
            padding: 12px;
            border-radius: 6px;
            margin-bottom: 20px;
            font-size: 14px;
            border-left: 4px solid #363;
            display: none;
        }
        
        .success-message.show {
            display: block;
        }
        
        .attempts-warning {
            background: #fff3cd;
            color: #856404;
            padding: 12px;
            border-radius: 6px;
            margin-bottom: 20px;
            font-size: 14px;
            border-left: 4px solid #ffc107;
        }
        
        button {
            width: 100%;
            padding: 15px;
            background: #3498db;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.3s;
        }
        
        button:hover {
            background: #2980b9;
        }
        
        button:disabled {
            background: #bdc3c7;
            cursor: not-allowed;
        }
        
        .resend-container {
            text-align: center;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #e9ecef;
        }
        
        .resend-container p {
            margin-bottom: 15px;
            color: #6c757d;
        }
        
        #resendBtn {
            background: #2ecc71;
        }
        
        #resendBtn:hover {
            background: #27ae60;
        }
        
        #resendBtn:disabled {
            background: #bdc3c7;
        }
        
        .countdown {
            font-weight: bold;
            color: #e74c3c;
        }
        
        .help-text {
            text-align: center;
            margin-top: 20px;
            font-size: 14px;
            color: #6c757d;
        }
        
        .security-notice {
            background: #e8f4fc;
            border-radius: 8px;
            padding: 15px;
            margin-top: 25px;
            font-size: 13px;
            color: #2c3e50;
            border-left: 4px solid #3498db;
        }
        
        .security-notice h3 {
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .otp-instructions {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            font-size: 14px;
            color: #495057;
            border-left: 4px solid #e9ecef;
        }
        
        .footer {
            text-align: center;
            padding: 20px;
            color: white;
            font-size: 13px;
            margin-top: 20px;
            opacity: 0.8;
        }
        
        @media (max-width: 480px) {
            .card {
                border-radius: 10px;
            }
            
            .header {
                padding: 20px;
            }
            
            .form-container {
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <div class="header">
                <h1>Two-Factor Verification</h1>
                <p>Enter your verification code to continue</p>
            </div>
            
            <div class="form-container">
                <div class="logo">
                    <i class="fas fa-lock"></i>
                </div>
                
                <div class="otp-instructions">
                    <p>For your security, we've sent a verification code to your authenticated device. Please enter it below to complete your login.</p>
                </div>
                
                <div id="errorMessage" class="error-message">
                    <!-- Error message will be inserted here -->
                </div>
                
                <div id="successMessage" class="success-message">
                    <!-- Success message will be inserted here -->
                </div>
                
                <?php if ($_SESSION['otp_attempts'] > 0): ?>
                <div class="attempts-warning">
                    <strong>Warning:</strong> You have <?php echo (5 - $_SESSION['otp_attempts']); ?> attempts remaining before your account is temporarily locked.
                </div>
                <?php endif; ?>
                
                <form id="otpForm" method="POST" action="">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token'] ?? ''); ?>">
                    
                    <div class="input-group">
                        <label for="otp">Verification Code</label>
                        <i class="fas fa-key input-icon"></i>
                        <input type="text" id="otp" name="otp" placeholder="Enter 6-digit code" maxlength="6" required autofocus autocomplete="off">
                    </div>
                    
                    <button type="submit">Verify & Continue</button>
                </form>
                
                <div class="resend-container">
                    <p>Didn't receive the code? <span id="countdown" class="countdown">02:00</span></p>
                    <button id="resendBtn" disabled>Resend Verification Code</button>
                    <p id="resendLimit" style="display: none; color: #e74c3c; margin-top: 10px; font-size: 13px;">
                        Maximum resend attempts reached. Please contact support if you need assistance.
                    </p>
                </div>
                
                <div class="security-notice">
                    <h3><i class="fas fa-shield-alt"></i> Security Notice</h3>
                    <p>This system is protected by advanced security measures. Your verification code is time-sensitive and will expire shortly.</p>
                </div>
            </div>
        </div>
        
        <div class="footer">
            <p>&copy; 2023 Member Portal | All rights reserved</p>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('otpForm');
            const otpInput = document.getElementById('otp');
            const errorDiv = document.getElementById('errorMessage');
            const successDiv = document.getElementById('successMessage');
            const resendBtn = document.getElementById('resendBtn');
            const countdownEl = document.getElementById('countdown');
            const resendLimitEl = document.getElementById('resendLimit');
            
            // Focus on OTP input
            otpInput.focus();
            
            // Countdown timer for resend button
            let timeLeft = 120; // 2 minutes in seconds
            let countdownInterval = setInterval(updateCountdown, 1000);
            
            function updateCountdown() {
                if (timeLeft <= 0) {
                    clearInterval(countdownInterval);
                    countdownEl.textContent = '00:00';
                    
                    // Check if user has reached resend limit
                    if (<?php echo $_SESSION['otp_resend_attempts']; ?> >= 3) {
                        resendLimitEl.style.display = 'block';
                        resendBtn.style.display = 'none';
                    } else {
                        resendBtn.disabled = false;
                    }
                    return;
                }
                
                const minutes = Math.floor(timeLeft / 60);
                const seconds = timeLeft % 60;
                countdownEl.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
                timeLeft--;
            }
            
            // Allow only digits in OTP field
            otpInput.addEventListener('input', function() {
                this.value = this.value.replace(/[^0-9]/g, '');
            });
            
            // Form validation
            form.addEventListener('submit', function(e) {
                const otpValue = otpInput.value.trim();
                
                if (otpValue.length !== 6) {
                    e.preventDefault();
                    showError('Please enter a valid 6-digit verification code.');
                    return;
                }
                
                // If we get here, form is valid
                errorDiv.classList.remove('show');
            });
            
            // Resend OTP functionality
            resendBtn.addEventListener('click', function() {
                if (!resendBtn.disabled) {
                    resendOTP();
                }
            });
            
            // Function to show error messages
            function showError(message) {
                errorDiv.textContent = message;
                errorDiv.classList.add('show');
                successDiv.classList.remove('show');
                
                // Scroll to error message
                errorDiv.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            }
            
            // Function to show success messages
            function showSuccess(message) {
                successDiv.textContent = message;
                successDiv.classList.add('show');
                errorDiv.classList.remove('show');
                
                // Scroll to success message
                successDiv.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            }
            
            // Auto-submit when 6 digits are entered
            otpInput.addEventListener('input', function() {
                if (this.value.length === 6) {
                    // In a real application, you might want to automatically submit
                    // form.submit();
                }
            });
            
            // Resend OTP via AJAX
            function resendOTP() {
                resendBtn.disabled = true;
                
                // Create form data
                const formData = new FormData();
                formData.append('action', 'resend_otp');
                formData.append('csrf_token', '<?php echo $_SESSION['csrf_token']; ?>');
                
                // Make AJAX request
                fetch('<?php echo $_SERVER['PHP_SELF']; ?>', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showSuccess(data.message);
                        
                        // Reset countdown
                        clearInterval(countdownInterval);
                        timeLeft = 120;
                        countdownInterval = setInterval(updateCountdown, 1000);
                        
                        // Update UI based on remaining attempts
                        if (data.remaining_attempts <= 0) {
                            resendLimitEl.style.display = 'block';
                            resendBtn.style.display = 'none';
                            countdownEl.textContent = '00:00';
                        } else {
                            resendBtn.disabled = true;
                        }
                    } else {
                        showError(data.message);
                        resendBtn.disabled = false;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showError('An error occurred while resending the verification code.');
                    resendBtn.disabled = false;
                });
            }
        });
    </script>
</body>
</html>