<?php

namespace Modules\Admin\App\Livewire\WebsiteSettings;

use Livewire\Component;
use App\Services\WebsiteTemplateService;
use Modules\Admin\App\Services\WebsiteSettingsService;

class AnalyticsSettings extends Component
{
    private $targetNotify = "#website-analytics-settings-card .notification-container";

    public $google_analytics_enabled,
        $google_analytics_id;

    protected $listeners = ['saveAnalyticsSettings' => 'save'];

    public function mount()
    {
        $this->loadSettings();
    }

    public function loadSettings()
    {
        $WebsiteTemplateService = app(WebsiteTemplateService::class);

        // Obtener los valores de las configuraciones de la base de datos
        $settings = $WebsiteTemplateService->getWebsiteVars('google');

        $this->google_analytics_enabled = $settings['analytics']['enabled'];
        $this->google_analytics_id      = $settings['analytics']['id'];
    }

    public function save()
    {
        if ($this->google_analytics_enabled) {
            $this->validate([
                'google_analytics_id' => 'required|string|min:12|max:30',
            ]);
        }

        $websiteSettingsService = app(WebsiteSettingsService::class);

        // Guardar título del App en configuraciones
        $websiteSettingsService->updateSetting('google_analytics_enabled', $this->google_analytics_enabled);
        $websiteSettingsService->updateSetting('google_analytics_id', $this->google_analytics_id);

        app(WebsiteTemplateService::class)->clearWebsiteVarsCache();

        $this->loadSettings();

        $this->dispatch(
            'notification',
            target: $this->targetNotify,
            type: 'success',
            message: 'Se han guardado los cambios en las configuraciones.'
        );
    }

    public function render()
    {
        return view('admin::livewire.website-settings.analytics-settings');
    }
}
