<?php
session_start();
require 'vendor/autoload.php';
require 'db.php';

use OTPHP\TOTP;

if (!isset($_SESSION['username'])) {
    die("⚠️ Unauthorized access. Please log in.");
}

$username = $_SESSION['username'];

// Fetch user OTP secret from the database
$stmt = $pdo->prepare("SELECT email, otp_secret FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch();

if (!$user) {
    $_SESSION['error'] = "User authentication failed. Please log in again.";
    header("Location: login.php");
    exit();
}

$otpSecret = $user['otp_secret'];
$email = $user['email']; // Get user email for notifications
$totp = TOTP::create($otpSecret);
$userOTP = trim($_POST['otp'] ?? '');
$ipAddress = $_SERVER['REMOTE_ADDR']; // Get user's IP address

// Initialize attempt tracking
if (!isset($_SESSION['otp_attempts'])) {
    $_SESSION['otp_attempts'] = 0;
    $_SESSION['otp_locked_until'] = 0;
}

// Check if user is locked out
if ($_SESSION['otp_attempts'] >= 5 && time() < $_SESSION['otp_locked_until']) {
    $_SESSION['error'] = "Too many failed attempts. Try again later.";
    header("Location: transaction_approval.php");
    exit();
}

// Validate OTP
if ($totp->verify($userOTP)) {
    $_SESSION['success'] = "✅ OTP verified! Transaction Approved.";
    $_SESSION['otp_attempts'] = 0; // Reset attempts on success
    header("Location: success_page.php");
    exit();
} else {
    $_SESSION['otp_attempts']++; // Increase failed attempts
    if ($_SESSION['otp_attempts'] >= 5) {
        $_SESSION['otp_locked_until'] = time() + 300; // Lock for 5 mins

        // Send email notification
        $subject = "🚨 Security Alert: Multiple OTP Failures";
        $message = "
            <html>
            <head><title>Security Alert</title></head>
            <body>
                <h2>Failed OTP Attempts Detected</h2>
                <p><strong>Username:</strong> $username</p>
                <p><strong>Email:</strong> $email</p>
                <p><strong>IP Address:</strong> $ipAddress</p>
                <p><strong>Time:</strong> " . date('Y-m-d H:i:s') . "</p>
                <p>We've detected multiple failed OTP attempts on your account. If this wasn't you, please secure your account immediately.</p>
            </body>
            </html>
        ";

        // Email Headers
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
        $headers .= "From: security@yourapp.com" . "\r\n";

        // Send email to user
        mail($email, $subject, $message, $headers);

        // Optionally send alert to admin
        $adminEmail = "admin@yourapp.com";
        mail($adminEmail, $subject, $message, $headers);
    }

    $_SESSION['error'] = "Invalid OTP. Try again.";
    header("Location: transaction_approval.php");
    exit();
}
?>




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verify OTP</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-4">
    <h2>Enter OTP for Authentication</h2>
    <?php if (!empty($message)): ?>
        <div class="alert alert-info"><?= $message ?></div>
    <?php endif; ?>

    <form method="post">
        <div class="form-group">
            <label for="otp">Enter OTP:</label>
            <input type="text" class="form-control" id="otp" name="otp" required>
        </div>
        <button type="submit" class="btn btn-primary">Verify OTP</button>
    </form>
</div>
</body>
</html>
