<?php

namespace App\Services;

use Illuminate\Support\Facades\Cache;
use Modules\Admin\App\Models\Setting;

class WebsiteTemplateService
{
    private $cacheTTL = 60 * 24 * 30; // 30 días en minutos

    /**
     * Actualiza o crea un ajuste en la base de datos.
     */
    public function updateSetting(string $key, string $value): bool
    {
        $setting = Setting::updateOrCreate(
            ['key' => $key],
            ['value' => trim($value)]
        );

        return $setting->save();
    }

    /**
     * Obtiene las variables del sitio web desde el caché o la base de datos.
     */
    public function getWebsiteVars(String $setting = ''): array
    {
        try {
            $webVars = Cache::remember('website_settings', $this->cacheTTL, function () {
                $settings = Setting::global()
                    ->where(function ($query) {
                        $query->where('key', 'LIKE', 'website_%')
                            ->orWhere('key', 'LIKE', 'google_%')
                            ->orWhere('key', 'LIKE', 'chat_%');
                    })
                    ->pluck('value', 'key')
                    ->toArray();

                return [
                    'title'       => $settings['website_title'] ?? config('_var.appTitle'),
                    'author'      => config('_var.author'),
                    'description' => $settings['website_description'] ?? config('_var.appDescription'),
                    'favicon'     => $this->getFaviconPaths($settings),
                    'app_name'    => $settings['website_app_name'] ?? config('_var.appName'),
                    'image_logo'  => $this->getImageLogoPaths($settings),
                    'template'    => $this->getTemplateVars($settings),
                    'google'      => $this->getGoogleVars($settings),
                    'chat'        => $this->getChatVars($settings),
                    'contact'     => $this->getContactVars(),
                    'social'      => $this->getSocialVars(),
                ];
            });

            return $setting
                ? $webVars[$setting]
                : $webVars;
        } catch (\Exception $e) {
            echo __METHOD__;
            echo "<br>" . $e->getMessage() . "<br><br>";
            die('You must configure the database.');
        }
    }

    /**
     * Obtiene los paths de favicon en distintos tamaños.
     */
    private function getFaviconPaths(array $settings): array
    {
        $defaultFavicon = config('_var.appFavicon');
        $namespace = $settings['website_favicon_ns'] ?? null;

        return [
            'namespace' => $namespace,
            '16x16'     => $namespace ? "{$namespace}_16x16.png" : $defaultFavicon,
            '76x76'     => $namespace ? "{$namespace}_76x76.png" : $defaultFavicon,
            '120x120'   => $namespace ? "{$namespace}_120x120.png" : $defaultFavicon,
            '152x152'   => $namespace ? "{$namespace}_152x152.png" : $defaultFavicon,
            '180x180'   => $namespace ? "{$namespace}_180x180.png" : $defaultFavicon,
            '192x192'   => $namespace ? "{$namespace}_192x192.png" : $defaultFavicon,
        ];
    }

    /**
     * Obtiene los paths de los logos en distintos tamaños.
     */
    private function getImageLogoPaths(array $settings): array
    {
        $defaultLogo = config('_var.appLogo');

        return [
            'small'       => $this->getImagePath($settings, 'website_image_logo_small', $defaultLogo),
            'medium'      => $this->getImagePath($settings, 'website_image_logo_medium', $defaultLogo),
            'large'       => $this->getImagePath($settings, 'website_image_logo', $defaultLogo),
            'small_dark'  => $this->getImagePath($settings, 'website_image_logo_small_dark', $defaultLogo),
            'medium_dark' => $this->getImagePath($settings, 'website_image_logo_medium_dark', $defaultLogo),
            'large_dark'  => $this->getImagePath($settings, 'website_image_logo_dark', $defaultLogo),
        ];
    }

    /**
     * Obtiene un path de imagen o retorna un valor predeterminado.
     */
    private function getImagePath(array $settings, string $key, string $default): string
    {
        return $settings[$key] ?? $default;
    }

    /**
     * Obtiene las configuraciones de plantilla.
     */
    private function getTemplateVars(array $settings): array
    {
        return [
            'style_switcher' => (bool)($settings['website_tpl_style_switcher'] ?? false),
            'footer_text'    => $settings['website_tpl_footer_text'] ?? '',
        ];
    }

    /**
     * Obtiene las configuraciones de Google Analytics.
     */
    private function getGoogleVars(array $settings): array
    {
        return [
            'analytics' => [
                'enabled' => (bool)($settings['google_analytics_enabled'] ?? false),
                'id'      => $settings['google_analytics_id'] ?? '',
            ]
        ];
    }

    /**
     * Obtiene las configuraciones del proveedor de Chat.
     */
    private function getChatVars(array $settings): array
    {
        return [
            'provider'         => $settings['chat_provider'] ?? '',
            'whatsapp_number'  => $settings['chat_whatsapp_number'] ?? '',
            'whatsapp_message' => $settings['chat_whatsapp_message'] ?? '',
        ];
    }

