<?php
/**
 * Frontend configuration builder.
 *
 * @package BatoCookieConsent
 */

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

final class Bato_Cookie_Consent_Settings_Frontend_Config
{
    private Bato_Cookie_Consent_Settings_Metadata $metadata;

    public function __construct(Bato_Cookie_Consent_Settings_Metadata $metadata)
    {
        $this->metadata = $metadata;
    }

    public function build(array $settings): array
    {
        $logo = $this->metadata->resolve_logo_url($settings);
        $logo_disabled = ! empty($settings['general']['logoDisabled']);
        $components = array(
            'buttons' => $this->banner_buttons($settings['general']['bannerType']),
        );

        $config = array(
            'autoShow' => (bool) $settings['general']['enabled'],
            'mode' => $settings['general']['mode'],
            'policyVersion' => $settings['updated_at'],
            'language' => $settings['general']['language'],
            'defaultLanguage' => 'en',
            'fallbackLanguage' => 'en',
            'layout' => $settings['general']['layout'],
            'providedBy' => $settings['general']['providedBy'],
            'policyLinks' => $settings['policyLinks'],
            'content' => $settings['content'],
            'storage' => array(
                'type' => 'cookie',
                'cookieName' => 'cookie_consent',
                'expiresDays' => $settings['advanced']['expiresDays'],
                'sameSite' => 'Lax',
                'secure' => is_ssl(),
                'domain' => '',
                'path' => '/',
            ),
            'style' => array(
                'className' => $settings['styling']['className'],
            ),
            'floatingButton' => array(
                'enabled' => (bool) $settings['advanced']['floatingButton']['enabled'],
                'showAfterConsent' => (bool) $settings['advanced']['floatingButton']['showAfterConsent'],
            ),
            'integrations' => array(
                'googleConsentMode' => $settings['advanced']['googleConsentMode'],
            ),
        );

        if ($logo_disabled) {
            $components['logo'] = false;
        } elseif ($logo) {
            $config['logo'] = $logo;
        }

        $config['components'] = $components;

        return apply_filters('bato_cookie_consent_config', $config, $settings);
    }

    private function banner_buttons(string $banner_type): array
    {
        $button_modes = array(
            'full' => array('acceptAll' => true, 'customize' => true, 'rejectAll' => true),
            'accept-only' => array('acceptAll' => true, 'customize' => false, 'rejectAll' => false),
            'no-customize' => array('acceptAll' => true, 'customize' => false, 'rejectAll' => true),
            'no-reject' => array('acceptAll' => true, 'customize' => true, 'rejectAll' => false),
        );

        return $button_modes[$banner_type] ?? $button_modes['full'];
    }
}
