<?php
/**
 * Settings metadata for the admin app.
 *
 * @package BatoCookieConsent
 */

if (! defined('ABSPATH')) {
    exit;
}

final class Bato_Cookie_Consent_Settings_Metadata
{
    public function metadata(array $settings): array
    {
        $logo_id = absint($settings['general']['logoAttachmentId']);
        $selected_logo = $logo_id ? wp_get_attachment_image_url($logo_id, 'full') : '';

        return array(
            'supportedLanguages' => Bato_Cookie_Consent_Settings_Languages::supported(),
            'siteLocale' => get_locale(),
            'defaultLanguage' => Bato_Cookie_Consent_Settings_Languages::default_language(),
            'defaultLogoUrl' => $this->default_logo_url(),
            'siteLogoUrl' => $this->site_logo_url(),
            'selectedLogoUrl' => $selected_logo,
            'logoDisabled' => ! empty($settings['general']['logoDisabled']),
            'labels' => Bato_Cookie_Consent_Settings_Defaults::admin_labels(),
        );
    }

    public function resolve_logo_url(array $settings): string
    {
        if (! empty($settings['general']['logoDisabled'])) {
            return '';
        }

        if (! empty($settings['general']['useDefaultLogo'])) {
            return $this->default_logo_url();
        }

        $attachment_id = absint($settings['general']['logoAttachmentId'] ?? 0);

        if ($attachment_id) {
            $logo = wp_get_attachment_image_url($attachment_id, 'full');

            if ($logo) {
                return esc_url_raw($logo);
            }
        }

        $site_logo = $this->site_logo_url();

        return $site_logo ?: $this->default_logo_url();
    }

    private function site_logo_url(): string
    {
        $site_logo_id = absint(get_theme_mod('custom_logo'));

        if (! $site_logo_id) {
            return '';
        }

        $site_logo = wp_get_attachment_image_url($site_logo_id, 'full');

        return $site_logo ? esc_url_raw($site_logo) : '';
    }

    private function default_logo_url(): string
    {
        return esc_url_raw(BATO_COOKIE_CONSENT_URL . 'assets/bato-cookie-consent.svg');
    }
}
