<?php
/**
 * GESTOR CYBER - player_api.php
 * Protocolo Xtream Codes — compatível com Smarters, TiviMate, Perfect Player, IBO, XCIPTV, OTT Navigator.
 */

define('GESTOR_CYBER', true);
require_once __DIR__ . '/_core.php';

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Cache-Control: no-store');

$username = trim($_GET['username'] ?? $_POST['username'] ?? '');
$password = trim($_GET['password'] ?? $_POST['password'] ?? '');
$action   = trim($_GET['action']   ?? $_POST['action']   ?? '');

// ─── Sem credenciais ──────────────────────────────────────────────────────────
if (!$username || !$password) {
    echo json_encode(['user_info' => ['auth' => 0], 'server_info' => []]);
    exit;
}

// ─── Autenticar ───────────────────────────────────────────────────────────────
$auth = gc_auth($username, $password);
if (!$auth) {
    echo json_encode(['user_info' => ['auth' => 0], 'server_info' => []]);
    exit;
}

$client      = $auth['client'];
$db          = $auth['db'];
$src         = gc_source($db);
$our         = gc_our();
$allow_adult = ($client['adult_content'] ?? false) === true;
$config      = $db['config'] ?? [];
$exp_ts      = !empty($client['expires_at']) ? strtotime($client['expires_at']) : 0;

// ─── Resposta de autenticação ─────────────────────────────────────────────────
$auth_resp = [
    'user_info' => [
        'username'               => $client['username'],
        'password'               => $client['plain_password'] ?? $password,
        'message'                => $config['panel_name'] ?? 'GESTOR CYBER',
        'auth'                   => 1,
        'status'                 => gc_expired($client) ? 'Expired' : 'Active',
        'exp_date'               => (string)$exp_ts,
        'is_trial'               => ($client['is_test'] ?? false) ? '1' : '0',
        'active_cons'            => '0',
        'created_at'             => (string)strtotime($client['created_at'] ?? 'now'),
        'max_connections'        => (string)($client['max_connections'] ?? 1),
        'allowed_output_formats' => ['m3u8', 'ts', 'rtmp'],
    ],
    'server_info' => [
        'url'             => $our,
        'port'            => '80',
        'https_port'      => '443',
        'server_protocol' => str_starts_with($our, 'https') ? 'https' : 'http',
        'rtmp_port'       => '1935',
        'timezone'        => 'America/Sao_Paulo',
        'timestamp_now'   => time(),
        'time_now'        => date('Y-m-d H:i:s'),
        'process'         => true,
    ],
];

// Sem action = autenticação pura
if ($action === '' || $action === 'auth') {
    echo json_encode($auth_resp);
    exit;
}

// Sem fonte
if (!$src) {
    echo json_encode([]);
    exit;
}

// ─── Buscar e parsear M3U ─────────────────────────────────────────────────────
$m3u = gc_m3u($src);

if (empty($m3u)) {
    // Retorna estrutura vazia mas válida para o app não quebrar
    switch ($action) {
        case 'get_live_categories':
        case 'get_vod_categories':
        case 'get_series_categories':
        case 'get_live_streams':
        case 'get_vod_streams':
        case 'get_series':
            echo json_encode([]);
            break;
        default:
            echo json_encode($auth_resp);
    }
    exit;
}

$parsed      = gc_parse($m3u);
$all         = $parsed['streams'];
$cats        = $parsed['cats'];

// Filtrar adulto
if (!$allow_adult) $all = gc_filter_adult($all);

// Separar por tipo
$live   = array_values(array_filter($all, fn($s) => $s['type'] === 'live'));
$movies = array_values(array_filter($all, fn($s) => $s['type'] === 'movie'));
$series = array_values(array_filter($all, fn($s) => $s['type'] === 'series'));

// Filtro de categoria (opcional)
$filter_cid = isset($_GET['category_id']) ? (int)$_GET['category_id'] : null;
$fc = fn($arr) => $filter_cid === null ? $arr
    : array_values(array_filter($arr, fn($s) => $s['cid'] === $filter_cid));

