<?php
// player_api.php - VERSÃO FINAL REVISADA (ESTABILIDADE TOTAL)
// --------------------------------------------------------------------

error_reporting(0);
ini_set('display_errors', 0);

if (ob_get_level()) ob_end_clean();
ob_start();
require_once 'includes/db.php';
ob_clean(); 

header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");

// --- 1. ENTRADA DE DADOS ---
$username = $_REQUEST['username'] ?? '';
$password = $_REQUEST['password'] ?? '';
$action   = $_REQUEST['action'] ?? '';

// --- 2. LOGIN ---
try {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1");
    $stmt->execute([$username, $password]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) { $user = false; }

// Se usuário não existir
if (!$user) { 
    echo json_encode(['user_info' => ['auth' => 0]]); 
    exit; 
}

// Verifica validade da conta de forma segura (evita bug de conta vitalícia)
$is_expired = false;
if (!empty($user['expire_date'])) {
    $exp_ts = strtotime($user['expire_date']);
    if ($exp_ts > 0 && $exp_ts < time()) {
        $is_expired = true;
    }
}

// Se estiver bloqueado ou vencido
if ($user['active'] == 0 || $is_expired) { 
    echo json_encode(['user_info' => ['auth' => 0]]); 
    exit;
}

// --- 3. BOUQUETS (PERMISSÕES) ---
$allowed_ch_cats = []; $allowed_mov_cats = []; $allowed_ser_cats = [];
$has_bouquets = false;

$user_bouquets = json_decode($user['bouquets'] ?? '[]', true);
if (!empty($user_bouquets)) {
    $has_bouquets = true;
    $placeholders = implode(',', array_fill(0, count($user_bouquets), '?'));
    try {
        $stmt_bq = $pdo->prepare("SELECT * FROM bouquets WHERE id IN ($placeholders)");
        $stmt_bq->execute($user_bouquets);
        while($bq = $stmt_bq->fetch(PDO::FETCH_ASSOC)) {
            $allowed_ch_cats = array_merge($allowed_ch_cats, json_decode($bq['bouq_channels'] ?? '[]', true));
            $allowed_mov_cats = array_merge($allowed_mov_cats, json_decode($bq['bouq_movies'] ?? '[]', true));
            $allowed_ser_cats = array_merge($allowed_ser_cats, json_decode($bq['bouq_series'] ?? '[]', true));
        }
    } catch(Exception $e) {}
}

$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
$host_parts = explode(':', $_SERVER['HTTP_HOST']);
$host_clean = $host_parts[0];
$port = $_SERVER['SERVER_PORT'] ?? "80";

// --- RESPOSTA DE LOGIN (AUTENTICAÇÃO PADRÃO XTREAM CODES) ---
if (empty($action)) {
    echo json_encode([
        "user_info" => [
            "username" => $user['username'],
            "password" => $user['password'],
            "message" => "", // Campo obrigatório para Smarters
            "auth" => 1,
            "status" => "Active",
            "exp_date" => !empty($user['expire_date']) ? (string)strtotime($user['expire_date']) : "0",
            "is_trial" => (string)($user['is_trial'] ?? "0"),
            "active_cons" => "0", // Campo obrigatório
            "created_at" => "0",  // Campo obrigatório
            "max_connections" => (string)($user['max_connections'] ?? "1"),
            "allowed_output_formats" => ["m3u8", "ts", "rtmp"]
        ],
        "server_info" => [
            "url" => $host_clean,
            "port" => (string)$port,
            "https_port" => "443",
            "server_protocol" => $protocol,
            "rtmp_port" => (string)$port,
            "timezone" => "America/Sao_Paulo",
            "timestamp_now" => time(),
            "time_now" => date('Y-m-d H:i:s'), // Campo obrigatório para TiviMate
            "process" => true
        ]
    ]); 
    exit;
}

// =====================================================================
// CANAIS AO VIVO
// =====================================================================
if ($action == 'get_live_categories') {
    $sql = "SELECT id as category_id, name as category_name, 0 as parent_id FROM categories WHERE type='channel'";
    if ($has_bouquets && !empty($allowed_ch_cats)) {
        $sql .= " AND id IN (".implode(',', array_map('intval', $allowed_ch_cats)).")";
    }
    echo json_encode($pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC)); exit;
}

