<?php

namespace Modules\Admin\App\Livewire\WebsiteSettings;

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

class FaviconSettings extends Component
{
    use WithFileUploads;

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

    public $upload_image_favicon;
    public $website_favicon_16x16,
        $website_favicon_76x76,
        $website_favicon_120x120,
        $website_favicon_152x152,
        $website_favicon_180x180,
        $website_favicon_192x192;

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

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

        $this->upload_image_favicon = null;

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

        $this->website_favicon_16x16   = $settings['favicon']['16x16'];
        $this->website_favicon_76x76   = $settings['favicon']['76x76'];
        $this->website_favicon_120x120 = $settings['favicon']['120x120'];
        $this->website_favicon_152x152 = $settings['favicon']['152x152'];
        $this->website_favicon_180x180 = $settings['favicon']['180x180'];
        $this->website_favicon_192x192 = $settings['favicon']['192x192'];
    }

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

        // Procesar favicon si se ha cargado una imagen
        $websiteSettingsService = app(WebsiteSettingsService::class);
        $websiteSettingsService->processAndSaveFavicon($this->upload_image_favicon);

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