<?php
// player_api.php - Original com Ajuste para Monitor (content_id)
// --- LIMPEZA DE BUFFER E ERROS ---
error_reporting(0); // Evita que erros de PHP quebrem o JSON do aplicativo
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. RECEBE DADOS ---
$username = $_REQUEST['username'] ?? '';
$password = $_REQUEST['password'] ?? '';
$action   = $_REQUEST['action'] ?? '';

// --- 2. LOGIN / AUTENTICAÇÃO ---
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; }

if (!$user) { 
    echo json_encode(['user_info' => ['auth' => 0], 'status' => 'Login Failed']); exit; 
}

// TRAVA DE BLOQUEIO
if ($user['active'] == 0 || strtotime($user['expire_date']) < time()) {
    echo json_encode(['user_info' => ['auth' => 0], 'status' => 'Account Blocked or Expired']); 
    exit;
}

// --- 3. LÓGICA DE BOUQUETS ---
$allowed_ch_cats = [];
$allowed_mov_cats = [];
$allowed_ser_cats = [];
$has_bouquets = false;

try {
    $user_bouquets = json_decode($user['bouquets'] ?? '[]', true);
    if (!empty($user_bouquets)) {
        $has_bouquets = true;
        // Busca os dados dos pacotes
        $placeholders = implode(',', array_fill(0, count($user_bouquets), '?'));
        $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) {}

// --- DADOS DO SERVIDOR ---
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
$host = $_SERVER['HTTP_HOST'];
$port = "80";

// RESPOSTA DE LOGIN
if (empty($action)) {
    try {
        $user_ip = $_SERVER['REMOTE_ADDR'];
        $ua = $_SERVER['HTTP_USER_AGENT'] ?? 'App';
        
        // Limpa logins antigos
        $pdo->prepare("DELETE FROM active_connections WHERE user_id = ?")->execute([$user['id']]);
        
        // --- AQUI ESTÁ A "OPÇÃO DO STREAM.PHP" (Ajuste para o Monitor) ---
        // Alterado de 'stream_id' para 'content_id' para compatibilidade com o monitor novo
        $pdo->prepare("INSERT INTO active_connections (user_id, username, content_id, stream_type, user_ip, start_time, user_agent) VALUES (?, ?, 0, 'app_login', ?, ?, ?)")->execute([$user['id'], $user['username'], $user_ip, time(), $ua]);
    } catch (Exception $e) {}

    $response = [
        "user_info" => [
            "username" => $user['username'],
            "password" => $user['password'],
            "message" => "Login OK",
            "auth" => 1,
            "status" => "Active",
            "exp_date" => (string)strtotime($user['expire_date']),
            "is_trial" => "0",
            "active_cons" => "0",
            "created_at" => "1600000000",
            "max_connections" => "1",
            "allowed_output_formats" => ["m3u8", "ts", "rtmp"]
        ],
        "server_info" => [
            "url" => $host, "port" => $port, "https_port" => "443", "server_protocol" => $protocol, "rtmp_port" => "8880", "timezone" => "America/Sao_Paulo", "timestamp_now" => time(), "time_now" => date("Y-m-d H:i:s")
        ]
    ];
    echo json_encode($response); exit;
}

// =====================================================================
// CONTEÚDOS COM FILTRO DE BOUQUETS
// =====================================================================

// --- CANAIS (LIVE) ---
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)) {
        $ids = implode(',', array_map('intval', $allowed_ch_cats));
        $sql .= " AND id IN ($ids)";
    } elseif ($has_bouquets && empty($allowed_ch_cats)) {
        echo json_encode([]); exit;
    }
    
    $data = $pdo->query("$sql ORDER BY order_id ASC")->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($data); exit;
}

if ($action == 'get_live_streams') {
    $sql = "SELECT id, name, logo_url, category_id, epg_id FROM channels";
    if ($has_bouquets && !empty($allowed_ch_cats)) {
        $ids = implode(',', array_map('intval', $allowed_ch_cats));
        $sql .= " WHERE category_id IN ($ids)";
    } elseif ($has_bouquets) {
        echo json_encode([]); exit;
    }

    $stmt = $pdo->query("$sql ORDER BY name ASC");
    $streams = []; $i = 1;
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $cat_id = $row['category_id'] ? (string)$row['category_id'] : "0";
        $logo = $row['logo_url'] ? $row['logo_url'] : ""; 
        $epg = $row['epg_id'] ? $row['epg_id'] : ""; 

        $streams[] = [
            "num" => $i++, "name" => $row['name'], "stream_type" => "live", "stream_id" => (int)$row['id'], "stream_icon" => $logo, "epg_channel_id" => $epg, "added" => (string)time(), "category_id" => $cat_id, "custom_sid" => "", "tv_archive" => 0, "direct_source" => "", "tv_archive_duration" => 0, "is_adult" => "0"
        ];
    }
    echo json_encode($streams); 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)) {
        $ids = implode(',', array_map('intval', $allowed_mov_cats));
        $sql .= " AND id IN ($ids)";
    } elseif ($has_bouquets) { echo json_encode([]); exit; }
    
    $data = $pdo->query("$sql ORDER BY order_id ASC")->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($data); exit;
}

