<?php
// player_api.php - Com Verificação de Bloqueio (active = 0)
// --- LIMPEZA DE BUFFER ---
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 (NOVO)
// Se active for 0 (Bloqueado) OU Data Expirada -> Bloqueia acesso
// =================================================================
if ($user['active'] == 0 || strtotime($user['expire_date']) < time()) {
    echo json_encode(['user_info' => ['auth' => 0], 'status' => 'Account Blocked or Expired']); 
    exit;
}

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

// RESPOSTA DE LOGIN
if (empty($action)) {

    // REGISTRO DE CLIENTE ONLINE NO APP
    try {
        $user_ip = $_SERVER['REMOTE_ADDR'];
        $ua = $_SERVER['HTTP_USER_AGENT'] ?? 'App';
        
        $pdo->prepare("DELETE FROM active_connections WHERE user_id = ?")->execute([$user['id']]);
        
        $sql_log = "INSERT INTO active_connections (user_id, username, stream_id, stream_type, user_ip, start_time, user_agent) VALUES (?, ?, 0, 'app_login', ?, ?, ?)";
        $pdo->prepare($sql_log)->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 (O RESTO SEGUE IGUAL)
// =====================================================================

// --- CANAIS (LIVE) ---
if ($action == 'get_live_categories') {
    $data = $pdo->query("SELECT id as category_id, name as category_name, 0 as parent_id FROM categories WHERE type='channel' ORDER BY order_id ASC")->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($data); exit;
}

if ($action == 'get_live_streams') {
    $stmt = $pdo->query("SELECT id, name, logo_url, category_id, epg_id FROM channels 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') {
    $data = $pdo->query("SELECT id as category_id, name as category_name, 0 as parent_id FROM categories WHERE type='movie' ORDER BY order_id ASC")->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($data); exit;
}

if ($action == 'get_vod_streams') {
    $stmt = $pdo->query("SELECT id, name, cover_url, category_id, description FROM movies 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 = "";
        if (preg_match('/\((\d{4})\)/', $row['name'], $matches)) {
            $year = $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;
}

// --- SINOPSE DOS FILMES (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 ($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') {
    $data = $pdo->query("SELECT id as category_id, name as category_name, 0 as parent_id FROM categories WHERE type='series' ORDER BY order_id ASC")->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($data); exit;
}

if ($action == 'get_series') {
    $stmt = $pdo->query("SELECT id, name, cover_url, category_id, description FROM series 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 = "";
        if (preg_match('/\((\d{4})\)/', $row['name'], $matches)) {
            $year = $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 DA SÉRIE ---
if ($action == 'get_series_info') {
    $sid = $_REQUEST['series_id'];
    
    $info = $pdo->query("SELECT * FROM series WHERE id=$sid")->fetch(PDO::FETCH_ASSOC);
    if(!$info) { echo json_encode([]); exit; }

    $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;
}
?>