    /**
     * Obtiene las variables de contacto.
     */
    public function getContactVars(): array
    {
        $settings = Setting::global()
            ->where('key', 'LIKE', 'contact_%')
            ->pluck('value', 'key')
            ->toArray();

        return [
            'phone_number' => isset($settings['contact_phone_number'])
                ? preg_replace('/\D/', '', $settings['contact_phone_number'])  // Elimina todo lo que no sea un número
                : '',
            'phone_number_text' => $settings['contact_phone_number'] ?? '',
            'phone_number_ext' => $settings['contact_phone_number_ext'] ?? '',
            'email'     => $settings['contact_email'] ?? '',
            'direccion' => $settings['contact_direccion'] ?? '',
            'horario'   => $settings['contact_horario'] ?? '',
            'location' => [
                'lat' => $settings['contact_location_lat'] ?? '',
                'lng' => $settings['contact_location_lng'] ?? '',
            ],
            'form' => [
                'email'    => $settings['contact_form_email'] ?? '',
                'email_cc' => $settings['contact_form_email_cc'] ?? '',
                'subject'  => $settings['contact_form_subject'] ?? '',
            ],
        ];
    }

    /**
     * Obtiene las variables de redes sociales.
     */
    public function getSocialVars(): array
    {
        $social = Setting::global()
            ->where('key', 'LIKE', 'social_%')
            ->pluck('value', 'key')
            ->toArray();

        return [
            'whatsapp'         => $social['social_whatsapp'] ?? '',
            'whatsapp_message' => $social['social_whatsapp_message'] ?? '',
            'facebook'         => $social['social_facebook'] ?? '',
            'instagram'        => $social['social_instagram'] ?? '',
            'linkedin'         => $social['social_linkedin'] ?? '',
            'tiktok'           => $social['social_tiktok'] ?? '',
            'x_twitter'        => $social['social_x_twitter'] ?? '',
            'google'           => $social['social_google'] ?? '',
            'pinterest'        => $social['social_pinterest'] ?? '',
            'youtube'          => $social['social_youtube'] ?? '',
            'vimeo'            => $social['social_vimeo'] ?? '',
        ];
    }

    /**
     * Limpia el caché de las variables del sitio web.
     */
    public static function clearWebsiteVarsCache(): void
    {
        Cache::forget('website_settings');
    }

    /**
     * Obtiene las variables legales.
     */
    public function getLegalVars($legalDocument = false)
    {
        $legal = Setting::global()
            ->where('key', 'LIKE', 'legal_%')
            ->pluck('value', 'key')
            ->toArray();

        $legalDocuments =  [
            'legal_terminos_y_condiciones' => [
                'title' => 'Términos y condiciones',
                'enabled' => (bool)($legal['legal_terminos_y_condiciones_enabled'] ?? false),
                'content' => $legal['legal_terminos_y_condiciones_content'] ?? '',
            ],
            'legal_aviso_de_privacidad' => [
                'title' => 'Aviso de privacidad',
                'enabled' => (bool)($legal['legal_aviso_de_privacidad_enabled'] ?? false),
                'content' => $legal['legal_aviso_de_privacidad_content'] ?? '',
            ],
            'legal_politica_de_devoluciones' => [
                'title' => 'Política de devoluciones y reembolsos',
                'enabled' => (bool)($legal['legal_politica_de_devoluciones_enabled'] ?? false),
                'content' => $legal['legal_politica_de_devoluciones_content'] ?? '',
            ],
            'legal_politica_de_envios' => [
                'title' => 'Política de envíos',
                'enabled' => (bool)($legal['legal_politica_de_envios_enabled'] ?? false),
                'content' => $legal['legal_politica_de_envios_content'] ?? '',
            ],
            'legal_politica_de_cookies' => [
                'title' => 'Política de cookies',
                'enabled' => (bool)($legal['legal_politica_de_cookies_enabled'] ?? false),
                'content' => $legal['legal_politica_de_cookies_content'] ?? '',
            ],
            'legal_autorizaciones_y_licencias' => [
                'title' => 'Autorizaciones y licencias',
                'enabled' => (bool)($legal['legal_autorizaciones_y_licencias_enabled'] ?? false),
                'content' => $legal['legal_autorizaciones_y_licencias_content'] ?? '',
            ],
            'legal_informacion_comercial' => [
                'title' => 'Información comercial',
                'enabled' => (bool)($legal['legal_informacion_comercial_enabled'] ?? false),
                'content' => $legal['legal_informacion_comercial_content'] ?? '',
            ],
            'legal_consentimiento_para_el_login_de_terceros' => [
                'title' => 'Consentimiento para el login de terceros',
                'enabled' => (bool)($legal['legal_consentimiento_para_el_login_de_terceros_enabled'] ?? false),
                'content' => $legal['legal_consentimiento_para_el_login_de_terceros_content'] ?? '',
            ],
            'legal_leyendas_de_responsabilidad' => [
                'title' => 'Leyendas de responsabilidad',
                'enabled' => (bool)($legal['legal_leyendas_de_responsabilidad_enabled'] ?? false),
                'content' => $legal['legal_leyendas_de_responsabilidad_content'] ?? '',
            ],
        ];

        return $legalDocument
            ? $legalDocuments[$legalDocument]
            : $legalDocuments;
    }
}