<?php

namespace Modules\Admin\App\Livewire\WebsiteSettings;

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

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

    public $chat_provider,
        $chat_whatsapp_number,
        $chat_whatsapp_message;

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

        $this->chat_provider         = $settings['provider'];
        $this->chat_whatsapp_number  = $settings['whatsapp_number'];
        $this->chat_whatsapp_message = $settings['whatsapp_message'];
    }

    public function save()
    {
        if ($this->chat_provider == 'whatsapp') {
            $this->validate([
                'chat_whatsapp_number' => 'required|string|max:20',
                'chat_whatsapp_message' => 'required|string|max:255',
            ]);
        }

        $websiteSettingsService = app(WebsiteSettingsService::class);

        // Guardar título del App en configuraciones
        $websiteSettingsService->updateSetting('chat_provider', $this->chat_provider);
        $websiteSettingsService->updateSetting('chat_whatsapp_number', preg_replace('/\D/', '', $this->chat_whatsapp_number));
        $websiteSettingsService->updateSetting('chat_whatsapp_message', $this->chat_whatsapp_message);

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