<?php
require '../vendor/autoload.php';
require '../db.php';
use OTPHP\TOTP;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $app_id = $_POST['app_id'] ?? null;
    $api_key = $_POST['api_key'] ?? null;
    $user_id = $_POST['user_id'] ?? null;

    // Validate API Key
    $stmt = $conn->prepare("SELECT * FROM registered_apps WHERE app_id = ? AND api_key = ?");
    $stmt->bind_param("ss", $app_id, $api_key);
    $stmt->execute();
    if (!$stmt->get_result()->fetch_assoc()) {
        die(json_encode(["error" => "Invalid API credentials"]));
    }

    // Fetch user's secret
    $stmt = $conn->prepare("SELECT secret FROM authentications WHERE user_id = ? AND app_id = ?");
    $stmt->bind_param("is", $user_id, $app_id);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    if (!$result) {
        die(json_encode(["error" => "User not found"]));
    }

    // Generate OTP
    $totp = TOTP::create($result['secret']);
    $otp = $totp->now();

    echo json_encode(["otp" => $otp]);
}
?>
