<?php
session_start();
require_once 'config.php';

$pdo = getConexaoAtiva(); // Banco Principal (Xtream ou XUI)
$pdo_int = getConexaoInterna(); // Banco Local (Configs)

$pdo->exec("SET NAMES utf8mb4");
$pdo_int->exec("SET NAMES utf8mb4");

// ====================================================================
// INTELIGÊNCIA ARTIFICIAL: DETECTA SE É XUI ONE OU XTREAM UI
// ====================================================================
$modo_ativo = 'interno';
try {
    $modo_ativo = $pdo_int->query("SELECT modo_ativo FROM configuracoes LIMIT 1")->fetchColumn() ?: 'interno';
} catch (Exception $e) {}

// O XUI One usa a tabela no plural e a coluna chama 'episode_num' em vez de 'sort'
$tabela_series = ($modo_ativo === 'xui') ? '`streams_series`' : '`series`';
$tabela_episodios = ($modo_ativo === 'xui') ? '`streams_episodes`' : '`series_episodes`';
$col_sort = ($modo_ativo === 'xui') ? 'episode_num' : 'sort';

// --- INÍCIO: BUSCA DE PERSONALIZAÇÃO DINÂMICA ---
$nome_painel = 'TOP IPTV';
$logo_url = '';
$cor_primaria = '#007bff';

try {
    $tabela_existe = $pdo_int->query("SHOW TABLES LIKE 'painel_config'")->rowCount() > 0;
    if ($tabela_existe) {
        $config_p = $pdo_int->query("SELECT * FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
        if ($config_p) {
            $nome_painel = !empty($config_p['nome_painel']) ? $config_p['nome_painel'] : $nome_painel;
            $logo_url = !empty($config_p['logo_url']) ? $config_p['logo_url'] : $logo_url;
            $cor_primaria = !empty($config_p['cor_primaria']) ? $config_p['cor_primaria'] : $cor_primaria;
        }
    }
} catch (Exception $e) {}
// --- FIM: BUSCA DE PERSONALIZAÇÃO DINÂMICA ---

if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; }

$role = $_SESSION['user_role'];
$nome_usuario = $_SESSION['username'];
$user_id_logado = $_SESSION['user_id'];
$series_id = $_GET['series_id'] ?? die("Série não especificada.");

// BUSCA DADOS DA SÉRIE PAI (MODO INTELIGENTE)
$stmtS = $pdo->prepare("SELECT title FROM $tabela_series WHERE id = ?");
$stmtS->execute([$series_id]);
$serie = $stmtS->fetch();

$mensagem = "";

// Sidebar Credits
try {
    $user_credits = $pdo_int->query("SELECT credits FROM reg_users WHERE id = " . intval($user_id_logado))->fetchColumn() ?: 0;
} catch (Exception $e) { $user_credits = 0; }

// --- AÇÕES ---

if (isset($_POST['save_episode'])) {
    $title = $_POST['title'];
    $season = $_POST['season_num'];
    $ep_sort = $_POST['sort'];
    $link = $_POST['stream_source'];
    $id_ep = $_POST['episode_id'] ?? null;
    $stream_id = $_POST['stream_id'] ?? null;

    if (!empty($link) && substr($link, 0, 1) !== '[') {
        $link = json_encode([$link], JSON_UNESCAPED_SLASHES);
    }

    if ($id_ep && $stream_id) {
        $pdo->prepare("UPDATE streams SET stream_display_name = ?, stream_source = ? WHERE id = ?")->execute([$title, $link, $stream_id]);
        $pdo->prepare("UPDATE $tabela_episodios SET season_num = ?, $col_sort = ? WHERE id = ?")->execute([$season, $ep_sort, $id_ep]);
    } else {
        $insStream = $pdo->prepare("INSERT INTO streams (stream_display_name, stream_source, type, added) VALUES (?, ?, 5, ?)");
        $insStream->execute([$title, $link, time()]);
        $new_stream_id = $pdo->lastInsertId();
        $pdo->prepare("INSERT INTO $tabela_episodios (series_id, stream_id, season_num, $col_sort) VALUES (?, ?, ?, ?)")->execute([$series_id, $new_stream_id, $season, $ep_sort]);
    }
    $mensagem = "<div class='alert success'>Episódio salvo com sucesso!</div>";
}

