<?php

namespace Modules\Admin\App\Livewire\WebsiteSettings;

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

class ImageLogoSettings extends Component
{
    use WithFileUploads;

    private $targetNotify = "#website-image-logo-settings-card .notification-container";

    public $website_image_logo,
        $website_image_logo_dark;

    public $upload_image_logo,
        $upload_image_logo_dark;

    public function mount()
    {
        $this->loadSettings();
    }

    public function loadSettings()
    {
        $websiteTemplateService = app(WebsiteTemplateService::class);

        $this->upload_image_logo      = null;
        $this->upload_image_logo_dark = null;

        // Obtener los valores de las configuraciones de la base de datos
        $settings = $websiteTemplateService->getWebsiteVars();

        $this->website_image_logo      = $settings['image_logo']['large'];
        $this->website_image_logo_dark = $settings['image_logo']['large_dark'];
    }

    public function save()
    {
        $this->validate([
            'upload_image_logo' => 'nullable|image|mimes:jpeg,png,jpg,svg,webp|max:20480',
            'upload_image_logo_dark' => 'nullable|image|mimes:jpeg,png,jpg,svg,webp|max:20480',
        ]);

        $websiteSettingsService = app(WebsiteSettingsService::class);

        // Procesar favicon si se ha cargado una imagen
        if ($this->upload_image_logo) {
            $websiteSettingsService->processAndSaveImageLogo($this->upload_image_logo);
        }

        if ($this->upload_image_logo_dark) {
            $websiteSettingsService->processAndSaveImageLogo($this->upload_image_logo_dark, 'dark');
        }

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