<?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
        $stream_id = $_GET['stream_id'] ?? '';  // Se não tiver stream_id, deixa vazio

        // Alterar a extensão do stream_id de 
        if (strpos($stream_id, '.mp4') !== false) {
            $stream_id = str_replace('.mp4', '.mp4', $stream_id);
        }

        // Redirecionar para a nova URL
        $redirect_url = "{$url_user}/series/{$username}/{$password}/{$stream_id}";
        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."]);
}

?>