if (isset($_GET['delete_ep'])) {
    $pdo->prepare("DELETE FROM $tabela_episodios WHERE id = ?")->execute([$_GET['delete_ep']]);
    $pdo->prepare("DELETE FROM streams WHERE id = ?")->execute([$_GET['stream_id']]);
    header("Location: episodios.php?series_id=$series_id"); exit;
}

// BUSCA OS EPISÓDIOS (MODO INTELIGENTE: Puxando sort/episode_num de forma universal)
$query = "SELECT se.*, se.$col_sort as sort, s.stream_display_name as title, s.stream_source 
          FROM $tabela_episodios se 
          LEFT JOIN streams s ON se.stream_id = s.id 
          WHERE se.series_id = ? 
          ORDER BY se.season_num ASC, se.$col_sort ASC";
$episodes = $pdo->prepare($query); 
$episodes->execute([$series_id]);
$lista_eps = $episodes->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <link rel="stylesheet" href="tema.css">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Episódios - <?php echo htmlspecialchars($nome_painel); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { 
            --bg: #0f1114; 
            --sidebar: #1e2227; 
            --card: #272c33; 
            --accent: <?php echo $cor_primaria; ?>; 
            --border: #3a4149; 
            --text: #d1d5da; 
            --success: #28a745;
            --danger: #dc3545;
        }
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background: var(--bg); color: var(--text); display: flex; height: 100vh; overflow: hidden; }

        /* CSS OBRIGATÓRIO PARA A LOGO E MENU (Evita o bug da logo gigante) */
        .sidebar { width: 260px; background-color: var(--sidebar); border-right: 1px solid var(--border); display: flex; flex-direction: column; transition: all 0.3s ease; z-index: 1001; flex-shrink: 0; }
        .sidebar-header { padding: 25px 20px; text-align: center; font-size: 22px; font-weight: bold; border-bottom: 1px solid var(--border); color: white; }
        .sidebar-logo { width: 100%; max-width: 180px; height: auto; max-height: 60px; object-fit: contain; display: block; margin: 0 auto; }
        
        .user-info { padding: 20px; text-align: center; border-bottom: 1px solid var(--border); }
        .user-info .badge { background: rgba(255, 255, 255, 0.05); color: var(--accent); padding: 4px 10px; border-radius: 4px; font-size: 11px; text-transform: uppercase; font-weight: bold; margin-top: 5px; display: inline-block; }
        .credits-badge { display: block; margin-top: 10px; color: var(--success); font-weight: bold; font-size: 13px; }
        
        .menu-list { list-style: none; padding: 0; margin: 0; flex: 1; overflow-y: auto; }
        .menu-item { padding: 14px 25px; color: var(--text); text-decoration: none; display: flex; align-items: center; transition: 0.2s; font-size: 15px; border-left: 4px solid transparent; cursor: pointer; }
        .menu-item i:first-child { margin-right: 15px; width: 20px; text-align: center; font-size: 16px; color: #8a94a1; }
        .menu-item:hover, .menu-item.active { background: #2c3138; color: white; border-left-color: var(--accent); }
        .menu-item.active i { color: var(--accent); }
        
        .submenu { display: none; background: #121519; list-style: none; padding: 0; margin: 0; }
        .submenu .menu-item { padding-left: 52px; font-size: 14px; border-left: none; }
        .arrow-icon { margin-left: auto; transition: 0.3s; font-size: 12px; }
        .rotate { transform: rotate(180deg); }
        
        .menu-category { padding: 20px 25px 8px; font-size: 11px; text-transform: uppercase; color: #8a94a1; font-weight: bold; letter-spacing: 1px; }
        .logout-btn { padding: 15px; background-color: var(--danger); color: white; text-align: center; text-decoration: none; font-weight: bold; margin-top: auto; }

        /* MAIN CONTENT */
        .main { flex: 1; display: flex; flex-direction: column; overflow-y: auto; width: 100%; position: relative; }
        .topbar { display: flex; justify-content: space-between; align-items: center; padding: 15px 30px; background-color: var(--sidebar); border-bottom: 1px solid var(--border); }
        .menu-toggle { display: none; background: none; border: none; color: white; font-size: 24px; cursor: pointer; }
        
        .mode-badge { padding: 6px 15px; background: rgba(40, 167, 69, 0.15); color: var(--success); border-radius: 20px; font-size: 12px; font-weight: bold; border: 1px solid var(--success); white-space: nowrap; display: inline-block; }

        .content-area { padding: 30px; width: 100%; box-sizing: border-box; flex: 1; }

        .header-area { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; flex-wrap: wrap; gap: 10px; }
        .btn { padding: 10px 18px; border-radius: 6px; border: none; cursor: pointer; font-weight: bold; color: white; text-decoration: none; font-size: 13px; display: inline-flex; align-items: center; gap: 8px; transition: 0.2s;}
        .btn-blue { background: var(--accent); }
        .btn-blue:hover { filter: brightness(0.85); }
        .btn-red { background: var(--danger); }
        .btn-red:hover { filter: brightness(1.2); }

        .table-container { background: var(--card); border-radius: 10px; border: 1px solid var(--border); overflow-x: auto; width: 100%; }
        table { width: 100%; border-collapse: collapse; min-width: 600px; }
        th { background: rgba(0,0,0,0.2); padding: 15px; text-align: left; font-size: 11px; color: #8a94a1; text-transform: uppercase; }
        td { padding: 15px; border-bottom: 1px solid var(--border); font-size: 14px; }

        .modal { display: none; position: fixed; z-index: 2000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.9); overflow-y: auto; }
        .modal-content { background: var(--card); width: 95%; max-width: 450px; margin: 10% auto; padding: 25px; border-radius: 12px; border: 1px solid var(--border); position: relative; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 5px; font-size: 12px; color: #8a94a1; font-weight: bold; }
        .form-group input { width: 100%; padding: 12px; background: #121519; border: 1px solid var(--border); color: white; border-radius: 6px; box-sizing: border-box; }

        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 1000; }
        .alert { padding: 15px; border-radius: 6px; margin-bottom: 20px; text-align: center; background: rgba(40, 167, 69, 0.1); color: var(--success); border: 1px solid var(--success); }

        @media (max-width: 768px) {
            .menu-toggle { display: block; margin-right: 15px; }
            .sidebar { position: fixed; left: -260px; height: 100%; box-shadow: 10px 0 20px rgba(0,0,0,0.5); }
            .sidebar.active { left: 0; }
            .sidebar-overlay.active { display: block; }
            .topbar { padding: 15px 20px; justify-content: flex-start; }
            .topbar-right { margin-left: auto; }
            .content-area { padding: 15px; }
            .header-area { flex-direction: column; align-items: stretch; text-align: center; }
            .btn { justify-content: center; }
        }
    </style>
</head>
<body>

    <div class="sidebar-overlay" id="overlay" onclick="toggleMenu()"></div>

    <?php include 'sidebar.php'; ?>

    <div class="main">
        <header class="topbar">
            <div style="display: flex; align-items: center;">
                <button class="menu-toggle" id="btn-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
                <div style="font-weight:bold; color:white; font-size:18px; margin-left:10px;">EPISÓDIOS</div>
            </div>
            <div class="topbar-right">
                <span class="mode-badge"><i class="fas fa-database"></i> <?php echo defined('MODO_SISTEMA') ? strtoupper(MODO_SISTEMA) : strtoupper($modo_ativo); ?></span>
            </div>
        </header>

        <div class="content-area">
            <div class="header-area">
                <div>
                    <h2 style="margin:0; color:white;"><?php echo htmlspecialchars($serie['title']); ?></h2>
                    <small style="color:var(--accent); font-weight:bold;">Gerenciamento de Episódios</small>
                </div>
                <button class="btn btn-blue" onclick="openModalAdd()"><i class="fas fa-plus"></i> NOVO EPISÓDIO</button>
            </div>

            <?php echo $mensagem; ?>

            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th>TEMP.</th>
                            <th>EP.</th>
                            <th>TÍTULO</th>
                            <th>AÇÕES</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($lista_eps as $ep): ?>
                        <tr>
                            <td><strong style="color:var(--accent)">T<?php echo $ep['season_num']; ?></strong></td>
                            <td>EP <?php echo $ep['sort']; ?></td>
                            <td><?php echo htmlspecialchars($ep['title']); ?></td>
                            <td>
                                <button class="btn btn-blue" style="padding:8px 12px; margin-right:5px;" onclick='openModalEdit(<?php echo htmlspecialchars(json_encode($ep), ENT_QUOTES, "UTF-8"); ?>)'><i class="fas fa-edit"></i></button>
                                <a href="?series_id=<?php echo $series_id; ?>&delete_ep=<?php echo $ep['id']; ?>&stream_id=<?php echo $ep['stream_id']; ?>" class="btn btn-red" style="padding:8px 12px;" onclick="return confirm('Excluir?')"><i class="fas fa-trash"></i></a>
                            </td>
                        </tr>
                        <?php endforeach; if(empty($lista_eps)) echo "<tr><td colspan='4' style='text-align:center;'>Nenhum episódio cadastrado.</td></tr>"; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php include 'rodape.php'; ?>
    </div>

    <div id="modalEp" class="modal">
        <div class="modal-content">
            <h3 id="modalTitle" style="margin-top:0; color:white;">Novo Episódio</h3>
            <form method="POST">
                <input type="hidden" name="episode_id" id="field_id">
                <input type="hidden" name="stream_id" id="field_stream_id">
                
                <div style="display:grid; grid-template-columns: 1fr 1fr; gap:10px;">
                    <div class="form-group"><label>Temporada</label><input type="number" name="season_num" id="field_season" required></div>
                    <div class="form-group"><label>Nº Episódio</label><input type="number" name="sort" id="field_sort" required></div>
                </div>
                <div class="form-group"><label>Título do Episódio</label><input type="text" name="title" id="field_title" placeholder="Ex: Piloto"></div>
                <div class="form-group"><label>URL do Vídeo</label><input type="text" name="stream_source" id="field_source" required></div>
                
                <button type="submit" name="save_episode" class="btn btn-blue" style="width:100%; padding:15px; justify-content:center;">SALVAR AGORA</button>
                <button type="button" onclick="closeModal()" style="background:none; border:none; color:#8a94a1; width:100%; margin-top:10px; cursor:pointer;">Cancelar</button>
            </form>
        </div>
    </div>

    <script>
        function toggleMenu() { 
            document.getElementById('sidebar').classList.toggle('active'); 
            document.getElementById('overlay').classList.toggle('active'); 
        }

        function toggleSubmenu(id) {
            const sub = document.getElementById(id);
            const arrow = document.getElementById('arrow-' + id);
            if (sub.style.display === "block") {
                sub.style.display = "none";
                if(arrow) arrow.classList.remove('rotate');
            } else {
                sub.style.display = "block";
                if(arrow) arrow.classList.add('rotate');
            }
        }

        function openModalAdd() {
            document.getElementById('modalTitle').innerText = "Novo Episódio";
            document.getElementById('field_id').value = "";
            document.getElementById('field_stream_id').value = "";
            document.getElementById('field_title').value = "";
            document.getElementById('field_season').value = "";
            document.getElementById('field_sort').value = "";
            document.getElementById('field_source').value = "";
            document.getElementById('modalEp').style.display = 'block';
        }

        function openModalEdit(ep) {
            document.getElementById('modalTitle').innerText = "Editar Episódio";
            document.getElementById('field_id').value = ep.id;
            document.getElementById('field_stream_id').value = ep.stream_id;
            document.getElementById('field_title').value = ep.title;
            document.getElementById('field_season').value = ep.season_num;
            document.getElementById('field_sort').value = ep.sort;
            let rawSource = ep.stream_source;
            try {
                if (rawSource.startsWith('[') && rawSource.endsWith(']')) {
                    let parsed = JSON.parse(rawSource);
                    if (Array.isArray(parsed) && parsed.length > 0) rawSource = parsed[0];
                }
            } catch (e) { }
            document.getElementById('field_source').value = rawSource;
            document.getElementById('modalEp').style.display = 'block';
        }

        function closeModal() { document.getElementById('modalEp').style.display = 'none'; }
    </script>
    <script src="tema.js"></script>
</body>
</html>