<?php

namespace Modules\Admin\App\Livewire\WebsiteSettings;

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

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

    public $contact_phone_number,
        $contact_phone_number_ext,
        $contact_email;

    protected $listeners = ['saveContactInfoSettings' => '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->contact_phone_number     = $settings['contact']['phone_number'];
        $this->contact_phone_number_ext = $settings['contact']['phone_number_ext'];
        $this->contact_email            = $settings['contact']['email'];
    }

    public function save()
    {
        $this->validate([
            'contact_phone_number' => ['nullable', 'string', 'max:20'],
            'contact_phone_number_ext' => ['nullable', 'string', 'max:10'],
            'contact_email' => ['nullable', 'email']
        ]);

        $websiteSettingsService = app(WebsiteSettingsService::class);

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

        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.contact-info-settings');
    }
}