if ($action == 'get_vod_streams') {
    $sql = "SELECT id, name, cover_url, category_id, description FROM movies";
    if ($has_bouquets && !empty($allowed_mov_cats)) {
        $ids = implode(',', array_map('intval', $allowed_mov_cats));
        $sql .= " WHERE category_id IN ($ids)";
    } elseif ($has_bouquets) { echo json_encode([]); exit; }

    $stmt = $pdo->query("$sql ORDER BY name ASC");
    $streams = []; $i = 1;
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $cat_id = $row['category_id'] ? (string)$row['category_id'] : "0";
        $logo = $row['cover_url'] ? $row['cover_url'] : "";
        $desc = $row['description'] ? $row['description'] : "Sem sinopse.";
        $year = preg_match('/\((\d{4})\)/', $row['name'], $matches) ? $matches[1] : "";

        $streams[] = [
            "num" => $i++, "name" => $row['name'], "stream_type" => "movie", "stream_id" => (int)$row['id'], "stream_icon" => $logo, "added" => (string)time(), "category_id" => $cat_id, "container_extension" => "mp4", "custom_sid" => "", "direct_source" => "", "rating" => "0", "rating_5based" => 0, "year" => $year, "releaseDate" => $year, "director" => "", "cast" => "", "plot" => $desc, "duration_secs" => 0, "duration" => "00:00:00"
        ];
    }
    echo json_encode($streams); exit;
}

// --- VOD INFO ---
if ($action == 'get_vod_info') {
    $vod_id = (int)($_REQUEST['vod_id'] ?? 0);
    $stmt = $pdo->prepare("SELECT * FROM movies WHERE id = ? LIMIT 1");
    $stmt->execute([$vod_id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if($has_bouquets && !empty($allowed_mov_cats) && !in_array($row['category_id'], $allowed_mov_cats)) {
        echo json_encode([]); exit;
    }

    if ($row) {
        $year = preg_match('/\((\d{4})\)/', $row['name'], $matches) ? $matches[1] : "";
        echo json_encode([
            "info" => ["name" => $row['name'], "movie_image" => $row['cover_url'], "plot" => $row['description'], "rating" => "0", "releasedate" => $year, "director" => "", "cast" => "", "genre" => ""],
            "movie_data" => ["stream_id" => (int)$row['id'], "name" => $row['name'], "container_extension" => "mp4", "stream_icon" => $row['cover_url']]
        ]);
    } else { echo json_encode([]); }
    exit;
}

// --- SÉRIES ---
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)) {
        $ids = implode(',', array_map('intval', $allowed_ser_cats));
        $sql .= " AND id IN ($ids)";
    } elseif ($has_bouquets) { echo json_encode([]); exit; }

    $data = $pdo->query("$sql ORDER BY order_id ASC")->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($data); exit;
}

if ($action == 'get_series') {
    $sql = "SELECT id, name, cover_url, category_id, description FROM series";
    if ($has_bouquets && !empty($allowed_ser_cats)) {
        $ids = implode(',', array_map('intval', $allowed_ser_cats));
        $sql .= " WHERE category_id IN ($ids)";
    } elseif ($has_bouquets) { echo json_encode([]); exit; }

    $stmt = $pdo->query("$sql ORDER BY name ASC");
    $series = []; $i = 1;
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $cat_id = $row['category_id'] ? (string)$row['category_id'] : "0";
        $logo = $row['cover_url'] ? $row['cover_url'] : "";
        $year = preg_match('/\((\d{4})\)/', $row['name'], $matches) ? $matches[1] : "";

        $series[] = [
            "num" => $i++, "name" => $row['name'], "series_id" => (int)$row['id'], "cover" => $logo, "plot" => $row['description'], "cast" => "", "director" => "", "genre" => "", "releaseDate" => $year, "last_modified" => (string)time(), "rating" => "0", "rating_5based" => 0, "backdrop_path" => [], "youtube_trailer" => "", "episode_run_time" => "0", "category_id" => $cat_id
        ];
    }
    echo json_encode($series); exit;
}

// --- EPISÓDIOS ---
if ($action == 'get_series_info') {
    $sid = $_REQUEST['series_id'];
    $info = $pdo->query("SELECT * FROM series WHERE id=$sid")->fetch(PDO::FETCH_ASSOC);
    
    if($has_bouquets && !empty($allowed_ser_cats) && !in_array($info['category_id'], $allowed_ser_cats)) {
        echo json_encode([]); exit;
    }

    if(!$info) { echo json_encode([]); exit; }

    // Mantido original: tabelas 'episodes' e 'seasons'
    $stmt = $pdo->query("SELECT e.*, s.name as season_name, s.id as season_id_real FROM episodes e JOIN seasons s ON e.season_id = s.id WHERE s.series_id=$sid ORDER BY s.name, e.id ASC");
    $episodes = []; $seasons_map = []; $ep_counters = []; 

    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $s_num = (int)filter_var($row['season_name'], FILTER_SANITIZE_NUMBER_INT);
        if ($s_num == 0) $s_num = 1;
        if (!isset($ep_counters[$s_num])) $ep_counters[$s_num] = 1;
        $ep_num = $ep_counters[$s_num]++;

        $episodes[$s_num][] = [
            "id" => (string)$row['id'], "episode_num" => (string)$ep_num, "title" => $row['name'], "container_extension" => "mp4", "info" => ["movie_image" => $row['cover_url'], "plot" => "", "duration_secs" => 0, "duration" => "00:00:00"], "custom_sid" => "", "added" => (string)time(), "season" => (int)$s_num, "direct_source" => ""
        ];

        if (!isset($seasons_map[$s_num])) {
            $seasons_map[$s_num] = ["air_date" => "", "episode_count" => 0, "id" => (int)$row['season_id_real'], "name" => "Season " . $s_num, "overview" => "", "season_number" => $s_num, "cover" => $row['cover_url'], "cover_big" => $row['cover_url']];
        }
    }

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