<?php
// ======================================================================
//      PLAYER API v9.0 - Versão Final com Lógica de Filtro Definitiva
// ======================================================================

// --- Dependências e Configurações Iniciais ---
require_once($_SERVER['DOCUMENT_ROOT'] . '/api/controles/db.php');
header('Content-Type: application/json; charset=utf-8');
date_default_timezone_set('America/Sao_Paulo');

// --- Parâmetros da Requisição ---
$username = $_GET['username'] ?? null;
$password = $_GET['password'] ?? null;
$action = $_GET['action'] ?? '';
$category_id_req = ($_GET['category_id'] ?? null) === '*' ? null : ($_GET['category_id'] ?? null);

// --- Etapa 1: Autenticação do Cliente ---
if (!$username || !$password) {
    echo json_encode(['user_info' => ['auth' => 0, 'message' => 'Usuário e senha são necessários.']]);
    exit;
}

try {
    $conexao = conectar_bd();
    $stmt_auth = $conexao->prepare("SELECT * FROM clientes WHERE usuario = :username AND senha = :password");
    $stmt_auth->bindValue(':username', $username);
    $stmt_auth->bindValue(':password', $password);
    $stmt_auth->execute();
    $cliente_info = $stmt_auth->fetch(PDO::FETCH_ASSOC);

    if (!$cliente_info) {
        echo json_encode(['user_info' => ['auth' => 0]]);
        exit;
    }
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['user_info' => ['auth' => 0, 'message' => 'Erro interno do servidor.']]);
    exit;
}

// --- Etapa 2: Lógica de Pacotes (Bouquets) ---
$allowed_category_ids = null;
if (!empty($cliente_info['bouquet_id'])) {
    $stmt_bouquet = $conexao->prepare("SELECT category_id FROM bouquet_categories WHERE bouquet_id = ?");
    $stmt_bouquet->execute([$cliente_info['bouquet_id']]);
    $allowed_category_ids = $stmt_bouquet->fetchAll(PDO::FETCH_COLUMN);
    if (empty($allowed_category_ids)) { $allowed_category_ids = [0]; }
}

// --- Etapa 3: Roteador de Ações ---
switch ($action) {

    case '': // Ação de Login
        $exp_date = strtotime($cliente_info['Vencimento']);
        $status = ($exp_date >= time()) ? "Active" : "Expired";
        $auth = ($status == "Active") ? 1 : 0;
        $response = [
            'user_info' => [ 'username' => $cliente_info['usuario'], 'password' => $cliente_info['senha'], 'message' => 'Bem Vindo!', 'auth' => $auth, 'status' => $status, 'exp_date' => "$exp_date", 'is_trial' => "".$cliente_info['is_trial'], 'active_cons' => 0, 'created_at' => strtotime($cliente_info['Criado_em']), 'max_connections' => "".$cliente_info['conexoes'], 'allowed_output_formats' => ['m3u8', 'ts']],
            'server_info' => [ 'url' => $_SERVER['HTTP_HOST'], 'port' => $_SERVER['SERVER_PORT'], 'https_port' => "443", 'server_protocol' => $_SERVER['REQUEST_SCHEME'], 'rtmp_port' => '8880', 'timestamp_now' => time(), 'time_now' => date('Y-m-d H:i:s'), 'timezone' => date_default_timezone_get() ]
        ];
        echo json_encode($response);
        break;

    case 'get_live_categories':
    case 'get_vod_categories':
    case 'get_series_categories':
        $typeMap = ['get_live_categories' => 'streams', 'get_vod_categories' => 'movie', 'get_series_categories' => 'series'];
        $type = $typeMap[$action];

        $query = "SELECT id as category_id, nome as category_name, parent_id FROM categoria WHERE type = ?";
        $params = [$type];

        if ($cliente_info['adulto'] == 0) { $query .= " AND is_adult = 0"; }

        if ($allowed_category_ids !== null) {
            $placeholders = implode(',', array_fill(0, count($allowed_category_ids), '?'));
            $query .= " AND id IN ($placeholders)";
            $params = array_merge($params, $allowed_category_ids);
        }
        $query .= " ORDER BY position ASC";
        
        $stmt = $conexao->prepare($query);
        $stmt->execute($params);
        $results = $stmt->fetchAll();
        
        if (empty($results)) { $results[] = ["category_id" => "1", "category_name" => "Sem categorias", "parent_id" => 0]; }
        echo json_encode($results);
        break;

    case 'get_live_streams':
    case 'get_vod_streams':
    case 'get_series':
        $typeMap = ['get_live_streams' => 'live', 'get_vod_streams' => 'movie', 'get_series' => 'series'];
        $tableMap = ['get_live_streams' => 'streams', 'get_vod_streams' => 'streams', 'get_series' => 'series'];
        $stream_type = $typeMap[$action];
        $table = $tableMap[$action];

        $query = "SELECT * FROM `{$table}` WHERE stream_type = :stream_type";
        $params = [':stream_type' => $stream_type];
        
        if ($cliente_info['adulto'] == 0) { $query .= " AND is_adult = 0"; }

        if ($allowed_category_ids !== null) {
            $in_placeholders = implode(',', array_map(function($key) { return ':cat'.$key; }, array_keys($allowed_category_ids)));
            $query .= " AND category_id IN ($in_placeholders)";
            foreach ($allowed_category_ids as $key => $id) {
                $params[':cat'.$key] = $id;
            }
        }
        
        if ($category_id_req) {
            $query .= " AND category_id = :category_id_req";
            $params[':category_id_req'] = $category_id_req;
        }

        $query .= " ORDER BY name ASC";
        
        $stmt = $conexao->prepare($query);
        $stmt->execute($params);
        $results = $stmt->fetchAll();

        // Remapeia o array para o formato JSON esperado pelo app
        $formatted_results = [];
        foreach ($results as $num => $row) {
             if ($action == 'get_live_streams') { $formatted_results[] = [ "num" => $num + 1, "name" => $row["name"], "stream_type" => $row["stream_type"], "stream_id" => (int)$row["id"], "stream_icon" => $row["stream_icon"], "epg_channel_id" => $row["epg_channel_id"], "added" => $row["added"], "category_id" => $row["category_id"], "tv_archive" => 0, "tv_archive_duration" => 0 ]; }
             elseif ($action == 'get_vod_streams') { $formatted_results[] = [ "num" => $num + 1, "name" => $row["name"], "stream_id" => (int)$row["id"], "stream_icon" => $row["stream_icon"], "rating" => $row["rating"], "added" => $row["added"], "category_id" => $row["category_id"], "container_extension" => $row["container_extension"] ?? "mp4" ]; }
             elseif ($action == 'get_series') { $formatted_results[] = [ "num" => $num + 1, "name" => $row["name"], "series_id" => (int)$row["id"], "cover" => $row["cover"], "plot" => $row["plot"], "cast" => $row["cast"], "director" => $row["director"], "genre" => $row["genre"], "releaseDate" => $row["release_date"], "last_modified" => $row["last_modified"], "rating" => $row["rating"], "youtube_trailer" => $row["youtube_trailer"], "episode_run_time" => $row["episode_run_time"], "category_id" => $row["category_id"] ]; }
        }
        echo json_encode($formatted_results);
        break;

    default:
        echo json_encode([]);
        break;
}
?>