<?php
require 'config_pdo.php';
require '../vendor/autoload.php'; // Load dependencies

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

date_default_timezone_set('UTC');

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

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

// Extract and verify token
$token = trim(str_replace("Bearer", "", $headers["Authorization"]));
try {
    $decoded = JWT::decode($token, new Key(JWT_SECRET_KEY, "HS256"));
    $user_id = $decoded->sub;
} catch (Exception $e) {
    http_response_code(401);
    echo json_encode(["status" => "error", "message" => "Invalid or expired token"]);
    exit;
}

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

// Fetch secret key from DB
global $pdo;
$app_name = $data["app_name"];
$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"]);
    exit;
}

$secretKey = $row["secret"];

// ✅ Generate OTP Using OTPHP
$totp = TOTP::createFromSecret($secretKey);
$otp = $totp->now();

$currentTime = time();
$timeCounter = floor($currentTime / 30);

// ✅ Debug Logging
$logMessage = "[" . date("Y-m-d H:i:s") . "] Token verified for User ID: $user_id\n";
$logMessage .= "[" . date("Y-m-d H:i:s") . "] Secret Key from DB for App '$app_name': $secretKey\n";
$logMessage .= "[" . date("Y-m-d H:i:s") . "] Generated OTP for App '$app_name': $otp\n";
$logMessage .= "[" . date("Y-m-d H:i:s") . "] Server Time: " . date('Y-m-d H:i:s') . " UTC\n";
$logMessage .= "[" . date("Y-m-d H:i:s") . "] Current Unix Time: $currentTime\n";
$logMessage .= "[" . date("Y-m-d H:i:s") . "] Time Step Counter: $timeCounter\n";
//file_put_contents("debug_log.txt", $logMessage, FILE_APPEND);

echo json_encode(["status" => "success", "otp" => $otp]);
?>
