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

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

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

// Function to log debug messages
function debug_log($message) {
    file_put_contents("debug_log.txt", "[" . 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"]);
    debug_log("Token missing in request");
    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;
    debug_log("Token verified for User ID: $user_id");
} catch (Exception $e) {
    http_response_code(401);
    echo json_encode(["status" => "error", "message" => "Invalid or expired token"]);
    debug_log("Invalid or expired token: " . $e->getMessage());
    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"]);
    debug_log("Missing app_name in request");
    exit;
}

$app_name = $data["app_name"];

// Fetch secret key from DB
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"]);
    debug_log("App '$app_name' not found for User ID: $user_id");
    exit;
}

$secretKey = $row["secret"];
debug_log("Secret Key from DB for App '$app_name': $secretKey");

// ✅ Generate OTP Manually (No TwoFactorAuth)
function generateOTP($secret, $timeStep = 30, $digits = 6) {
    $timeCounter = floor(time() / $timeStep);
    // Debugging logs
   error_log("Current Unix Time: " . time());
   error_log("Time Step Counter: " . $timeCounter);
   
    $hash = hash_hmac('sha1', pack('N*', 0) . pack('N*', $timeCounter), $secret, true);
    $offset = ord($hash[19]) & 0xf;
    $binary = (ord($hash[$offset]) & 0x7f) << 24 |
              (ord($hash[$offset + 1]) & 0xff) << 16 |
              (ord($hash[$offset + 2]) & 0xff) << 8 |
              (ord($hash[$offset + 3]) & 0xff);
    $otp = $binary % pow(10, $digits);
    return str_pad($otp, $digits, '0', STR_PAD_LEFT);
}

// Generate OTP
$otp = generateOTP($secretKey);
debug_log("Generated OTP for App '$app_name': $otp");

// Send response
echo json_encode(["status" => "success", "otp" => $otp]);

?>
