<?php
require_once __DIR__ . '/../con/config.php';

date_default_timezone_set('America/Argentina/Mendoza'); // Establece la zona horaria

$encryption_key = '3e1g9x52z15b2u54';
$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);
}

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']) || !isset($data['id'])) {
        throw new Exception("Se requiere email, password e id en el body JSON");
    }

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

    // Autenticación de usuario
    $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");
    }

    $hoy = new DateTime();
    $vencimiento = new DateTime($user['vencimiento']);

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

    // Traemos el canal, incluyendo 'adultos'
    $stmt = $conn->prepare("
        SELECT id, name, uri, drm_scheme, drm_license_uri, logo, headers, webview, isMagis, default_KID, adultos
        FROM channels 
        WHERE id = ? AND name != '' AND uri != ''
        LIMIT 1
    ");
    $stmt->bind_param("i", $channel_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $channel = $result->fetch_assoc();
    $stmt->close();

    if (!$channel) {
        throw new Exception("Canal no encontrado");
    }

    // Resolver licencia DRM (clearkey vs. otra)
    $drm_license_uri = $channel['drm_scheme'] === 'clearkey'
        ? "https://yaetv.com/panel_api/clearkey/llaves.php?id=" . $channel['id']
        : ($channel['drm_license_uri'] ?? '');

    // Headers (isMagis usa headers.php)
    if (isset($channel['isMagis']) && $channel['isMagis'] == 1) {
        $_GET['url'] = $channel['uri'];
        ob_start();
        include __DIR__ . '/headers.php';
        $headers_json = ob_get_clean();
        $headers = json_decode($headers_json, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception("Error al obtener headers desde headers.php");
        }
    } else {
        $headers = $channel['headers'] ? json_decode($channel['headers'], true) : [];
    }

    // Armar respuesta (incluye 'adultos' como booleano)
    $response_item = [
        'name' => $channel['name'],
        'uri' => $channel['uri'],
        'logo' => $channel['logo'] ?? '',
        'drm_scheme' => $channel['drm_scheme'] ?? '',
        'drm_license_uri' => $drm_license_uri,
        'headers' => $headers,
        'adultos' => isset($channel['adultos']) ? (bool)$channel['adultos'] : false, // true/false real
    ];

    if (isset($channel['webview']) && in_array($channel['webview'], ['yes', 'no'], true)) {
        $response_item['webview'] = $channel['webview'];
    }

    if (!is_null($channel['default_KID'])) {
        $response_item['default_KID'] = $channel['default_KID'];
    }

    if (trim($channel['name']) === 'TIGO') {
        $response_item['isJwPlayer'] = true;
    }

    $response = [$response_item];

    if ($encrypt_response) {
        echo encryptAES($response, $encryption_key);
    } else {
        echo json_encode($response, 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();
    }
}
?>
