<?php

namespace Modules\Admin\App\Livewire\WebsiteSettings;

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

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

    public $website_title,
        $website_description;

    protected $listeners = ['saveWebsiteSettings' => '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_title        = $settings['title'];
        $this->website_description  = $settings['description'];
    }

    public function save()
    {
        $this->validate([
            'website_title' => 'string|required|max:50',
            'website_description' => 'string|max:160',
        ]);

        $websiteTemplateService = app(WebsiteTemplateService::class);

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

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