<?php
error_reporting(0);

// Configuração do banco de dados
$servername = "localhost";
$dbname = "newp2p";
$serverport = ;
$username = "newp2p";
$password = '312680Le';

$dsn = "mysql:host=$servername;port=$serverport;dbname=$dbname;";
$connection = new PDO($dsn, $username, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

// Pegando os dados da URL
$username_ = $_GET['username'];
$password_ = $_GET['password'];

// Consultando o DNS associado ao usuário
$stmt = $connection->prepare("SELECT * FROM `users` WHERE username_ = ? AND password = ?");
$stmt->bindParam(1, $username_);
$stmt->bindParam(2, $password_);
$stmt->execute();

$seller = 1; // Padrão, caso não encontre o usuário
if ($stmt->rowCount() > 0) {
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $seller = $row['member_id'];
    }
}

// Conectando ao banco SQLite para pegar o DNS
$db = new SQLite3('./api/.ansdb.db');
$rows3 = $db->query("SELECT * FROM dns WHERE id = '$seller'");
$row3 = $rows3->fetchArray();

$portal_one = $row3['portal1'];  // Supondo que você queira o primeiro portal (ajuste conforme necessário)
$api_url = $portal_one;
//$api_url = $portal_one . "/player_api.php";

// Função para obter os dados da API via GET
function getApiData($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);

    $response = curl_exec($ch);
    
    if (curl_errno($ch)) {
        echo json_encode(["error" => "Erro CURL: " . curl_error($ch)]);
        exit;
    }

    curl_close($ch);
    
    return json_decode($response, true);
}

// Chamadas para obter os streams e categorias com o DNS, username e password
$live_streams_url = "{$api_url}/player_api.php?username={$username_}&password={$password_}&action=get_live_streams";
$live_categories_url = "{$api_url}/player_api.php?username={$username_}&password={$password_}&action=get_live_categories";

$live_streams = getApiData($live_streams_url);
$live_categories = getApiData($live_categories_url);

// Verifica se os dados retornaram corretamente
if (!isset($live_streams) || !isset($live_categories)) {
    echo json_encode(["error" => "Erro ao obter os dados da API"]);
    exit;
}

// Inicializa o array de resposta com bouquet fixo
$response = [
    "bouquets" => [
        [
            "bouquet_id" => "1",
            "bouquet_name" => "Brazil",
            "bouquet_order" => 0,
            "bouquet_expires" => ""
        ]
    ],
    "packages" => [],
    "channels" => []
];

// Processa as categorias para "packages"
foreach ($live_categories as $category) {
    $category_id = (int)$category['category_id'];

    $response['packages'][] = [
        'name' => $category['category_name'],
        'id' => $category_id,
        'language' => 'Brazil',
        'bouquet_id' => 1, // Bouquet fixo "Brazil"
        'is_adult' => isset($category['category_is_adult']) ? $category['category_is_adult'] : "0"
    ];
}

// Processa os canais para "channels"
foreach ($live_streams as $stream) {
    $package_id = (int)$stream['category_id'];

    $response['channels'][] = [
        'name' => $stream['name'],
        'number' => (int)$stream['stream_id'],
        'icon' => $stream['stream_icon'] ?? "",
        'streamer' => (int)$stream['stream_id'],
        'epg_name' => $stream['epg_channel_id'] ?? null,
        'timeshift' => isset($stream['tv_archive']) ? (int)$stream['tv_archive'] : 0,
        'language' => 'Brazil',
        'package_id' => $package_id,
        'drm_id' => null,
        'order' => isset($stream['stream_id']) ? (int)$stream['stream_id'] : 0,
        'url' => "{$api_url}/live/{$username_}/{$password_}/{$stream['stream_id']}.m3u8",
        'timeshift_url' => "{$api_url}/streaming/timeshift.php?stream={$stream['stream_id']}&start=%s&duration=%d&username={$username_}&password={$password_}"
    ];
}

// Retorna a resposta JSON formatada
header('Content-Type: application/json');
echo json_encode($response, JSON_PRETTY_PRINT);
?>