<?php


require_once __DIR__ . '/../con/config.php';
// Clave de encriptación (16 bytes para AES-128)
$encryption_key = '3e1g9x52z15b2u54';
// Configuración de cabeceras
header('Content-Type: text/plain; charset=utf-8');
header('Access-Control-Allow-Origin: *');
// Función para encriptar con AES-128-ECB y PKCS5Padding
function encryptAES($data, $key) {
    $plaintext = json_encode($data, JSON_UNESCAPED_SLASHES);
    $encrypted = openssl_encrypt(
        $plaintext,
        'AES-128-ECB',
        $key,
        OPENSSL_RAW_DATA
    );
    if ($encrypted === false) {
        throw new Exception("Error al encriptar los datos: " . openssl_error_string());
    }
    return base64_encode($encrypted);
}

try {
    // 1. Obtener categorías y canales de la base de datos
    $output = [];
    
    $categories_query = "SELECT id, name FROM categories ORDER BY name";
    $categories_result = $conn->query($categories_query);
    
    if (!$categories_result) {
        throw new Exception("Error al consultar categorías: " . $conn->error);
    }
    
    while ($category = $categories_result->fetch_assoc()) {
        if (empty($category['name'])) continue;
        
        $category_id = $category['id'];
        $category_name = $category['name'];
        
        $stmt = $conn->prepare("SELECT id, name, uri, drm_scheme, drm_license_uri, logo, headers, webview FROM channels WHERE category_id = ? ORDER BY name");
        $stmt->bind_param("i", $category_id);
        $stmt->execute();
        $channels_result = $stmt->get_result();
        
        $samples = [];
        
        while ($channel = $channels_result->fetch_assoc()) {
            if (empty($channel['name']) || empty($channel['uri'])) continue;
            
            $drm_license_uri = $channel['drm_scheme'] === 'clearkey' 
                ? "http://digital-tv.net/clearkey/clearkey.php?id=" . $channel['id'] 
                : ($channel['drm_license_uri'] ?? '');
            
            $headers = $channel['headers'] ? json_decode($channel['headers'], true) : [];
            
            $channel_data = [
                'name' => $channel['name'],
                'uri' => $channel['uri'],
                'logo' => $channel['logo'] ?? ''
            ];
            
            if (!empty($channel['drm_scheme'])) {
                $channel_data['drm_scheme'] = $channel['drm_scheme'];
            }
            if (!empty($drm_license_uri)) {
                $channel_data['drm_license_uri'] = $drm_license_uri;
            }
            if (!empty($headers)) {
                $channel_data['headers'] = $headers;
            }
            if ($channel['webview'] === 'yes') {
                $channel_data['webview'] = 'yes';
            }
            
            $samples[] = $channel_data;
        }
        
        $stmt->close();
        
        if (!empty($samples)) {
            $output[] = ['name' => $category_name, 'samples' => $samples];
        }
    }
    
    $categories_result->free();
    
    // 2. Obtener eventos deportivos
    $events_url = "https://streamtpcloud.com/eventos.json";
    $jsonData = file_get_contents($events_url);
    
    if ($jsonData === FALSE) {
        throw new Exception("Error al obtener los datos de eventos deportivos");
    }
    
    $data = json_decode($jsonData, true);
    
    if ($data === NULL) {
        throw new Exception("Error al decodificar el JSON de eventos deportivos");
    }
    
    // Filtrar eventos con estado "en vivo" o "pronto"
    $filteredEvents = array_filter($data, function ($event) {
        return in_array(strtolower($event['status']), ['en vivo', 'pronto']);
    });
    
    // 3. Formatear los eventos como una categoría adicional
    $sports_samples = [];
    
    // Logo por defecto para eventos deportivos
    $default_sports_logo = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTteNujiAoh7t2hIHVtM0S1PCRaGxaleTvOIA&s";
    
    foreach ($filteredEvents as $event) {
        $sports_samples[] = [
            "name" => $event["title"] . " - " . $event["time"],
            "uri" => $event["link"],
            "webview" => "yes",
            "logo" => $default_sports_logo // Añadir logo por defecto a todos los eventos deportivos
        ];
    }
    
    // Añadir la categoría de eventos deportivos si hay eventos
    if (!empty($sports_samples)) {
        $output[] = [
            "name" => "EVENTOS DEPORTIVOS",
            "samples" => $sports_samples
        ];
    }
    
    // 4. Verificar que haya datos y encriptar
    if (empty($output)) {
        throw new Exception("No se encontraron datos válidos para encriptar");
    }
    
    echo encryptAES($output, $encryption_key);
    
} catch (Exception $e) {
    http_response_code(500);
    echo "Error: " . $e->getMessage();
} finally {
    if (isset($conn) && $conn) {
        $conn->close();
    }
}
?>