<?php
/**
 * Xtream Codes M3U Generator - Advanced Version
 * Pełna obsługa API z przeglądaniem kategorii i odcinkami serii
 */

error_reporting(E_ALL);
ini_set('display_errors', 0);
session_start();

class XtreamAPI {
    private $server;
    private $username;
    private $password;
    private $timeout = 30;
    
    public function __construct($server, $username, $password) {
        $this->server = rtrim($server, '/');
        $this->username = $username;
        $this->password = $password;
    }
    
    public function request($action = '', $params = []) {
        $url = $this->server . '/player_api.php';
        $queryParams = array_merge([
            'username' => $this->username,
            'password' => $this->password,
        ], $params);
        
        if ($action) {
            $queryParams['action'] = $action;
        }
        
        $url .= '?' . http_build_query($queryParams);
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => $this->timeout,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            CURLOPT_HTTPHEADER => ['Accept: application/json']
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            throw new Exception("Błąd cURL: $error");
        }
        
        if ($httpCode !== 200) {
            throw new Exception("Błąd HTTP: $httpCode");
        }
        
        $data = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception("Nieprawidłowa odpowiedź JSON");
        }
        
        return $data;
    }
    
    public function authenticate() {
        $data = $this->request();
        
        if (isset($data['user_info']['auth']) && $data['user_info']['auth'] == 0) {
            throw new Exception("Błędne dane logowania");
        }
        
        return $data;
    }
    
    public function getLiveCategories() {
        return $this->request('get_live_categories');
    }
    
    public function getVodCategories() {
        return $this->request('get_vod_categories');
    }
    
    public function getSeriesCategories() {
        return $this->request('get_series_categories');
    }
    
    public function getLiveStreams($categoryId = null) {
        $params = $categoryId ? ['category_id' => $categoryId] : [];
        return $this->request('get_live_streams', $params);
    }
    
    public function getVodStreams($categoryId = null) {
        $params = $categoryId ? ['category_id' => $categoryId] : [];
        return $this->request('get_vod_streams', $params);
    }
    
    public function getSeries($categoryId = null) {
        $params = $categoryId ? ['category_id' => $categoryId] : [];
        return $this->request('get_series', $params);
    }
    
    public function getSeriesInfo($seriesId) {
        return $this->request('get_series_info', ['series_id' => $seriesId]);
    }
    
    public function getServer() {
        return $this->server;
    }
    
    public function getUsername() {
        return $this->username;
    }
    
    public function getPassword() {
        return $this->password;
    }
}

class M3UGenerator {
    private $api;
    
    public function __construct(XtreamAPI $api) {
        $this->api = $api;
    }
    
    public function generateLive($categoryId = null) {
        $streams = $this->api->getLiveStreams($categoryId);
        $categories = $this->indexCategories($this->api->getLiveCategories());
        
        return $this->buildM3U($streams, $categories, 'live');
    }
    
    public function generateVod($categoryId = null) {
        $streams = $this->api->getVodStreams($categoryId);
        $categories = $this->indexCategories($this->api->getVodCategories());
        
        return $this->buildM3U($streams, $categories, 'vod');
    }
    
    public function generateSeries($categoryId = null, $includeEpisodes = false) {
        $series = $this->api->getSeries($categoryId);
        $categories = $this->indexCategories($this->api->getSeriesCategories());
        
        if (!$includeEpisodes) {
            return $this->buildM3U($series, $categories, 'series_info');
        }
        
        // Generuj z odcinkami
        $m3u = "#EXTM3U\n";
        
        foreach ($series as $show) {
            try {
                $seriesInfo = $this->api->getSeriesInfo($show['series_id']);
                $seriesName = $show['name'] ?? 'Unknown Series';
                $logo = $show['cover'] ?? '';
                $catId = $show['category_id'] ?? '';
                $groupTitle = $categories[$catId] ?? 'Seriale';
                
                if (!empty($seriesInfo['episodes'])) {
                    foreach ($seriesInfo['episodes'] as $seasonNum => $episodes) {
                        foreach ($episodes as $episode) {
                            $epNum = $episode['episode_num'] ?? '00';
                            $epTitle = $episode['title'] ?? "Odcinek $epNum";
                            $epId = $episode['id'] ?? '';
                            $ext = $episode['container_extension'] ?? 'mp4';
                            
                            $fullTitle = sprintf('%s S%02dE%02d - %s', 
                                $seriesName, 
                                (int)$seasonNum, 
                                (int)$epNum, 
                                $epTitle
                            );
                            
                            $m3u .= sprintf(
                                '#EXTINF:-1 tvg-name="%s" tvg-logo="%s" group-title="%s",%s' . "\n",
                                $this->escape($fullTitle),
                                $this->escape($logo),
                                $this->escape($groupTitle),
                                $fullTitle
                            );
                            
                            $m3u .= sprintf(
                                '%s/series/%s/%s/%s.%s' . "\n",
                                $this->api->getServer(),
                                $this->api->getUsername(),
                                $this->api->getPassword(),
                                $epId,
                                $ext
                            );
                        }
                    }
                }
            } catch (Exception $e) {
                // Pomijamy serie z błędami
                continue;
            }
        }
        
        return $m3u;
    }
    
