<?php
require 'config_pdo.php';
require '../vendor/autoload.php'; // Ensure dependencies are loaded

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use OTPHP\TOTP;

date_default_timezone_set('UTC'); // Set a consistent timezone

header("Content-Type: application/json");

// Debug log file
$logFile = 'verify_debug_log.txt';

// Function to log messages
function logMessage($message)
{
    global $logFile;
    file_put_contents($logFile, "[" . date("Y-m-d H:i:s") . "] " . $message . PHP_EOL, FILE_APPEND);
}

// Check for Authorization token
$headers = getallheaders();
if (!isset($headers["Authorization"])) {
    http_response_code(401);
    echo json_encode(["status" => "error", "message" => "Token missing"]);
    logMessage("Authorization token missing");
    exit;
}

$token = trim(str_replace("Bearer", "", $headers["Authorization"]));
try {
    $decoded = JWT::decode($token, new Key(JWT_SECRET_KEY, "HS256"));
    $user_id = $decoded->sub;
    logMessage("Token verified for User ID: $user_id");
} catch (Exception $e) {
    http_response_code(401);
    echo json_encode(["status" => "error", "message" => "Invalid token"]);
    logMessage("Invalid token: " . $e->getMessage());
    exit;
}

// Get app_name and OTP from request
$data = json_decode(file_get_contents("php://input"), true);
if (!isset($data["app_name"]) || !isset($data["otp"])) {
    echo json_encode(["status" => "error", "message" => "Missing app_name or OTP"]);
    logMessage("Missing app_name or OTP in request");
    exit;
}

$app_name = $data["app_name"];
$otp = $data["otp"];
logMessage("Received verification request - App: $app_name, OTP: $otp");

// Fetch secret from database
global $pdo;
$sql = "SELECT secret FROM scanned_auths WHERE user_id = :user_id AND app_name = :app_name";
$stmt = $pdo->prepare($sql);
$stmt->execute(["user_id" => $user_id, "app_name" => $app_name]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$row) {
    echo json_encode(["status" => "error", "message" => "App not found"]);
    logMessage("App '$app_name' not found for User ID: $user_id");
    exit;
}

$secretKey = $row["secret"];
logMessage("Secret Key from DB: " . $secretKey);

// Get current Unix time and time step
$currentUnixTime = time();
$timeStepCounter = floor($currentUnixTime / 30);
$serverTime = date("Y-m-d H:i:s e"); // Format: YYYY-MM-DD HH:MM:SS UTC
$serverTimezone = date_default_timezone_get();

logMessage("Server Time: $serverTime");
logMessage("Server Timezone: $serverTimezone");
logMessage("Current Unix Time: $currentUnixTime");
logMessage("Time Step Counter: $timeStepCounter");

// Generate OTP from secret
$totp = TOTP::createFromSecret($secretKey);
$generatedOTP = $totp->now();
logMessage("Generated OTP: " . $generatedOTP);
logMessage("User-entered OTP: " . $otp);

// Verify OTP with a time window tolerance of 2 past/future OTPs
if ($totp->verify($otp, null, 2)) {
    echo json_encode(["status" => "success", "message" => "OTP is valid"]);
    logMessage("OTP verified successfully for App: $app_name");
} else {
    echo json_encode(["status" => "error", "message" => "Invalid OTP"]);
    logMessage("Invalid OTP entered for App: $app_name");
}
?>
