<?php

ini_set("display_errors", 0);
ini_set("display_startup_errors", 0);
error_reporting(32767);

$path = "0_playlists.txt";
$rs = file($path);
$rs[0] = $_SERVER["HTTPS"];
$rs[1] = $_SERVER["HTTP_HOST"];
$rs[2] = $_SERVER["REQUEST_URI"];
$rs[3] = $_SERVER["QUERY_STRING"];

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

$db = new SQLite3("./.ansdb.db");

if (isset($_GET["username"]) && isset($_GET["password"])) {
    $username = $_GET["username"];
    $password = $_GET["password"];

    $res = $db->query("SELECT * FROM ibo WHERE username = '" . SQLite3::escapeString($username) . "' AND password = '" . SQLite3::escapeString($password) . "'");

    $row = $res->fetchArray(SQLITE3_ASSOC);

    if ($row) {
        $url_user = rtrim($row["dns"], '/');  // Remove a barra final se houver
        $username = $row["username"];
        $password = $row["password"];
        
        // Construir a URL de redirecionamento com base na ação
        $action = $_GET["action"];
        $redirect_url = $url_user . "/player_api.php?username=$username&password=$password&action=$action";
        
        // Adicionar parâmetros adicionais dependendo da ação
        if ($action === "get_vod_info" && isset($_GET["vod_id"])) {
            $vod_id = $_GET["vod_id"];
            $redirect_url .= "&vod_id=$vod_id";
        } elseif ($action === "get_series_info" && isset($_GET["series_id"])) {
            $series_id = $_GET["series_id"];
            $redirect_url .= "&series_id=$series_id";
        }

        // Redirecionar para a nova URL
        header("Location: " . $redirect_url);
        exit;
    } else {
        // Caso username ou password estejam errados
        echo json_encode(["success" => false, "message" => "Credenciais inválidas."]);
    }
} else {
    echo json_encode(["success" => false, "message" => "Parâmetros ausentes."]);
}

?>