<?php

declare(strict_types=1);

function compat_encode(array $data, string $key): string
{
    $json = (string)json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    $key = $key !== '' ? $key : 'OmniMax1';
    $encoded = '';
    $keyLen = strlen($key);
    for ($i = 0, $len = strlen($json); $i < $len; $i++) {
        $encoded .= chr(ord($json[$i]) ^ ord($key[$i % $keyLen]));
    }
    return base64_encode($encoded);
}

function serve_ovpn_config(): void
{
    $file = DB_DIR . '/vpn/config.ovpn';
    if (!is_file($file)) {
        json_response(['success' => false, 'message' => 'ovpn_not_found'], 404);
    }

    $config = (string)file_get_contents($file);
    $vpn = get_config('vpn');
    $user = trim((string)($vpn['ovpn_username'] ?? ''));
    $pass = trim((string)($vpn['ovpn_password'] ?? ''));

    // Compatibilidade com engine OpenVPN/ics-openvpn transplantada no APK:
    // quando houver credenciais no painel, embute o auth-user-pass no profile servido.
    // Assim o app consegue importar o .ovpn internamente mesmo que a base antiga
    // ainda não grave ovpn_username/ovpn_password no SharedPreferences.
    if ($user !== '' && $pass !== '' && stripos($config, '<auth-user-pass>') === false) {
        $inlineAuth = "<auth-user-pass>\n" . $user . "\n" . $pass . "\n</auth-user-pass>";
        if (preg_match('/^\s*auth-user-pass(?:\s+.*)?$/mi', $config)) {
            $config = preg_replace('/^\s*auth-user-pass(?:\s+.*)?$/mi', $inlineAuth, $config, 1);
        } else {
            $config .= "\n" . $inlineAuth . "\n";
        }
    }

    header('Content-Type: application/x-openvpn-profile; charset=utf-8');
    header('Content-Disposition: inline; filename="config.ovpn"');
    header('X-Content-Type-Options: nosniff');
    echo $config;
    exit;
}

function route_public_api(string $path, string $method): bool
{
    if ($path === '/api/vpn/config.ovpn') {
        serve_ovpn_config();
    }
    if ($path === '/api/vpn/config') {
        json_response(['success' => true] + vpn_config_payload(true));
    }
    if ($path === '/api/servers') {
        json_response(['success' => true, 'servers' => api_servers()]);
    }
    if (in_array($path, ['/api/device/register', '/api/devices/register', '/api/register_device'], true)) {
        $device = upsert_device(request_data());
        json_response(['success' => true, 'device' => $device, 'config' => device_auto_config($device)]);
    }
    if (in_array($path, ['/api/device/config', '/api/autologin', '/api/auto-login'], true)) {
        $input = request_data();
        $device = upsert_device($input);
        json_response(['success' => true] + device_auto_config($device));
    }
    if (starts_with($path, '/api/')) {
        json_response(['success' => false, 'message' => 'not_found'], 404);
    }

    if ($path === '/ApiIPTV.php' || $path === '/api4/ApiIPTV.php') {
        route_bootstrap_api();
    }

    if (starts_with($path, '/api4/') || starts_with($path, '/panel_pro/')) {
        route_legacy_api($path, $method);
    }

    return false;
}

