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

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

date_default_timezone_set('UTC'); // Ensure consistent timezone
header("Content-Type: application/json");

// Debug log file
$logFile = 'list_debug_log.txt';
function logMessage($message) {
    global $logFile;
    file_put_contents($logFile, "[" . date("Y-m-d H:i:s") . "] " . $message . PHP_EOL, FILE_APPEND);
}

// Authenticate user
$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;
}

// Fetch registered apps
global $pdo;
$sql = "SELECT app_name, created_at FROM scanned_auths WHERE user_id = :user_id ORDER BY created_at DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute(["user_id" => $user_id]);
$apps = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (!$apps) {
    echo json_encode(["status" => "error", "message" => "No registered apps found"]);
    logMessage("No registered apps for User ID: $user_id");
    exit;
}

// Return apps list
echo json_encode(["status" => "success", "apps" => $apps]);
logMessage("Registered apps listed for User ID: $user_id");

?>