// ─── Actions ──────────────────────────────────────────────────────────────────
switch ($action) {

    case 'get_live_categories':
        echo json_encode(gc_cats_json($live, $cats));
        break;

    case 'get_live_streams':
        $out = [];
        foreach ($fc($live) as $i => $s) {
            $out[] = [
                'num'                 => $i + 1,
                'name'                => $s['name'],
                'stream_type'         => 'live',
                'stream_id'           => $s['sid'],
                'stream_icon'         => $s['logo'],
                'epg_channel_id'      => $s['tvg_id'],
                'added'               => (string)time(),
                'category_id'         => (string)$s['cid'],
                'custom_sid'          => '',
                'tv_archive'          => 0,
                'direct_source'       => gc_rewrite($s['url'], $our, $username, $password),
                'tv_archive_duration' => 0,
            ];
        }
        echo json_encode($out);
        break;

    case 'get_vod_categories':
        echo json_encode(gc_cats_json($movies, $cats));
        break;

    case 'get_vod_streams':
        $out = [];
        foreach ($fc($movies) as $i => $s) {
            $out[] = [
                'num'                 => $i + 1,
                'name'                => $s['name'],
                'stream_type'         => 'movie',
                'stream_id'           => $s['sid'],
                'stream_icon'         => $s['logo'],
                'added'               => (string)time(),
                'category_id'         => (string)$s['cid'],
                'container_extension' => 'mkv',
                'custom_sid'          => '',
                'direct_source'       => gc_rewrite($s['url'], $our, $username, $password),
            ];
        }
        echo json_encode($out);
        break;

    case 'get_vod_info':
        $vid   = (int)($_GET['vod_id'] ?? 0);
        $found = null;
        foreach ($movies as $s) { if ($s['sid'] === $vid) { $found = $s; break; } }
        if (!$found) { echo json_encode([]); break; }
        echo json_encode([
            'info'       => ['name' => $found['name'], 'movie_image' => $found['logo'], 'genre' => $found['group']],
            'movie_data' => ['stream_id' => $vid, 'name' => $found['name'], 'container_extension' => 'mkv',
                             'direct_source' => gc_rewrite($found['url'], $our, $username, $password)],
        ]);
        break;

    case 'get_series_categories':
        echo json_encode(gc_cats_json($series, $cats));
        break;

    case 'get_series':
        $out = [];
        foreach ($fc($series) as $i => $s) {
            $out[] = [
                'num'          => $i + 1,
                'name'         => $s['name'],
                'series_id'    => $s['sid'],
                'cover'        => $s['logo'],
                'plot'         => '',
                'genre'        => $s['group'],
                'category_id'  => (string)$s['cid'],
                'rating'       => '0',
                'rating_5based'=> 0,
                'backdrop_path'=> [],
                'last_modified'=> (string)time(),
            ];
        }
        echo json_encode($out);
        break;

    case 'get_series_info':
        $sid   = (int)($_GET['series_id'] ?? 0);
        $found = null;
        foreach ($series as $s) { if ($s['sid'] === $sid) { $found = $s; break; } }
        if (!$found) { echo json_encode([]); break; }
        echo json_encode([
            'info'     => ['name' => $found['name'], 'cover' => $found['logo'], 'genre' => $found['group']],
            'episodes' => ['1' => [[
                'id' => (string)$sid, 'episode_num' => 1, 'title' => $found['name'],
                'container_extension' => 'mkv', 'season' => 1, 'added' => (string)time(),
                'direct_source' => gc_rewrite($found['url'], $our, $username, $password),
            ]]]
        ]);
        break;

    // EPG — tenta na fonte, fallback vazio
    case 'get_short_epg':
    case 'get_simple_data_table':
        $base_src = gc_base($src);
        $u_src    = urlencode($src['username'] ?? '');
        $p_src    = urlencode($src['password'] ?? '');
        $sid      = (int)($_GET['stream_id'] ?? 0);
        $extra    = $action === 'get_short_epg' ? '&limit='.(int)($_GET['limit']??4) : '';
        $epg_url  = "$base_src/player_api.php?username=$u_src&password=$p_src&action=$action&stream_id=$sid$extra";
        $raw      = gc_fetch($epg_url, 10);
        echo ($raw && strlen($raw) > 2) ? $raw : json_encode(['epg_listings' => []]);
        break;

    default:
        echo json_encode($auth_resp);
        break;
}