function route_bootstrap_api(): void
{
    $tag = (string)($_GET['tag'] ?? 'licV4');
    $messages = get_config('messages');

    if (in_array($tag, ['man', 'ann', 'connv2'], true)) {
        json_response([
            'tag' => 'connv2',
            'success' => '0',
            'api_ver' => '1.0v',
            'message' => $messages['message'],
            'msgid' => $messages['msgid'],
            'msg_status' => $messages['msg_status'],
            'msg_expire' => $messages['msg_expire'],
            'announcement' => $messages['announcement'],
            'ann_status' => $messages['ann_status'],
            'ann_expire' => $messages['ann_expire'],
            'ann_interval' => $messages['ann_interval'],
            'ann_disappear' => $messages['ann_disappear'],
        ]);
    }

    if ($tag === 'conn' || $tag === 'msg_conf') {
        json_response(['tag' => $tag, 'success' => '1', 'api_ver' => '1.0v']);
    }

    if ($tag === 'whatsup') {
        json_response(['tag' => 'whatsup', 'success' => $messages['whatsup'] === 'yes' ? '1' : '0', 'api_ver' => '1.0v', 'whatsup' => $messages['whatsup']]);
    }

    if ($tag === 'gfilter') {
        $filter = json_decode($messages['filter_json'], true);
        if (!is_array($filter)) {
            $filter = [];
        }
        json_response(['tag' => 'gfilter_n', 'success' => '1', 'api_ver' => '1.0v', 'status' => $messages['gfilter_status'], 'filter' => $filter]);
    }

    if ($tag === 'msg_cat_view' || $tag === 'msg') {
        $active = $messages['msg_status'] === 'ACTIVE' && trim($messages['message']) !== '';
        json_response([
            'tag' => $tag,
            'success' => $active ? '1' : '0',
            'api_ver' => '1.0v',
            'message' => $active ? $messages['message'] : $messages['category_message'],
        ]);
    }

    $core = get_config('core');
    $portalCfg = get_config('portal');
    $urls = get_config('urls');
    $vpnCfg = vpn_config_payload(true);
    $support = get_config('support');
    $branding = get_config('branding');
    $buttons = get_config('buttons');
    $interface = get_config('interface');
    $admob = get_config('admob');
    $prebid = get_config('prebid');
    $vast = get_config('vast');
    $ads = get_config('ads');
    $players = get_config('players');
    $playback = get_config('playback');
    $maintenance = get_config('maintenance');
    $others = get_config('others');
    $servers = api_servers();
    $footballEnabled = strtolower((string)($buttons['btn_football'] ?? 'yes')) !== 'no';
    $buttons['ms'] = $footballEnabled ? 'yes' : 'no';
    for ($i = 2; $i <= 5; $i++) {
        $buttons['ms' . $i] = $footballEnabled ? 'yes' : 'no';
    }
    $requestInput = request_data();
    $deviceConfig = null;
    if (input_has_device_id($requestInput)) {
        $deviceConfig = device_auto_config(upsert_device($requestInput + ['platform' => 'bootstrap']));
    }

    $cid = $core['cid'] !== '' ? $core['cid'] : '1';
    $requestAppName = preg_replace('/[^A-Za-z0-9 _.-]/', '', (string)($_REQUEST['an'] ?? ''));
    $requestAppName = trim((string)$requestAppName);
    $appName = $core['appname'] !== '' ? $core['appname'] : 'OmniMax';
    $keyAppName = $requestAppName !== '' ? $requestAppName : $appName;
    $keyPrefix = str_replace(' ', '', $keyAppName . $cid);
    $primary = $servers[0] ?? ['name' => 'Servidor Principal', 'url' => '0'];

    $portal = [
        'panel' => $portalCfg['panel'],
        'portal' => $primary['url'] ?? '0',
        'portal2' => $servers[1]['url'] ?? '0',
        'portal3' => $servers[2]['url'] ?? '0',
        'portal4' => $servers[3]['url'] ?? '0',
        'portal5' => $servers[4]['url'] ?? '0',
        'portal_name' => $primary['name'] ?? 'Servidor Principal',
        'portal2_name' => $servers[1]['name'] ?? '0',
        'portal3_name' => $servers[2]['name'] ?? '0',
        'portal4_name' => $servers[3]['name'] ?? '0',
        'portal5_name' => $servers[4]['name'] ?? '0',
        'portal_vod' => $portalCfg['portal_vod'],
        'portal_series' => $portalCfg['portal_series'],
    ];

    if ($urls['logurl'] === '') {
        $urls['logurl'] = panel_base_url();
    }
    if (($urls['mqtt_url'] ?? '') === '') {
        unset($urls['mqtt_url']);
    }
    if (($others['max_epg_file_size'] ?? '') === '') {
        unset($others['max_epg_file_size']);
    }

    // Mantém compatibilidade com bases que leem apenas urls.ovpn_url
    // e também entrega credenciais para bases com engine OpenVPN real.
    $urls['vpn_enabled'] = 'no';
    $urls['vpn_required'] = 'no';
    $urls['vpn_auto_connect'] = 'no';
    $urls['ovpn_url'] = 'No';
    $urls['ovpn_username'] = '';
    $urls['ovpn_password'] = '';
    if (($vpnCfg['vpn_enabled'] ?? false) === true) {
        $urls['ovpn_url'] = (string)$vpnCfg['ovpn_url'];
        $urls['ovpn_username'] = (string)($vpnCfg['ovpn_username'] ?? '');
        $urls['ovpn_password'] = (string)($vpnCfg['ovpn_password'] ?? '');
        $urls['vpn_enabled'] = 'yes';
        $urls['vpn_required'] = !empty($vpnCfg['vpn_required']) ? 'yes' : 'no';
        $urls['vpn_auto_connect'] = !empty($vpnCfg['vpn_auto_connect']) ? 'yes' : 'no';
    }

    $supportLink = support_link_from_config($support);
    if (($support['support_qr_url'] ?? '') === '') {
        $support['support_qr_url'] = qr_service_url($supportLink);
    }
    $support['support_link'] = $supportLink;

    $logoUrl = trim((string)($branding['app_logo_url'] ?? ''));
    if ($logoUrl === '') {
        $logoUrl = panel_absolute_url('img/app_brand/home_logo.png');
    }
    $branding['app_logo_url'] = $logoUrl;
    $branding['img_splash_logo'] = $logoUrl;
    $branding['img_logo'] = $logoUrl;

    $messageActive = ($messages['msg_status'] ?? '') === 'ACTIVE' && trim((string)($messages['message'] ?? '')) !== '';
    $appMessageStatus = $messageActive ? 'ACTIVE' : 'INACTIVE';
    $appMessageText = $messageActive ? (string)$messages['message'] : '';
    $effectiveShowExpire = ($core['expiry_popup_enabled'] ?? 'yes') === 'yes' ? (string)$core['show_expire'] : 'no';

    json_response([
        'success' => '1',
        'status' => $core['status'],
        'cid' => $cid,
        'which' => $tag,
        'ip' => (string)($_SERVER['REMOTE_ADDR'] ?? ''),
        'app' => compat_encode([
            'id' => '1',
            'appname' => $appName,
            'expire' => $core['expire'],
            'login_type' => $core['login_type'],
            'version_code' => $core['version_code'],
            'filter_status' => $core['filter_status'],
            'epg_mode' => $core['epg_mode'],
            'apkautoupdate' => $core['apkautoupdate'],
            'show_expire' => $effectiveShowExpire,
            'expiry_popup_enabled' => $core['expiry_popup_enabled'],
        ], $keyPrefix . 'app'),
        'portal' => compat_encode($portal, $keyPrefix . 'portal'),
        'urls' => compat_encode($urls, $keyPrefix . 'urls'),
        'support' => $support,
        'branding' => $branding,
        'app_logo_url' => $logoUrl,
        'img_splash_logo' => $logoUrl,
        'img_logo' => $logoUrl,
        'msg_status' => $appMessageStatus,
        'message' => $appMessageText,
        'msg_txt' => $appMessageText,
        'msgid' => (string)($messages['msgid'] ?? '0'),
        'expiry_popup_enabled' => $core['expiry_popup_enabled'] === 'yes' ? 'yes' : 'no',
        'auto_login' => $deviceConfig,
        'vpn' => $vpnCfg,
        'vpnconfig' => $vpnCfg,
        'openvpn' => $vpnCfg,
        'button' => compat_encode($buttons, $keyPrefix . 'buttons'),
        'settings' => compat_encode($interface, $keyPrefix . 'sett'),
        'admobconfig' => $admob,
        'prebid' => $prebid,
        'vastconfig' => $vast,
        'freestar' => $ads['freestar'],
        'players' => $players,
        'ort_settings' => $playback,
        'maintenance' => $maintenance,
        'others' => $others,
    ]);
}

