<?php
/**
 * Helpers compartilhados pelos endpoints consumidos pelo aplicativo TV VIP.
 * Mantém compatibilidade com os dois formatos observados no APK:
 * 1) codificação customizada do LoginActivity;
 * 2) Base64 simples do ChangePlaylistActivity.
 */

function api_json_response(array $payload, int $status = 200): void {
    if (!headers_sent()) {
        http_response_code($status);
        header('Content-Type: application/json; charset=utf-8');
        header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    }
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function api_read_request(): array {
    $raw = file_get_contents('php://input');
    $request = is_string($raw) && trim($raw) !== '' ? json_decode($raw, true) : null;

    if (!is_array($request) && isset($_POST['data'])) {
        $request = ['data' => (string)$_POST['data']];
    }

    return is_array($request) ? $request : [];
}

function api_decode_app_data($encoded): ?array {
    if (!is_string($encoded) || $encoded === '') {
        return null;
    }

    // Fluxo customizado usado no login.
    if (function_exists('getDecodedString')) {
        try {
            $decoded = getDecodedString($encoded);
            if (is_string($decoded) && $decoded !== '') {
                $json = json_decode($decoded, true);
                if (is_array($json)) return $json;
            }
        } catch (Throwable $e) {
            // continua nos fallbacks
        }
    }

    // Fluxo Base64 simples usado na troca/consulta de listas.
    $decoded = base64_decode($encoded, true);
    if (is_string($decoded) && $decoded !== '') {
        $json = json_decode($decoded, true);
        if (is_array($json)) return $json;
    }

    // Compatibilidade de manutenção: aceita JSON bruto no campo data.
    $json = json_decode($encoded, true);
    return is_array($json) ? $json : null;
}

function api_normalize_mac(string $value): string {
    $hex = strtoupper(preg_replace('/[^0-9A-Fa-f]/', '', trim($value)) ?? '');
    if (strlen($hex) < 12) return '';
    $hex = substr($hex, 0, 12);
    return implode(':', str_split($hex, 2));
}

function api_mac_from_payload(array $payload): string {
    if (!empty($payload['mac_address'])) {
        return api_normalize_mac((string)$payload['mac_address']);
    }

    if (!empty($payload['app_device_id'])) {
        $raw = base64_decode((string)$payload['app_device_id'], true);
        if (is_string($raw)) {
            return api_normalize_mac($raw);
        }
    }

    if (!empty($payload['device_id_raw'])) {
        return api_normalize_mac((string)$payload['device_id_raw']);
    }

    return '';
}

function api_scheme(): string {
    $forwarded = $_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '';
    if ($forwarded !== '') {
        $first = strtolower(trim(explode(',', $forwarded)[0]));
        if ($first === 'https') return 'https';
    }

    $https = $_SERVER['HTTPS'] ?? '';
    return ($https !== '' && strtolower((string)$https) !== 'off') || ((int)($_SERVER['SERVER_PORT'] ?? 0) === 443)
        ? 'https' : 'http';
}

function api_panel_base_url(): string {
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $script = str_replace('\\', '/', $_SERVER['SCRIPT_NAME'] ?? '/api/auth.php');
    $apiDir = rtrim(dirname($script), '/');
    $panelDir = rtrim(dirname($apiDir), '/');
    return api_scheme() . '://' . $host . ($panelDir === '/' ? '' : $panelDir);
}

function api_make_device_key(): string {
    try {
        return str_pad((string)random_int(0, 999999), 6, '0', STR_PAD_LEFT);
    } catch (Throwable $e) {
        return str_pad((string)mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
    }
}

function api_get_or_create_device(SQLiteWrapper $db, string $mac, string $deviceType = ''): array {
    $rows = $db->select('devices', '*', 'mac_address = :mac', '', [':mac' => $mac]);
    $now = date('Y-m-d H:i:s');

    if (!empty($rows)) {
        $device = $rows[0];
        $key = trim((string)($device['device_key'] ?? ''));
        if ($key === '') $key = api_make_device_key();

        $db->update('devices', [
            'device_key' => $key,
            'device_type' => $deviceType !== '' ? $deviceType : (string)($device['device_type'] ?? ''),
            'last_seen' => $now
        ], 'mac_address = :mac', [':mac' => $mac]);

        $device['device_key'] = $key;
        if ($deviceType !== '') $device['device_type'] = $deviceType;
        $device['last_seen'] = $now;
        return $device;
    }

    $device = [
        'mac_address' => $mac,
        'device_key' => api_make_device_key(),
        'device_type' => $deviceType,
        'parent_control' => '0000',
        'created_at' => $now,
        'last_seen' => $now
    ];
    $db->insert('devices', $device);
    return $device;
}

function api_active_theme(SQLiteWrapper $db): array {
    $rows = $db->select('themes', '*', 'is_active = :active', 'id DESC', [':active' => 1]);
    if (empty($rows)) {
        $rows = $db->select('themes', '*', '', 'id DESC');
    }
    return $rows[0] ?? ['theme_id' => '1', 'layout_name' => 'activity_main'];
}

function api_update_settings(SQLiteWrapper $db): array {
    $rows = $db->select('update_settings', '*', 'id = :id', '', [':id' => 1]);
    return $rows[0] ?? [
        'version_code' => 0,
        'version_name' => '',
        'apk_url' => '',
        'changelog' => '',
        'force' => 0
    ];
}

function api_qr_target(SQLiteWrapper $db): string {
    $rows = $db->select('qr_code', '*', 'id = :id', '', [':id' => 1]);
    return trim((string)($rows[0]['url'] ?? ''));
}
