<?php

namespace Modules\Admin\App\Livewire\WebsiteSettings;

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

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

    public $contact_form_email,
        $contact_form_email_cc,
        $contact_form_subject;

    protected $listeners = ['saveContactFormSettings' => '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_form_email    = $settings['contact']['form']['email'];
        $this->contact_form_email_cc = $settings['contact']['form']['email_cc'];
        $this->contact_form_subject  = $settings['contact']['form']['subject'];
    }

    public function save()
    {
        $this->validate([
            'contact_form_email'    => 'required|email',
            'contact_form_email_cc' => 'nullable|email',
            'contact_form_subject'  => 'required|string'
        ]);

        $websiteSettingsService = app(WebsiteSettingsService::class);

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

        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-form-settings');
    }
}
