<?php

include 'header.php';
require 'vendor/autoload.php';
use OTPHP\TOTP;

//session_start();
include 'db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $entered_otp = trim($_POST['otp']);
    $user_id = $_SESSION['user_id'];

    $stmt = $conn->prepare("SELECT secret FROM authentications WHERE user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($row = $result->fetch_assoc()) {
        $secret = trim($row['secret']);
        $totp = TOTP::create($secret);

        if ($totp->verify($entered_otp)) {
            $_SESSION['flash_message'] = "✅ OTP is VALID! Transaction Approved.";
        } else {
            $_SESSION['flash_message'] = "❌ Invalid OTP! Try again.";
        }
    } else {
        $_SESSION['flash_message'] = "❌ No authentication record found.";
    }

    $stmt->close();
    $conn->close();
    header("Location: validate_otp.php");
    exit;
}
?>



<h2>Enter OTP for Transaction Approval</h2>

<?php
if (isset($_SESSION['flash_message'])) {
    echo '<div class="alert alert-info">' . $_SESSION['flash_message'] . '</div>';
    unset($_SESSION['flash_message']);
}
?>

<form method="POST">
    <input type="text" name="otp" class="form-control mb-3" placeholder="Enter OTP" required>
    <button type="submit" class="btn btn-success">Validate</button>
</form>

<?php include 'footer.php'; ?>
