<?php
require_once __DIR__ . '/../con/config.php';
$encryption_key = '3e1g9x52z15b2u54';
// ⚙️ Cambiar a true para habilitar cifrado
$encrypt_response = true;
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

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);
}

function logMessage($message) {
    error_log($message);
}

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception("Método no permitido, se requiere POST");
    }

    $json = file_get_contents('php://input');
    $data = json_decode($json, true);

    if (!$data || !isset($data['email']) || !isset($data['password'])) {
        throw new Exception("Se requiere email y password en el body JSON");
    }

    $email = filter_var($data['email'], FILTER_SANITIZE_EMAIL);
    $password = $data['password'];

    $stmt = $conn->prepare("SELECT email, password, vencimiento FROM users WHERE email = ? LIMIT 1");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    $stmt->close();

    if (!$user || $user['password'] !== $password) {
        throw new Exception("Credenciales inválidas");
    }

    date_default_timezone_set('America/Argentina/Mendoza');
    $hoy = new DateTime('now', new DateTimeZone('America/Argentina/Mendoza'));
    $vencimiento = new DateTime($user['vencimiento'], new DateTimeZone('America/Argentina/Mendoza'));

    if ($vencimiento < $hoy) {
        throw new Exception("Cuenta expirada");
    }

    $output = [];
    $categories_query = "SELECT id, name FROM categories WHERE name != '' ORDER BY name";
    $categories_result = $conn->query($categories_query);

    if (!$categories_result) {
        throw new Exception("Error al consultar categorías: " . $conn->error);
    }

    $channels_stmt = $conn->prepare("
        SELECT id, name, logo 
        FROM channels 
        WHERE category_id = ? AND name != '' AND uri != '' 
        ORDER BY name
    ");

    if (!$channels_stmt) {
        throw new Exception("Error preparando consulta de canales: " . $conn->error);
    }

    while ($category = $categories_result->fetch_assoc()) {
        $category_id = $category['id'];
        $category_name = $category['name'];

        // 🔥 FILTRO ADULTOS
        if (strcasecmp($category_name, 'ADULTOS') === 0) {
            continue;
        }

        $channels_stmt->bind_param("i", $category_id);
        $channels_stmt->execute();
        $channels_result = $channels_stmt->get_result();
        $samples = [];

        while ($channel = $channels_result->fetch_assoc()) {
            $samples[] = [
                'id' => $channel['id'],
                'name' => $channel['name'],
                'logo' => $channel['logo'] ?? ''
            ];
        }

        if (!empty($samples)) {
            $output[] = ['name' => $category_name, 'samples' => $samples];
        }
    }

    $channels_stmt->close();
    $categories_result->free();

    if (empty($output)) {
        throw new Exception("No se encontraron datos válidos");
    }

    if (isset($data['debug']) && $data['debug'] === true) {
        $output['__debug'] = [
            'now' => $hoy->format('Y-m-d H:i:s T'),
            'expiration_original' => $user['vencimiento'],
            'expiration_converted' => $vencimiento->format('Y-m-d H:i:s T'),
            'is_expired' => ($vencimiento < $hoy) ? 'Si' : 'No',
            'php_timezone' => date_default_timezone_get()
        ];
    }

    if ($encrypt_response) {
        echo encryptAES($output, $encryption_key);
    } else {
        echo json_encode($output, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    }

} catch (Exception $e) {
    http_response_code(401);
    echo json_encode(["error" => $e->getMessage()]);
} finally {
    if (isset($conn) && $conn) {
        $conn->close();
    }
}
?>