if ($action == 'get_live_streams') {
    $cat_id = (int)($_REQUEST['category_id'] ?? 0);
    $sql = "SELECT id as stream_id, name, logo_url as stream_icon, category_id, stream_url FROM channels";
    $where = [];
    if ($has_bouquets && !empty($allowed_ch_cats)) { $where[] = "category_id IN (".implode(',', array_map('intval', $allowed_ch_cats)).")"; }
    if ($cat_id > 0) { $where[] = "category_id = $cat_id"; }
    if (!empty($where)) { $sql .= " WHERE " . implode(' AND ', $where); }
    
    $res = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    $output = [];
    foreach($res as $index => $r) { 
        $item = [
            "num" => $index + 1,
            "name" => $r['name'],
            "stream_type" => "live",
            "stream_id" => (int)$r['stream_id'],
            "stream_icon" => $r['stream_icon'],
            "epg_channel_id" => null,
            "added" => (string)time(),
            "category_id" => (string)$r['category_id'],
            "custom_sid" => "",
            "tv_archive" => 0,
            "direct_source" => "",
            "tv_archive_duration" => 0
        ];
        if (strpos($r['stream_url'], '.m3u8') === false) { $item['stream_url'] = $r['stream_url'] . ".m3u8"; }
        else { $item['stream_url'] = $r['stream_url']; }
        $item['container_extension'] = "m3u8";
        
        $output[] = $item;
    }
    echo json_encode($output); exit;
}

// =====================================================================
// FILMES (VOD)
// =====================================================================
if ($action == 'get_vod_categories') {
    $sql = "SELECT id as category_id, name as category_name, 0 as parent_id FROM categories WHERE type='movie'";
    if ($has_bouquets && !empty($allowed_mov_cats)) {
        $sql .= " AND id IN (".implode(',', array_map('intval', $allowed_mov_cats)).")";
    }
    echo json_encode($pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC)); exit;
}

if ($action == 'get_vod_streams') {
    $cat_id = (int)($_REQUEST['category_id'] ?? 0);
    $sql = "SELECT id as stream_id, name, cover_url as stream_icon, category_id, stream_url, description as plot FROM movies";
    $where = [];
    if ($has_bouquets && !empty($allowed_mov_cats)) { $where[] = "category_id IN (".implode(',', array_map('intval', $allowed_mov_cats)).")"; }
    if ($cat_id > 0) { $where[] = "category_id = $cat_id"; }
    if (!empty($where)) { $sql .= " WHERE " . implode(' AND ', $where); }

    $res = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    $output = [];
    foreach($res as $index => $r) {
        $ext = (strpos($r['stream_url'], '.mkv') !== false) ? 'mkv' : 'mp4';
        $output[] = [
            "num" => $index + 1,
            "name" => $r['name'],
            "stream_type" => "movie",
            "stream_id" => (int)$r['stream_id'],
            "stream_icon" => $r['stream_icon'],
            "rating" => 0,
            "added" => (string)time(),
            "category_id" => (string)$r['category_id'],
            "container_extension" => $ext,
            "custom_sid" => "",
            "direct_source" => "",
            "stream_url" => $r['stream_url']
        ];
    }
    echo json_encode($output); exit;
}

if ($action == 'get_vod_info') {
    $vod_id = (int)($_REQUEST['vod_id'] ?? 0);
    $info = $pdo->query("SELECT * FROM movies WHERE id=$vod_id")->fetch(PDO::FETCH_ASSOC);
    if (!$info) { echo json_encode([]); exit; }
    
    echo json_encode([
        "info" => [
            "kinopoisk_url" => "",
            "tmdb_id" => "",
            "name" => $info['name'],
            "o_name" => $info['name'],
            "cover_big" => $info['cover_url'],
            "movie_image" => $info['cover_url'],
            "releasedate" => "",
            "episode_run_time" => 0,
            "youtube_trailer" => "",
            "director" => "",
            "actors" => "",
            "cast" => "",
            "description" => $info['description'] ?? "",
            "plot" => $info['description'] ?? "",
            "age" => "",
            "mpaa_rating" => "",
            "rating_count_kinopoisk" => 0,
            "country" => "",
            "genre" => "",
            "backdrop_path" => [$info['cover_url']],
            "duration_secs" => 0,
            "duration" => "00:00:00",
            "bitrate" => 0,
            "rating" => 0
        ],
        "movie_data" => [
            "stream_id" => (int)$info['id'],
            "name" => $info['name'],
            "title" => $info['name'],
            "year" => "",
            "added" => (string)time(),
            "category_id" => (string)$info['category_id'],
            "container_extension" => (strpos($info['stream_url'] ?? '', '.mkv') !== false) ? 'mkv' : 'mp4',
            "custom_sid" => "",
            "direct_source" => "",
            "stream_url" => $info['stream_url'] ?? ''
        ]
    ]);
    exit;
}

// =====================================================================
// SÉRIES - AGRUPAMENTO POR TEMPORADAS E EPISÓDIOS (PADRÃO XTREAM)
// =====================================================================
if ($action == 'get_series_categories') {
    $sql = "SELECT id as category_id, name as category_name, 0 as parent_id FROM categories WHERE type='series'";
    if ($has_bouquets && !empty($allowed_ser_cats)) {
        $sql .= " AND id IN (".implode(',', array_map('intval', $allowed_ser_cats)).")";
    }
    echo json_encode($pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC)); exit;
}

