<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/_app_guard.php';
app_guard_validate();

header("Content-Type: application/json; charset=utf-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') {
    http_response_code(204);
    exit;
}

function remote_out(array $payload): void {
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$allow = ["", "live", "movies", "series", "kids", "update", "config", "renew", "logout", "sair"];
$file = dirname(__DIR__) . "/remote_cmd.txt";
$method = strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET'));

if ($method === 'POST') {
    $cmd = strtolower(trim((string)($_POST["cmd"] ?? "")));
    if (!in_array($cmd, $allow, true)) {
        remote_out(["ok" => false, "status" => "invalid_cmd"]);
    }
    @file_put_contents($file, $cmd);
    remote_out(["ok" => true, "status" => "ok", "cmd" => $cmd, "ts" => time()]);
}

$cmd = is_file($file) ? strtolower(trim((string)@file_get_contents($file))) : "";
if (!in_array($cmd, $allow, true)) {
    $cmd = "";
}

remote_out([
    "ok" => true,
    "status" => "ok",
    "cmd" => $cmd,
    "ts" => is_file($file) ? (int)@filemtime($file) : 0
]);