    private function buildM3U($streams, $categories, $type) {
        if (empty($streams)) {
            throw new Exception("Brak strumieni");
        }
        
        $m3u = "#EXTM3U\n";
        
        foreach ($streams as $stream) {
            $name = $stream['name'] ?? 'Unknown';
            $streamId = $stream['stream_id'] ?? ($stream['series_id'] ?? '');
            $logo = $stream['stream_icon'] ?? ($stream['cover'] ?? '');
            $catId = $stream['category_id'] ?? '';
            $groupTitle = $categories[$catId] ?? 'Uncategorized';
            $epgId = $stream['epg_channel_id'] ?? '';
            $ext = $stream['container_extension'] ?? ($type === 'live' ? 'ts' : 'mp4');
            
            // EXTINF
            $m3u .= '#EXTINF:-1';
            if ($epgId) {
                $m3u .= ' tvg-id="' . $this->escape($epgId) . '"';
            }
            $m3u .= ' tvg-name="' . $this->escape($name) . '"';
            if ($logo) {
                $m3u .= ' tvg-logo="' . $this->escape($logo) . '"';
            }
            $m3u .= ' group-title="' . $this->escape($groupTitle) . '"';
            $m3u .= ',' . $name . "\n";
            
            // URL
            $m3u .= $this->buildUrl($type, $streamId, $ext) . "\n";
        }
        
        return $m3u;
    }
    
    private function buildUrl($type, $streamId, $ext) {
        $paths = [
            'live' => 'live',
            'vod' => 'movie',
            'series_info' => 'series'
        ];
        
        $path = $paths[$type] ?? 'movie';
        
        return sprintf(
            '%s/%s/%s/%s/%s.%s',
            $this->api->getServer(),
            $path,
            $this->api->getUsername(),
            $this->api->getPassword(),
            $streamId,
            $ext
        );
    }
    
    private function indexCategories($categories) {
        $indexed = [];
        foreach ($categories as $cat) {
            $indexed[$cat['category_id']] = $cat['category_name'];
        }
        return $indexed;
    }
    
    private function escape($value) {
        return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
    }
}

// ============== OBSŁUGA REQUESTÓW ==============

$error = '';
$success = '';
$serverInfo = null;
$categories = [];
$currentView = $_GET['view'] ?? 'form';

// Obsługa logowania
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $server = trim($_POST['xc_srv_addr'] ?? '');
    $username = trim($_POST['xc_usr_login'] ?? '');
    $password = trim($_POST['xc_access_key'] ?? '');
    
    if ($_POST['action'] === 'login') {
        try {
            $api = new XtreamAPI($server, $username, $password);
            $serverInfo = $api->authenticate();
            
            $_SESSION['xtream'] = [
                'server' => $server,
                'username' => $username,
                'password' => $password,
                'info' => $serverInfo
            ];
            
            $success = 'Zalogowano pomyślnie!';
            $currentView = 'dashboard';
        } catch (Exception $e) {
            $error = $e->getMessage();
        }
    }
    
    if ($_POST['action'] === 'generate' && isset($_SESSION['xtream'])) {
        try {
            $api = new XtreamAPI(
                $_SESSION['xtream']['server'],
                $_SESSION['xtream']['username'],
                $_SESSION['xtream']['password']
            );
            
            $generator = new M3UGenerator($api);
            $type = $_POST['type'] ?? 'vod';
            $categoryId = !empty($_POST['category_id']) ? $_POST['category_id'] : null;
            $includeEpisodes = isset($_POST['include_episodes']);
            
            switch ($type) {
                case 'live':
                    $m3u = $generator->generateLive($categoryId);
                    break;
                case 'vod':
                    $m3u = $generator->generateVod($categoryId);
                    break;
                case 'series':
                    $m3u = $generator->generateSeries($categoryId, $includeEpisodes);
                    break;
                default:
                    throw new Exception("Nieznany typ");
            }
            
            $filename = sprintf(
                '%s_%s_%s.m3u',
                $_SESSION['xtream']['username'],
                $type,
                date('Ymd_His')
            );
            
            header('Content-Type: application/x-mpegurl; charset=utf-8');
            header('Content-Disposition: attachment; filename="' . $filename . '"');
            header('Content-Length: ' . strlen($m3u));
            echo $m3u;
            exit;
            
        } catch (Exception $e) {
            $error = $e->getMessage();
        }
    }
}

