<?php

namespace Modules\Admin\App\Livewire\WebsiteSettings;

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

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

    public $contact_direccion,
        $contact_horario,
        $contact_location_lat,
        $contact_location_lng;

    protected $listeners = ['saveLocationSettings' => '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_direccion    = $settings['contact']['direccion'];
        $this->contact_horario      = $settings['contact']['horario'];
        $this->contact_location_lat = $settings['contact']['location']['lat'];
        $this->contact_location_lng = $settings['contact']['location']['lng'];
    }

    public function save()
    {
        $this->validate([
            'contact_direccion' => ['nullable', 'string', 'max:255'],
            'contact_horario' => ['nullable', 'string', 'max:255'],
            'contact_location_lat' => ['nullable', 'numeric'],
            'contact_location_lng' => ['nullable', 'numeric'],
        ]);

        $websiteSettingsService = app(WebsiteSettingsService::class);

        // Guardar título del App en configuraciones
        $websiteSettingsService->updateSetting('contact_direccion', $this->contact_direccion);
        $websiteSettingsService->updateSetting('contact_horario', $this->contact_horario);
        $websiteSettingsService->updateSetting('contact_location_lat', $this->contact_location_lat);
        $websiteSettingsService->updateSetting('contact_location_lng', $this->contact_location_lng);

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