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

use OTPHP\TOTP;

if (!isset($_SESSION["user_id"])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION["user_id"];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $enteredOtp = $_POST["otp"];

    // Fetch the stored secret
    $stmt = $conn->prepare("SELECT totp_secret FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->bind_result($totp_secret);
    $stmt->fetch();
    $stmt->close();

    if ($totp_secret) {
        $otp = TOTP::create($totp_secret);

        if ($otp->verify($enteredOtp)) {
            echo "<script>alert('OTP Verified!'); window.location='dashboard.php';</script>";
        } else {
            echo "<script>alert('Invalid OTP, try again!');</script>";
        }
    }
}
?>

<!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 class="container mt-5">
    <h2>Enter OTP</h2>
    <form method="POST">
        <div class="form-group">
            <label>Enter the 6-digit code:</label>
            <input type="text" name="otp" class="form-control" required>
        </div>
        <button type="submit" class="btn btn-success">Verify</button>
    </form>
</body>
</html>
