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

date_default_timezone_set('America/Argentina/Mendoza');

/* ===================== CONFIG ===================== */
$encryption_key   = '3e1g9x52z15b2u54';
$encrypt_response = true; // true = cifrado total | false = JSON plano

// Permitir override por body/GET: plain=true
$raw_in = file_get_contents('php://input');
$body   = json_decode($raw_in, true);
if (isset($body['plain'])) {
    $encrypt_response = !filter_var($body['plain'], FILTER_VALIDATE_BOOL);
} elseif (isset($_GET['plain'])) {
    $encrypt_response = !filter_var($_GET['plain'], FILTER_VALIDATE_BOOL);
}

/* ===================== HEADERS ===================== */
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');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');

/* ===================== HELPERS ===================== */
function encryptAES($data, $key) {
    $plaintext = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    $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 isWebviewEnabled($value) {
    if (is_null($value) || $value === '') return false;
    $val = strtolower(trim((string)$value));
    return in_array($val, ['yes', '1', 'true'], true) || $value === 1;
}
function dbBool($v): bool {
    if (is_bool($v)) return $v;
    if ($v === null) return false;
    $s = strtolower(trim((string)$v));
    return ($s === '1' || $s === 'true' || $s === 'yes' || $s === 'y' || $s === 'on');
}
function read_json_file_assoc(string $path): ?array {
    if (!is_readable($path)) return null;
    $size = @filesize($path);
    if ($size === false || $size > 1024 * 1024) return null; // máx 1MB
    $raw = @file_get_contents($path);
    if ($raw === false) return null;
    $arr = json_decode($raw, true);
    if (json_last_error() !== JSON_ERROR_NONE || !is_array($arr)) return null;
    return $arr;
}
function normalizeHeaders($headers): array {
    if (!is_array($headers)) return [];
    $isAssoc = array_keys($headers) !== range(0, count($headers) - 1);
    if ($isAssoc) return $headers;
    $out = [];
    foreach ($headers as $h) {
        if (is_string($h) && strpos($h, ':') !== false) {
            [$k,$v] = explode(':', $h, 2);
            $out[trim($k)] = trim($v);
        }
    }
    return $out;
}
function isFlowUrl(string $uri): bool {
    $uri = trim($uri);
    if ($uri === '') return false;
    if (stripos($uri, 'https://chromecast.cvattv.com') === 0) return true;
    if (stripos($uri, 'https://cdn.cvattv.com') === 0) return true;
    if (preg_match('#^https://chromecast\.cvattv\.com\.[a-z]{2}#i', $uri)) return true;
    if (preg_match('#^https://cdn\.cvattv\.com\.[a-z]{2}#i', $uri)) return true;
    return false;
}

/* ===================== DEBUG ===================== */
if (isset($_GET['ping'])) {
    echo json_encode([
        'status'  => 'OK',
        'file'    => __FILE__,
        'time'    => date('c'),
        'encrypt' => $encrypt_response ? 'true' : 'false'
    ], JSON_PRETTY_PRINT);
    exit;
}

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

    $data = $body;
    if (!is_array($data)) $data = json_decode($raw_in ?: file_get_contents('php://input'), true);

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

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

    // Autenticación de usuario
    $stmt = $conn->prepare("SELECT password, vencimiento FROM users WHERE email = ? LIMIT 1");
    if (!$stmt) throw new Exception("Error DB (users): " . $conn->error);
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();
    $stmt->close();

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

    // Validar vencimiento
    $hoy         = new DateTime();
    $vencimiento = new DateTime($user['vencimiento']);
    if ($vencimiento < $hoy) throw new Exception("Cuenta expirada");

    // Obtener canal con campo 'adultos'
    $stmt = $conn->prepare("
        SELECT id, name, uri, drm_scheme, drm_license_uri, logo, headers, webview, default_KID,
               claroandina, groupid, adultos
        FROM channels
        WHERE id = ? AND name <> '' AND uri <> ''
        LIMIT 1
    ");
    if (!$stmt) throw new Exception("Error DB (channels): " . $conn->error);

    $stmt->bind_param("i", $channel_id);
    $stmt->execute();
    $channel = $stmt->get_result()->fetch_assoc();
    $stmt->close();

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

    $is_webview = isWebviewEnabled($channel['webview'] ?? null);

    $headers = [];
    if (!empty($channel['headers'])) {
        $tmp = json_decode($channel['headers'], true);
        if (json_last_error() === JSON_ERROR_NONE && is_array($tmp)) {
            $headers = normalizeHeaders($tmp);
        }
    }

    $uri        = (string)$channel['uri'];
    $is_flow    = isFlowUrl($uri);
    $is_claro   = dbBool($channel['claroandina'] ?? 0);
    $group_id   = isset($channel['groupid']) ? (int)$channel['groupid'] : null;

    if ($is_flow) {
        $hasAuth = false;
        foreach ($headers as $k => $_) {
            if (strcasecmp($k, 'Authorization') === 0) { $hasAuth = true; break; }
        }
        if (!$hasAuth) {
            $token_path = '/home/yaetfswo/public_html/panel_api/canales/flow/token.json';
            try {
                if (is_readable($token_path)) {
                    $token_json = file_get_contents($token_path);
                    $token_data = json_decode($token_json, true);
                    if (json_last_error() === JSON_ERROR_NONE && !empty($token_data['token'])) {
                        $headers['Authorization'] = $token_data['token'];
                    }
                }
            } catch (Throwable $t) { /* no-op */ }
        }
    } else {
        if (!$is_claro) {
            foreach (array_keys($headers) as $k) {
                if (strcasecmp($k, 'Authorization') === 0) unset($headers[$k]);
            }
        }
    }

    $header_api = null;
    if ($is_claro) {
        $HEADER_API = null;
        $header_api_php = '/www/wwwroot/digital-tv.net/canales/DIGIPLAY/claro/header_api.php';
        if (is_readable($header_api_php)) {
            try {
                include $header_api_php;
                if (is_array($HEADER_API)) $header_api = $HEADER_API;
            } catch (Throwable $t) { }
        }
        if (!is_array($header_api)) {
            $cfg_json = read_json_file_assoc('/home/yaetfswo/public_html/panel_api/canales/claro/config.json');
            if (is_array($cfg_json)) $header_api = $cfg_json;
        }
        if (is_array($header_api) && $group_id !== null && !isset($header_api['group_id'])) {
            $header_api['group_id'] = $group_id;
        }
        if (is_array($header_api) && isset($header_api['Authorization']) && $header_api['Authorization'] !== '') {
            $headers['Authorization'] = $header_api['Authorization'];
        }
    }

    if ($is_webview) {
        $drm_scheme      = 'WEBVIEW';
        $drm_license_uri = '';
    } else {
        $drm_scheme = $channel['drm_scheme'] ?? '';
        if (($drm_scheme) === 'clearkey') {
            $drm_license_uri = "https://yaetv.com/panel_api/clearkey/llaves.php?id=" . $channel['id'];
        } elseif (!empty($channel['drm_license_uri'])) {
            $drm_license_uri = $channel['drm_license_uri'];
        } else {
            $drm_license_uri = '';
        }
    }

    // Convertir campo 'adultos' a booleano y exponer como 'isAdult'
    $is_adult_flag = dbBool($channel['adultos'] ?? 0);

    $response_item = [
        'name'            => (string)$channel['name'],
        'uri'             => (string)$channel['uri'],
        'logo'            => $channel['logo'] ?? '',
        'drm_scheme'      => $drm_scheme,
        'drm_license_uri' => $drm_license_uri,
        'headers'         => $headers,
        'claroandina'     => $is_claro,
        'adultos'         => $is_adult_flag,
    ];

    if (!is_null($channel['default_KID']) && $channel['default_KID'] !== '') {
        $response_item['default_KID'] = $channel['default_KID'];
    }
    if ($is_webview) {
        $response_item['isJwPlayer'] = true;
    }
    if ($is_claro && $group_id !== null) {
        $response_item['groupid'] = $group_id;
    }
    if ($is_claro) {
        $response_item['header_api'] = is_array($header_api)
            ? $header_api
            : ['_error' => 'No se pudo leer header_api (include/JSON)'];
    }

    $response = [$response_item];

    header('X-Encrypt: ' . ($encrypt_response ? '1' : '0'));
    if ($encrypt_response) {
        echo encryptAES($response, $encryption_key);
    } else {
        echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
    }

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