<?php
// app/app/whitelabel.php
// Carrega configurações de white label do JSON em /public/whitelabel.json
// Agora suporta seções: login (tela de login) e system (sidebar/dashboard)

/**
 * Defaults da Evolua Prospect
 */
function wl_defaults(): array {
    return [
        'login' => [
            'brand'          => '#6ee7ff',
            'brand2'         => '#7c3aed',
            'logo_url'       => 'assets/brand/logotipo.png',
            'favicon_url'    => 'assets/brand/favicon.png',
            'support_url'    => '',         // ← NOVO: URL do botão "Suporte" da tela de login
            'support_target' => '_blank',   // ← NOVO: '_blank' (nova aba) ou '_self' (mesma aba)
        ],
        'system' => [
            'brand'       => '#6ee7ff',
            'brand2'      => '#7c3aed',
            'sidebar_bg1' => '#221845',
            'sidebar_bg2' => '#0A0E19',
            'topbar_buttons' => [
                [
                    'label' => '🚀 Seja um Afiliado',
                    'url'   => 'https://prospect.evoluapainel.com/afiliacao.html',
                    'bg'    => '#6ee7ff',
                    'bg2'   => '#7c3aed',
                    'text'  => '#0b1020',
                ],
            ],
        ],
        'updated_at' => null,
    ];
}

/**
 * Lê o JSON. Faz migração transparente do formato v1 (raiz) pro v2 (seções).
 */
function wl_load(): array {
    static $cached = null;
    if ($cached !== null) return $cached;

    $defaults = wl_defaults();
    $jsonPath = __DIR__ . '/../public/whitelabel.json';

    if (!file_exists($jsonPath) || !is_readable($jsonPath)) {
        $cached = $defaults;
        return $cached;
    }

    $raw = @file_get_contents($jsonPath);
    if ($raw === false) {
        $cached = $defaults;
        return $cached;
    }

    $data = json_decode($raw, true);
    if (!is_array($data)) {
        $cached = $defaults;
        return $cached;
    }

    // ============ MIGRAÇÃO V1 → V2 ============
    if (!isset($data['login']) && !isset($data['system'])) {
        $data = [
            'login' => [
                'brand'          => $data['brand']       ?? $defaults['login']['brand'],
                'brand2'         => $data['brand2']      ?? $defaults['login']['brand2'],
                'logo_url'       => $data['logo_url']    ?? $defaults['login']['logo_url'],
                'favicon_url'    => $data['favicon_url'] ?? $defaults['login']['favicon_url'],
                'support_url'    => $defaults['login']['support_url'],
                'support_target' => $defaults['login']['support_target'],
            ],
            'system' => [
                'brand'       => $data['brand']       ?? $defaults['system']['brand'],
                'brand2'      => $data['brand2']      ?? $defaults['system']['brand2'],
                'sidebar_bg1' => $defaults['system']['sidebar_bg1'],
                'sidebar_bg2' => $defaults['system']['sidebar_bg2'],
            ],
            'updated_at' => $data['updated_at'] ?? null,
        ];
    }

    // ============ Validação por seção ============
    $valid = [
        'login'  => wl_validate_login_section($data['login']  ?? [], $defaults['login']),
        'system' => wl_validate_system_section($data['system'] ?? [], $defaults['system']),
        'updated_at' => $data['updated_at'] ?? null,
    ];

    $cached = $valid;
    return $cached;
}

function wl_validate_login_section(array $data, array $defaults): array {
    return [
        'brand'          => wl_validate_color($data['brand']          ?? null, $defaults['brand']),
        'brand2'         => wl_validate_color($data['brand2']         ?? null, $defaults['brand2']),
        'logo_url'       => wl_validate_url(  $data['logo_url']       ?? null, $defaults['logo_url']),
        'favicon_url'    => wl_validate_url(  $data['favicon_url']    ?? null, $defaults['favicon_url']),
        'support_url'    => wl_validate_url(  $data['support_url']    ?? null, $defaults['support_url']),
        'support_target' => wl_validate_target($data['support_target'] ?? null, $defaults['support_target']),
    ];
}

function wl_validate_system_section(array $data, array $defaults): array {
    return [
        'brand'          => wl_validate_color($data['brand']       ?? null, $defaults['brand']),
        'brand2'         => wl_validate_color($data['brand2']      ?? null, $defaults['brand2']),
        'sidebar_bg1'    => wl_validate_color($data['sidebar_bg1'] ?? null, $defaults['sidebar_bg1']),
        'sidebar_bg2'    => wl_validate_color($data['sidebar_bg2'] ?? null, $defaults['sidebar_bg2']),
        'topbar_buttons' => wl_validate_topbar_buttons($data['topbar_buttons'] ?? null),
    ];
}

function wl_validate_topbar_buttons($value): array {
    if (!is_array($value)) return [];

    $valid = [];
    foreach ($value as $btn) {
        if (!is_array($btn)) continue;

        $label = isset($btn['label']) && is_string($btn['label']) ? trim($btn['label']) : '';
        $url   = isset($btn['url'])   && is_string($btn['url'])   ? trim($btn['url'])   : '';

        if ($label === '' || mb_strlen($label) > 60) continue;
        if ($url === '') continue;

        if (!preg_match('#^https?://#i', $url)) {
            if (!preg_match('#^[?/][a-zA-Z0-9\-_/?=&.]*$#', $url)) continue;
        } else {
            if (!filter_var($url, FILTER_VALIDATE_URL)) continue;
        }

        $valid[] = [
            'label' => $label,
            'url'   => $url,
            'bg'    => wl_validate_color($btn['bg']   ?? null, '#6ee7ff'),
            'bg2'   => wl_validate_color($btn['bg2']  ?? null, '#7c3aed'),
            'text'  => wl_validate_color($btn['text'] ?? null, '#0b1020'),
        ];

        if (count($valid) >= 3) break;
    }

    return $valid;
}

/**
 * Valida hex (#fff ou #ffffff). Retorna fallback se inválido.
 */
function wl_validate_color($value, string $fallback): string {
    if (!is_string($value)) return $fallback;
    $value = trim($value);
    if (preg_match('/^#([a-fA-F0-9]{3}|[a-fA-F0-9]{6})$/', $value)) {
        return $value;
    }
    return $fallback;
}

/**
 * Valida URL absoluta ou caminho relativo seguro. String vazia é permitida (campo opcional).
 */
function wl_validate_url($value, string $fallback): string {
    if (!is_string($value)) return $fallback;
    $value = trim($value);
    if ($value === '') return $fallback;

    if (preg_match('#^https?://#i', $value)) {
        return filter_var($value, FILTER_VALIDATE_URL) ? $value : $fallback;
    }
    if (preg_match('#(\.\.|//|javascript:|data:)#i', $value)) {
        return $fallback;
    }
    return $value;
}

/**
 * Valida target de link (_blank | _self). Retorna fallback se inválido.
 */
function wl_validate_target($value, string $fallback = '_blank'): string {
    return in_array($value, ['_blank', '_self'], true) ? $value : $fallback;
}

/**
 * Atalho: pega a seção de login.
 */
function wl_login(): array {
    $wl = wl_load();
    return $wl['login'];
}

/**
 * Atalho: pega a seção de system.
 * Logo do system = logo do login (sempre a mesma marca).
 */
function wl_system(): array {
    $wl = wl_load();
    $sys = $wl['system'];
    $sys['logo_url']    = $wl['login']['logo_url'];
    $sys['favicon_url'] = $wl['login']['favicon_url'];
    return $sys;
}
