<?php
require '../vendor/autoload.php';
require '../db_config.php';
require 'authenticate.php'; // Secure API

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

// Authenticate API Key
$api_key = $_SERVER['HTTP_API_KEY'] ?? '';
$stmt = $pdo->prepare("SELECT user_id, app_id FROM registered_apps WHERE api_key = ?");
$stmt->execute([$api_key]);
$app = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$app) {
    echo json_encode(["error" => "Invalid API Key"]);
    exit;
}

$user_id = $app['user_id'];
$app_id = $app['app_id'];

// Get request data
$data = json_decode(file_get_contents("php://input"), true);
$otp = $data['otp'] ?? null;

if (!$otp) {
    echo json_encode(["error" => "OTP is required"]);
    exit;
}

// Fetch the stored secret
$stmt = $pdo->prepare("SELECT secret FROM scanned_auths WHERE user_id = ? AND app_id = ?");
$stmt->execute([$user_id, $app_id]);
$auth = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$auth) {
    echo json_encode(["error" => "No authentication found for this app"]);
    exit;
}

$totp = OTPHP\TOTP::create($auth['secret']);

if ($totp->verify($otp)) {
    echo json_encode(["success" => true, "message" => "OTP is valid"]);
} else {
    echo json_encode(["success" => false, "message" => "Invalid OTP"]);
}
?>
