<?php

namespace Modules\Admin\App\Livewire\WebsiteSettings;

use Livewire\Component;
use App\Services\WebsiteTemplateService;

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

    public $website_tpl_style_switcher,
        $website_tpl_footer_text;

    protected $listeners = ['saveTemplateSettings' => '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();

        $this->website_tpl_style_switcher = $settings['template']['style_switcher'];
        $this->website_tpl_footer_text    = $settings['template']['footer_text'];
    }

    public function save()
    {
        $this->validate([
            'website_tpl_footer_text' => 'nullable|string|max:50',
        ]);

        $websiteTemplateService = app(WebsiteTemplateService::class);

        // Guardar título del App en configuraciones
        $websiteTemplateService->updateSetting('website_tpl_style_switcher', $this->website_tpl_style_switcher);
        $websiteTemplateService->updateSetting('website_tpl_footer_text', $this->website_tpl_footer_text);

        $websiteTemplateService->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.template-settings');
    }
}