// Sprawdź sesję
if (isset($_SESSION['xtream'])) {
    $serverInfo = $_SESSION['xtream']['info'];
    if ($currentView === 'form') {
        $currentView = 'dashboard';
    }
}

// Pobierz kategorie jeśli zalogowany
if (isset($_SESSION['xtream']) && isset($_GET['get_categories'])) {
    try {
        $api = new XtreamAPI(
            $_SESSION['xtream']['server'],
            $_SESSION['xtream']['username'],
            $_SESSION['xtream']['password']
        );
        
        $type = $_GET['get_categories'];
        switch ($type) {
            case 'live':
                $categories = $api->getLiveCategories();
                break;
            case 'vod':
                $categories = $api->getVodCategories();
                break;
            case 'series':
                $categories = $api->getSeriesCategories();
                break;
        }
        
        header('Content-Type: application/json');
        echo json_encode($categories);
        exit;
    } catch (Exception $e) {
        header('Content-Type: application/json');
        echo json_encode(['error' => $e->getMessage()]);
        exit;
    }
}

// Wylogowanie
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

?>
<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Xtream M3U Generator Pro</title>
    <style>
        :root {
            --bg-primary: #0f0f1a;
            --bg-secondary: #1a1a2e;
            --bg-card: rgba(255, 255, 255, 0.03);
            --accent: #00d4ff;
            --accent-2: #7b2cbf;
            --text: #ffffff;
            --text-muted: #8892a0;
            --success: #10b981;
            --error: #ef4444;
            --warning: #f59e0b;
            --border: rgba(255, 255, 255, 0.1);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background: var(--bg-primary);
            color: var(--text);
            min-height: 100vh;
            line-height: 1.6;
        }
        
        .app {
            display: flex;
            min-height: 100vh;
        }
        
        .sidebar {
            width: 280px;
            background: var(--bg-secondary);
            border-right: 1px solid var(--border);
            padding: 24px;
            display: flex;
            flex-direction: column;
        }
        
        .logo {
            font-size: 1.5rem;
            font-weight: 700;
            background: linear-gradient(90deg, var(--accent), var(--accent-2));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: 32px;
            text-align: center;
        }
        
        .main {
            flex: 1;
            padding: 32px;
            overflow-y: auto;
        }
        
        .card {
            background: var(--bg-card);
            border: 1px solid var(--border);
            border-radius: 16px;
            padding: 24px;
            margin-bottom: 24px;
            backdrop-filter: blur(10px);
        }
        
        .card-header {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 20px;
            padding-bottom: 16px;
            border-bottom: 1px solid var(--border);
        }
        
        .card-header h2 {
            font-size: 1.25rem;
            font-weight: 600;
        }
        
        .card-header .icon {
            font-size: 1.5rem;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--text-muted);
            font-size: 0.9rem;
        }
        
        input, select {
            width: 100%;
            padding: 12px 16px;
            background: rgba(0, 0, 0, 0.3);
            border: 2px solid var(--border);
            border-radius: 10px;
            color: var(--text);
            font-size: 1rem;
            transition: all 0.2s;
        }
        
        input:focus, select:focus {
            outline: none;
            border-color: var(--accent);
            box-shadow: 0 0 0 3px rgba(0, 212, 255, 0.15);
        }
        
        select option {
            background: var(--bg-secondary);
        }
        
        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-top: 8px;
        }
        
        .checkbox-group input[type="checkbox"] {
            width: 20px;
            height: 20px;
            cursor: pointer;
        }
        
        .checkbox-group label {
            margin: 0;
            cursor: pointer;
        }
        
        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            padding: 12px 24px;
            border: none;
            border-radius: 10px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
            text-decoration: none;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, var(--accent), var(--accent-2));
            color: white;
            width: 100%;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 24px rgba(0, 212, 255, 0.3);
        }
        
        .btn-secondary {
            background: rgba(255, 255, 255, 0.1);
            color: var(--text);
        }
        
        .btn-secondary:hover {
            background: rgba(255, 255, 255, 0.15);
        }
        
        .btn-danger {
            background: var(--error);
            color: white;
        }
        
        .alert {
            padding: 14px 18px;
            border-radius: 10px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .alert-error {
            background: rgba(239, 68, 68, 0.15);
            border: 1px solid rgba(239, 68, 68, 0.3);
            color: #fca5a5;
        }
        
        .alert-success {
            background: rgba(16, 185, 129, 0.15);
            border: 1px solid rgba(16, 185, 129, 0.3);
            color: #6ee7b7;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 24px;
        }
        
        .stat-card {
            background: var(--bg-card);
            border: 1px solid var(--border);
            border-radius: 12px;
            padding: 20px;
            text-align: center;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            background: linear-gradient(90deg, var(--accent), var(--accent-2));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .stat-label {
            color: var(--text-muted);
            font-size: 0.9rem;
            margin-top: 4px;
        }
        
        .type-selector {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 12px;
            margin-bottom: 20px;
        }
        
        .type-btn {
            padding: 16px;
            background: var(--bg-card);
            border: 2px solid var(--border);
            border-radius: 12px;
            cursor: pointer;
            transition: all 0.2s;
            text-align: center;
        }
        
        .type-btn:hover {
            border-color: var(--accent);
        }
        
        .type-btn.active {
            border-color: var(--accent);
            background: rgba(0, 212, 255, 0.1);
        }
        
        .type-btn .icon {
            font-size: 2rem;
            margin-bottom: 8px;
        }
        
        .type-btn .label {
            font-weight: 600;
        }
        
        .user-info {
            padding: 16px;
            background: rgba(0, 212, 255, 0.1);
            border: 1px solid rgba(0, 212, 255, 0.2);
            border-radius: 12px;
            margin-bottom: 24px;
        }
        
        .user-info h3 {
            color: var(--accent);
            margin-bottom: 12px;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        
        .user-info-row {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
            font-size: 0.9rem;
        }
        
        .user-info-row:last-child {
            border-bottom: none;
        }
        
        .user-info-row span:first-child {
            color: var(--text-muted);
        }
        
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
            color: var(--text-muted);
        }
        
        .loading.show {
            display: block;
        }
        
        @media (max-width: 768px) {
            .app {
                flex-direction: column;
            }
            
            .sidebar {
                width: 100%;
                padding: 16px;
            }
            
            .type-selector {
                grid-template-columns: 1fr;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="app">
        <?php if ($currentView === 'dashboard' && isset($_SESSION['xtream'])): ?>
        <aside class="sidebar">
            <div class="logo">🎬 M3U Generator</div>
            
            <div class="user-info">
                <h3>Informacje o koncie</h3>
                <?php 
                $userInfo = $serverInfo['user_info'] ?? [];
                $srvInfo = $serverInfo['server_info'] ?? [];
                ?>
                <div class="user-info-row">
                    <span>Użytkownik:</span>
                    <span><?php echo htmlspecialchars($userInfo['username'] ?? '-'); ?></span>
                </div>
                <div class="user-info-row">
                    <span>Status:</span>
                    <span><?php echo htmlspecialchars($userInfo['status'] ?? '-'); ?></span>
                </div>
                <div class="user-info-row">
                    <span>Wygasa:</span>
                    <span><?php 
                        $exp = $userInfo['exp_date'] ?? null;
                        echo $exp ? date('Y-m-d', $exp) : 'Nieograniczony';
                    ?></span>
                </div>
                <div class="user-info-row">
                    <span>Połączenia:</span>
                    <span><?php echo htmlspecialchars($userInfo['max_connections'] ?? '-'); ?></span>
                </div>
            </div>
            
            <a href="?logout=1" class="btn btn-danger" style="margin-top: auto;">
                🚪 Wyloguj
            </a>
        </aside>
        <?php endif; ?>
        
        <main class="main">
            <?php if ($error): ?>
                <div class="alert alert-error">
                    ⚠️ <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>
            
            <?php if ($success): ?>
                <div class="alert alert-success">
                    ✅ <?php echo htmlspecialchars($success); ?>
                </div>
            <?php endif; ?>
            
            <?php if ($currentView === 'form'): ?>
            <!-- FORMULARZ LOGOWANIA -->
            <div class="card" style="max-width: 500px; margin: 100px auto;">
                <div class="card-header">
                    <span class="icon">🔐</span>
                    <h2>Zaloguj się do xtream api</h2>
                </div>
                
                <form method="POST" autocomplete="off" data-form-type="other">
                    <input type="hidden" name="action" value="login">
                    <!-- Honeypot fields for autofill prevention -->
                    <div style="position:absolute;left:-9999px;top:-9999px;">
                        <input type="text" name="username" tabindex="-1">
                        <input type="password" name="password" tabindex="-1">
                        <input type="text" name="email" tabindex="-1">
                        <input type="text" name="login" tabindex="-1">
                    </div>
                    
                    <div class="form-group">
                        <label>Adres serwera</label>
                        <input type="text" name="xc_srv_addr" id="f1_xc" placeholder="http://server.com:8080" required
                               autocomplete="new-password" data-lpignore="true" data-1p-ignore="true" data-bwignore="true"
                               value="<?php echo htmlspecialchars($_POST['xc_srv_addr'] ?? ''); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label>Login</label>
                        <input type="text" name="xc_usr_login" id="f2_xc" placeholder="user" required
                               autocomplete="new-password" data-lpignore="true" data-1p-ignore="true" data-bwignore="true"
                               value="<?php echo htmlspecialchars($_POST['xc_usr_login'] ?? ''); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label>Hasło</label>
                        <input type="text" name="xc_access_key" id="f3_xc" placeholder="pass" required
                               autocomplete="new-password" data-lpignore="true" data-1p-ignore="true" data-bwignore="true">
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        🚀 Połącz i zaloguj
                    </button>
                </form>
            </div>
            
            <?php else: ?>
            <!-- DASHBOARD -->
            <h1 style="margin-bottom: 24px;">Generator M3U</h1>
            
            <form method="POST" id="generateForm">
                <input type="hidden" name="action" value="generate">
                <input type="hidden" name="type" id="selectedType" value="vod">
                
                <div class="card">
                    <div class="card-header">
                        <span class="icon">📂</span>
                        <h2>Wybierz typ zawartości</h2>
                    </div>
                    
                    <div class="type-selector">
                        <div class="type-btn" data-type="live">
                            <div class="icon">📺</div>
                            <div class="label">Kanały Live</div>
                        </div>
                        <div class="type-btn active" data-type="vod">
                            <div class="icon">🎬</div>
                            <div class="label">Filmy (VOD)</div>
                        </div>
                        <div class="type-btn" data-type="series">
                            <div class="icon">📺</div>
                            <div class="label">Seriale</div>
                        </div>
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-header">
                        <span class="icon">⚙️</span>
                        <h2>Opcje generowania</h2>
                    </div>
                    
                    <div class="form-group">
                        <label>Kategoria (opcjonalnie)</label>
                        <select name="category_id" id="categorySelect">
                            <option value="">-- Wszystkie kategorie --</option>
                        </select>
                    </div>
                    
                    <div class="loading" id="categoryLoading">
                        ⏳ Ładowanie kategorii...
                    </div>
                    
                    <div class="form-group" id="episodesOption" style="display: none;">
                        <div class="checkbox-group">
                            <input type="checkbox" name="include_episodes" id="includeEpisodes">
                            <label for="includeEpisodes">Dołącz wszystkie odcinki (wolniejsze)</label>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        📥 Generuj plik M3U
                    </button>
                </div>
            </form>
            <?php endif; ?>
        </main>
    </div>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const typeBtns = document.querySelectorAll('.type-btn');
            const selectedTypeInput = document.getElementById('selectedType');
            const categorySelect = document.getElementById('categorySelect');
            const categoryLoading = document.getElementById('categoryLoading');
            const episodesOption = document.getElementById('episodesOption');
            
            if (!typeBtns.length) return;
            
            function loadCategories(type) {
                categoryLoading.classList.add('show');
                categorySelect.innerHTML = '<option value="">-- Wszystkie kategorie --</option>';
                
                fetch('?get_categories=' + type)
                    .then(r => r.json())
                    .then(data => {
                        categoryLoading.classList.remove('show');
                        if (Array.isArray(data)) {
                            data.forEach(cat => {
                                const opt = document.createElement('option');
                                opt.value = cat.category_id;
                                opt.textContent = cat.category_name;
                                categorySelect.appendChild(opt);
                            });
                        }
                    })
                    .catch(err => {
                        categoryLoading.classList.remove('show');
                        console.error(err);
                    });
            }
            
            typeBtns.forEach(btn => {
                btn.addEventListener('click', function() {
                    typeBtns.forEach(b => b.classList.remove('active'));
                    this.classList.add('active');
                    
                    const type = this.dataset.type;
                    selectedTypeInput.value = type;
                    
                    // Pokaż opcję odcinków tylko dla serii
                    episodesOption.style.display = type === 'series' ? 'block' : 'none';
                    
                    loadCategories(type);
                });
            });
            
            // Załaduj kategorie dla domyślnego typu
            loadCategories('vod');
        });
    </script>
</body>
</html>
