<?php 
include ('includes/header.php');

?>

<style>
/* Custom control panel styles matching ads.php */
.adm_container {
    max-width: 1200px;
    margin: 20px auto;
    padding: 15px;
}

.adm_title {
    text-align: center;
    margin-bottom: 20px;
    color: var(--light);
}

.adm_card {
    background-color: #2a2a2a;
    border-radius: 8px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    overflow: hidden;
    transition: all 0.3s ease;
}

.adm_card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 15px rgba(0, 0, 0, 0.2);
}

.adm_card_header {
    background-color: var(--accent-tertiary);
    color: var(--light);
    padding: 15px 20px;
    border-radius: 5px 5px 0 0;
    display: flex;
    align-items: center;
}

[data-theme="light"] .adm_card_header {
    background-color: var(--accent-tertiary);
    color: var(--light);
}

.adm_card_body {
    padding: 20px;
    background-color: #2a2a2a;
    color: var(--light);
}

[data-theme="light"] .adm_card_body {
    background-color: var(--light);
    color: var(--text-dark);
}

.adm_btn {
    display: inline-block;
    font-weight: 400;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    user-select: none;
    border: 1px solid transparent;
    padding: 0.5rem 1rem;
    font-size: 1rem;
    line-height: 1.5;
    border-radius: 0.25rem;
    transition: all 0.15s ease-in-out;
    cursor: pointer;
}

.adm_btn_primary {
    background-color: var(--accent-secondary);
    border-color: var(--accent-tertiary);
    color: var(--light);
}

.adm_btn_primary:hover {
    background-color: var(--accent-tertiary);
    border-color: var(--accent-secondary);
}

/* Other styling */
.category-card {
    margin-bottom: 20px;
}

.icon-colored {
    margin-right: 8px;
}

.alert {
    border-radius: 6px;
}

<?php

