<?php
require 'config_pdo.php';
require '../vendor/autoload.php'; // Ensure dependencies are loaded

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

date_default_timezone_set('UTC'); // Set a consistent timezone

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;
}

$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 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;
}

$app_name = $data["app_name"];

// Check if app exists for the user
global $pdo;
$sql = "SELECT * 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;
}

// Delete the app
$sql = "DELETE 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]);

if ($stmt->rowCount() > 0) {
    echo json_encode(["status" => "success", "message" => "App deleted successfully"]);
} else {
    echo json_encode(["status" => "error", "message" => "Failed to delete app"]);
}
?>