function route_legacy_api(string $path, string $method): void
{
    $clean = preg_replace('#/{2,}#', '/', preg_replace('#^/api4#', '', $path));

    if ($clean === '/panel_pro/api/client/devices/add' || str_ends_with($clean, '/devices/add') || str_ends_with($clean, '/device/add')) {
        $device = upsert_device(request_data());
        json_response(['success' => true, 'data' => ['device' => $device, 'config' => device_auto_config($device)]]);
    }

    if (str_ends_with($clean, '/devices/config') || str_ends_with($clean, '/device/config') || str_ends_with($clean, '/autologin')) {
        $device = upsert_device(request_data());
        json_response(['success' => true, 'data' => device_auto_config($device)] + device_auto_config($device));
    }

    if ($clean === '/panel_pro/api/client/login' || $clean === '/panel_pro/api/client/refresh_token') {
        json_response([
            'data' => [
                'access_token' => 'panel-' . bin2hex(random_bytes(16)),
                'refresh_token' => 'refresh-' . bin2hex(random_bytes(16)),
            ],
        ]);
    }

    if ($clean === '/panel_pro/api/client/content' || starts_with($clean, '/panel_pro/api/client/content/')) {
        $legacy = [];
        foreach (api_servers() as $server) {
            $legacy[] = [
                'id' => (string)$server['id'],
                'name' => $server['name'],
                'url' => $server['url'],
                'status' => 'active',
                'priority' => (int)$server['priority'],
            ];
        }
        json_response(['success' => true, 'data' => ['servers' => $legacy]]);
    }

    json_response(['message' => 'not_found'], 404);
}