// Lista principal das Séries
if ($action == 'get_series') {
    $cat_id = (int)($_REQUEST['category_id'] ?? 0);
    $sql = "SELECT id as series_id, name, cover_url as cover, category_id, description as plot FROM series";
    $where = [];
    if ($has_bouquets && !empty($allowed_ser_cats)) { $where[] = "category_id IN (".implode(',', array_map('intval', $allowed_ser_cats)).")"; }
    if ($cat_id > 0) { $where[] = "category_id = $cat_id"; }
    if (!empty($where)) { $sql .= " WHERE " . implode(' AND ', $where); }
    $sql .= " ORDER BY id DESC";

    $res = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    $output = [];
    foreach($res as $index => $r) { 
        $output[] = [
            "num" => $index + 1,
            "name" => $r['name'],
            "title" => $r['name'],
            "year" => "",
            "series_id" => (int)$r['series_id'],
            "cover" => $r['cover'] ?? '',
            "plot" => $r['plot'] ?? '',
            "cast" => "",
            "director" => "",
            "genre" => "",
            "releaseDate" => "",
            "last_modified" => (string)time(),
            "rating" => "0",
            "rating_5based" => 0,
            "backdrop_path" => [$r['cover'] ?? ''],
            "youtube_trailer" => "",
            "episode_run_time" => "0",
            "category_id" => (string)$r['category_id']
        ];
    }
    echo json_encode($output); exit;
}

// Entrando na Série (Mostra as Temporadas e Episódios)
if ($action == 'get_series_info') {
    $sid = (int)($_REQUEST['series_id'] ?? 0);
    $info = $pdo->query("SELECT id, name, cover_url as cover, description as plot, category_id FROM series WHERE id=$sid")->fetch(PDO::FETCH_ASSOC);
    if (!$info) { echo json_encode([]); exit; }

    // Busca os episódios junto com o nome/id da temporada
    $stmt = $pdo->prepare("
        SELECT e.id as episode_id, e.name as episode_title, e.stream_url, e.cover_url, 
               s.id as season_id, s.name as season_name 
        FROM episodes e 
        JOIN seasons s ON e.season_id = s.id 
        WHERE s.series_id = ? 
        ORDER BY s.id ASC, e.id ASC
    ");
    $stmt->execute([$sid]);
    
    $episodes = []; 
    $seasons = [];
    $season_counts = [];

    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        // Tenta extrair o número da temporada (ex: "Temporada 2" -> 2)
        $s_num = (int)filter_var($row['season_name'], FILTER_SANITIZE_NUMBER_INT);
        if ($s_num <= 0) $s_num = 1;
        
        if (!isset($season_counts[$s_num])) $season_counts[$s_num] = 0;
        $season_counts[$s_num]++;

        $ep_cover = !empty($row['cover_url']) ? $row['cover_url'] : $info['cover'];
        $ext = (strpos($row['stream_url'], '.mkv') !== false) ? 'mkv' : 'mp4';
        
        // Estrutura EXATA do Xtream UI para Episódios
        $episodes[(string)$s_num][] = [
            "id" => (string)$row['episode_id'], 
            "episode_num" => $season_counts[$s_num], 
            "title" => $row['episode_title'],
            "container_extension" => $ext,
            "info" => [
                "movie_image" => $ep_cover, 
                "plot" => "Episódio " . $season_counts[$s_num], 
                "duration" => "00:00:00",
                "rating" => "0",
                "releasedate" => ""
            ], 
            "custom_sid" => "",
            "added" => (string)time(),
            "season" => $s_num,
            "direct_source" => "",
            "stream_url" => $row['stream_url'] // Mantido caso o app queira o link direto
        ];

        // Monta o objeto das temporadas
        if (!isset($seasons[$s_num])) {
            $seasons[$s_num] = [
                "air_date" => "",
                "episode_count" => 0, // Será atualizado logo abaixo
                "id" => (int)$row['season_id'], 
                "name" => "Temporada " . $s_num, 
                "overview" => "",
                "season_number" => $s_num, 
                "cover" => $info['cover'], 
                "cover_big" => $info['cover']
            ];
        }
    }

    // Atualiza a contagem total de episódios por temporada
    foreach ($seasons as $num => &$season) {
        $season['episode_count'] = $season_counts[$num] ?? 0;
    }

    echo json_encode([
        "seasons" => array_values($seasons), 
        "info" => [
            "name" => $info['name'], 
            "cover" => $info['cover'], 
            "plot" => $info['plot'], 
            "cast" => "",
            "director" => "",
            "genre" => "",
            "releaseDate" => "",
            "last_modified" => (string)time(),
            "rating" => "0",
            "rating_5based" => 0,
            "backdrop_path" => [$info['cover']],
            "youtube_trailer" => "",
            "episode_run_time" => "0",
            "category_id" => (string)$info['category_id']
        ], 
        "episodes" => (object)$episodes
    ]);
    exit;
}

// =====================================================================
// SHORT EPG (Guia de Programação Rápido)
// =====================================================================
if ($action == 'get_short_epg') {
    echo json_encode(["epg_listings" => []]);
    exit;
}
?>
