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

date_default_timezone_set('America/Argentina/Mendoza');

/* ===================== CONFIG TELEGRAM ===================== */
define('TG_TOKEN', '8332763033:AAHB9zbuJP2K5qbz2s4o5xMbZd56ReNP3y8');
define('TG_CHATID', '326717436');

function notifyTelegram($msg) {
    $url = "https://api.telegram.org/bot".TG_TOKEN."/sendMessage?chat_id=".TG_CHATID."&parse_mode=html&text=".urlencode($msg);
    @file_get_contents($url);
}

/* ===================== 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;
}

/* ===================== 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']);

    $stmt = $conn->prepare("SELECT password, vencimiento FROM users WHERE email = ? LIMIT 1");
    $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");
    }

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

    $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
    ");
    $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_paths = [
                'SERVIDOR_LOCAL' => '/home/yaetfswo/public_html/panel_api/canales/flow/token1.json',
                'SERVIDOR_ROCHA'  => '/home/yaetfswo/public_html/panel_api/canales/flow/token.json'
            ];

            foreach ($token_paths as $name => $path) {
                try {
                    if (is_readable($path)) {
                        $token_json = file_get_contents($path);
                        $token_data = json_decode($token_json, true);
                        
                        if (json_last_error() === JSON_ERROR_NONE && !empty($token_data['token'])) {
                            $raw_token = $token_data['token'];
                            $token_valido = false;

                            $parts = explode('.', str_replace('Bearer ', '', $raw_token));
                            if (count($parts) === 3) {
                                $payload = json_decode(base64_decode(str_replace(['-', '_'], ['+', '/'], $parts[1])), true);
                                if (isset($payload['exp']) && time() < $payload['exp']) {
                                    $token_valido = true;
                                }
                            }

                            if ($token_valido) {
                                $headers['Authorization'] = $raw_token;

                                // --- LOGICA TELEGRAM (CON NOMBRE DE CANAL) ---
                                $file_last = sys_get_temp_dir() . '/last_flow_origin.txt';
                                if (@file_get_contents($file_last) !== $name) {
                                    // Aquí agregamos el nombre del canal al mensaje
                                    $canal_nombre = $channel['name'] ?? 'Desconocido';
                                    notifyTelegram("🔵 <b>Cambio de Origen Flow</b>\nOrigen: <code>$name</code>\nCanal: <b>$canal_nombre</b>");
                                    @file_put_contents($file_last, $name);
                                }
                                break; 
                            }
                        }
                    }
                } catch (Throwable $t) { }
            }
        }
    } 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 = '';
        }
    }

    $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'];
    }

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