// Función para hacer peticiones con cURL (más segura y con User-Agent)
function obtenerDatos($url) {
    $ch = curl_init();
    
    // Configurar opciones de cURL
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    
    // Configurar User-Agent avanzado para evitar bloqueos
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36');
    
    // Configurar cabeceras adicionales
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Accept: application/json, text/plain, */*',
        'Accept-Language: es-ES,es;q=0.9,en;q=0.8',
        'Connection: keep-alive',
        'Cache-Control: no-cache',
        'Pragma: no-cache'
    ]);
    
    // Ejecutar la solicitud
    $respuesta = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    
    curl_close($ch);
    
    // Validar respuesta
    if ($error) {
        return ['error' => 'Error cURL: ' . $error];
    }
    
    if ($httpCode != 200) {
        return ['error' => 'Response code HTTP: ' . $httpCode];
    }
    
    // Procesar la respuesta JSON
    $datos = json_decode($respuesta, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        return ['error' => 'Error al decodificar JSON: ' . json_last_error_msg()];
    }
    
    return $datos;
}

// Variables para manejar resultados
$categoriasPeliculas = [];
$categoriasSeries = [];
$error = '';
$autenticado = false;
$url_base = '';

// Procesar el formulario si fue enviado
if (isset($_POST['obtener_categorias'])) {
    $url_base = trim($_POST['url']);
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    
    // Validar campos
    if (empty($url_base) || empty($username) || empty($password)) {
        $error = 'Por favor complete todos los campos';
    } else {
        // Construir URLs para ambas categorías
        $url_peliculas = $url_base . '/player_api.php?username=' . $username . '&password=' . $password . '&action=get_vod_categories';
        $url_series = $url_base . '/player_api.php?username=' . $username . '&password=' . $password . '&action=get_series_categories';
        
        // Obtener categorías de películas
        $respuesta_peliculas = obtenerDatos($url_peliculas);
        
        if (isset($respuesta_peliculas['error'])) {
            $error = 'Error getting movie categories: ' . $respuesta_peliculas['error'];
        } else {
            $categoriasPeliculas = $respuesta_peliculas;
            
            // Si las películas funcionaron, intentar las series
            $respuesta_series = obtenerDatos($url_series);
            
            if (isset($respuesta_series['error'])) {
                $error = 'Error getting series categories: ' . $respuesta_series['error'];
                // Aún podemos mostrar las películas si están bien
            } else {
                $categoriasSeries = $respuesta_series;
            }
            
            $autenticado = true;
        }
    }
}
?>

<style>
/* Estilos personalizados para mejorar la página */
:root {
    --primary: #901515;            /* Rojo oscuro elegante */
    --primary-dark: #700000;       /* Rojo más oscuro */
    --primary-light: #c02020;      /* Rojo más claro */
    --accent: #e63946;             /* Rojo brillante para acentos */
}

.icon-colored {
    margin-right: 8px;
}

.fa-link { color: #00BFFF; }
.fa-user { color: #32CD32; }
.fa-lock { color: #FFD700; }
.fa-film { color: #FF5733; }
.fa-tv { color: #8A2BE2; }
.fa-check-circle { color: #00C851; }
.fa-copy { color: #666; }

.card {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    margin-bottom: 30px;
}

.card-header {
    font-weight: bold;
    border-bottom: none;
}

.form-control:focus {
    border-color: var(--primary);
    box-shadow: 0 0 0 0.2rem rgba(144, 21, 21, 0.25);
}

.btn-get-categories {
    padding: 10px 25px;
    font-weight: 600;
    transition: all 0.3s;
    background-color: var(--accent-tertiary);
    border-color: var(--primary-dark);
}

.btn-get-categories:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.2);
    background-color: var(--primary-light);
}

.category-card {
    transition: all 0.3s;
}

.category-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 15px rgba(0,0,0,0.1);
}

.copy-btn {
    transition: all 0.2s;
}

.copy-btn:hover {
    background-color: var(--accent-tertiary);
    color: white;
}

.copy-btn:active {
    transform: scale(0.95);
}

.results-container {
    padding-top: 20px;
    border-top: 1px solid rgba(0,0,0,0.1);
    margin-top: 20px;
}

.select-category {
    font-weight: 500;
    padding: 10px;
    height: auto;
}

.id-display {
    font-weight: bold;
    text-align: center;
    font-size: 1.1em;
}

.alert {
    border-radius: 8px;
}

.bg-primary {
    background-color: var(--primary) !important;
}

.btn-primary {
    background-color: var(--accent-tertiary);
    border-color: var(--primary-dark);
}

.btn-primary:hover {
    background-color: var(--primary-light);
    border-color: var(--primary-light);
}

.bg-danger {
    background-color: var(--accent) !important;
}

.btn-danger {
    background-color: var(--accent);
    border-color: var(--accent);
}

.btn-danger:hover {
    background-color: #d33;
    border-color: #d33;
}

@media (max-width: 768px) {
    .category-cards-container {
        margin-top: 20px;
    }
}
</style>

<div class="container-fluid">
    <div class="row justify-content-center">
        <div class="col-xl-10 col-lg-11 col-md-12">
            <div class="card main-card">
                <div class="card-header text-white" style="background-color: var(--accent-tertiary);">
                    <h3 class="m-0"><i class="fa fa-id-badge icon-colored"></i>Category ID Finder</h3>
                </div>
                <div class="card-body">
                    
                    <?php if (!empty($error)): ?>
                    <div class="alert alert-danger alert-dismissible fade show">
                        <button type="button" class="close" data-dismiss="alert">&times;</button>
                        <strong><i class="fa fa-exclamation-triangle"></i> Error:</strong> <?php echo $error; ?>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Formulario de autenticación -->
                    <form method="post" action="" id="loginForm" class="needs-validation" novalidate>
                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="url"><i class="fa fa-link icon-colored"></i>Server URL (DNS)</label>
                                    <input type="text" class="form-control" name="url" id="url" placeholder="http://example.com" 
                                        value="<?php echo isset($_POST['url']) ? htmlspecialchars($_POST['url']) : ''; ?>" required>
                                    <small class="form-text text-muted">Enter server URL without "/player_api.php" at the end</small>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="username"><i class="fa fa-user icon-colored"></i>Username</label>
                                    <input type="text" class="form-control" name="username" id="username" 
                                        value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="password"><i class="fa fa-lock icon-colored"></i>Password</label>
                                    <div class="input-group">
                                        <input type="password" class="form-control" name="password" id="password" 
                                            value="<?php echo isset($_POST['password']) ? htmlspecialchars($_POST['password']) : ''; ?>" required>
                                        <div class="input-group-append">
                                            <button class="btn" type="button" id="togglePassword" style="background-color: var(--primary-light); color: var(--light); border: 1px solid var(--border-color);">
                                                <i class="fa fa-eye"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group text-center my-4">
                            <button type="submit" name="obtener_categorias" class="btn btn-get-categories" style="background-color: var(--accent-secondary); color: var(--light); border: none; padding: 8px 16px; border-radius: 4px; transition: all 0.3s ease;">
                                <i class="fa fa-search"></i> Get Categories
                            </button>
                        </div>
                    </form>
                    
                    <?php if ($autenticado): ?>
                    <div class="results-container">
                        <div class="alert alert-success">
                            <i class="fa fa-check-circle"></i> Authentication successful. Available categories shown below.
                        </div>
                        
                        <!-- Selectores de categorías -->
                        <div class="row category-cards-container">
                            
                            <!-- Categorías de Películas -->
                            <div class="col-md-6">
                                <div class="card category-card border-0">
                                    <div class="card-header text-white" style="background-color: var(--accent-tertiary);">
                                        <h5 class="m-0"><i class="fa fa-film icon-colored"></i>Movie Categories</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="form-group">
                                            <label for="peliculasSelect"><strong>Select a category:</strong></label>
                                            <select class="form-control select-category" id="peliculasSelect">
                                                <option value="">-- Select category --</option>
                                                <?php if (!empty($categoriasPeliculas)): ?>
                                                    <?php foreach ($categoriasPeliculas as $categoria): ?>
                                                        <option value="<?php echo htmlspecialchars($categoria['category_id']); ?>">
                                                            <?php echo htmlspecialchars($categoria['category_name']); ?> (ID: <?php echo htmlspecialchars($categoria['category_id']); ?>)
                                                        </option>
                                                    <?php endforeach; ?>
                                                <?php else: ?>
                                                    <option value="" disabled>No categories found</option>
                                                <?php endif; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="form-group mt-4">
                                            <label for="peliculasId"><strong>Selected Category ID:</strong></label>
                                            <div class="input-group">
                                                <input type="text" class="form-control id-display" id="peliculasId" readonly>
                                                <div class="input-group-append">
                                                    <button class="btn btn-danger copy-btn" type="button" data-target="peliculasId">
                                                        <i class="fa fa-copy"></i> Copy
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Categorías de Series -->
                            <div class="col-md-6">
                                <div class="card category-card border-0">
                                    <div class="card-header text-white" style="background-color: var(--accent-tertiary);">
                                        <h5 class="m-0"><i class="fa fa-tv icon-colored"></i>Series Categories</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="form-group">
                                            <label for="seriesSelect"><strong>Select a category:</strong></label>
                                            <select class="form-control select-category" id="seriesSelect">
                                                <option value="">-- Select category --</option>
                                                <?php if (!empty($categoriasSeries)): ?>
                                                    <?php foreach ($categoriasSeries as $categoria): ?>
                                                        <option value="<?php echo htmlspecialchars($categoria['category_id']); ?>">
                                                            <?php echo htmlspecialchars($categoria['category_name']); ?> (ID: <?php echo htmlspecialchars($categoria['category_id']); ?>)
                                                        </option>
                                                    <?php endforeach; ?>
                                                <?php else: ?>
                                                    <option value="" disabled>No categories found</option>
                                                <?php endif; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="form-group mt-4">
                                            <label for="seriesId"><strong>Selected Category ID:</strong></label>
                                            <div class="input-group">
                                                <input type="text" class="form-control id-display" id="seriesId" readonly>
                                                <div class="input-group-append">
                                                    <button class="btn btn-primary copy-btn" type="button" data-target="seriesId">
                                                        <i class="fa fa-copy"></i> Copy
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                        </div>
                    </div>
                    <?php endif; ?>
                    
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Función para actualizar el campo de ID al seleccionar una categoría
    function setupSelector(selectId, idFieldId) {
        var select = document.getElementById(selectId);
        var idField = document.getElementById(idFieldId);
        
        if (select && idField) {
            select.addEventListener('change', function() {
                idField.value = this.value;
            });
        }
    }
    
    // Configurar selectores
    setupSelector('peliculasSelect', 'peliculasId');
    setupSelector('seriesSelect', 'seriesId');
    
    // Función para copiar al portapapeles
    document.querySelectorAll('.copy-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var targetId = this.getAttribute('data-target');
            var targetInput = document.getElementById(targetId);
            
            if (targetInput && targetInput.value) {
                targetInput.select();
                document.execCommand('copy');
                
                // Cambiar texto del botón temporalmente
                var originalHtml = this.innerHTML;
                this.innerHTML = '<i class="fa fa-check"></i> Copied!';
                
                setTimeout(function() {
                    btn.innerHTML = originalHtml;
                }, 1500);
            }
        });
    });
    
    // Mostrar/ocultar contraseña
    const togglePassword = document.getElementById('togglePassword');
    const password = document.getElementById('password');
    
    if (togglePassword && password) {
        togglePassword.addEventListener('click', function() {
            const type = password.getAttribute('type') === 'password' ? 'text' : 'password';
            password.setAttribute('type', type);
            
            // Cambiar el icono
            const icon = this.querySelector('i');
            icon.classList.toggle('fa-eye');
            icon.classList.toggle('fa-eye-slash');
        });
    }
    
    // Validación del formulario
    var form = document.getElementById('loginForm');
    if (form) {
        form.addEventListener('submit', function(event) {
            if (form.checkValidity() === false) {
                event.preventDefault();
                event.stopPropagation();
            }
            form.classList.add('was-validated');
        });
    }
});
</script>

<?php include ('includes/footer.php');?>
