<?php

namespace App\Livewire\Settings;

use App\Livewire\Forms\SettingsForm;
use App\Models\Setting;
use Livewire\Component;
use Livewire\WithFileUploads;

class General extends Component
{
    use WithFileUploads;

    public SettingsForm $settings_form;
    public Setting $settings;

    public function render() {
        return view('livewire.settings.general');
    }

    public function hasChangedImage($logo) {
        return $this->settings_form->$logo!=$this->settings->$logo;
    }
    
    public function rules() {
        return [
            'settings_form.site_logo' => $this->hasChangedImage('site_logo') ? 'required|mimes:jpeg,png|max:3072': '',
            'settings_form.site_favicon' =>$this->hasChangedImage('site_favicon') ? 'required|mimes:jpeg,png,ico|max:3072': '',
            'settings_form.site_alt_logo' =>$this->hasChangedImage('site_alt_logo')  ? 'required|mimes:jpeg,png|max:3072': '',
        ];
    }

    public function validationAttributes() {
        return [
            'settings_form.site_logo' => 'site logo',
            'settings_form.site_favicon' => 'site favicon',
            'settings_form.site_alt_logo' => 'site alt logo',
        ];
    }

    public function mount() {
        $settings = Setting::find(1);
        $this->settings_form->set($settings); 
    }

    public function update() {
        $this->validate();

        if($this->settings_form->site_logo != $this->settings->site_logo) {
            $this->settings_form->site_logo = '/storage/'.$this->settings_form->site_logo->store('site_logos', 'public');
        }

        if($this->settings_form->site_favicon!=$this->settings->site_favicon) {
            $this->settings_form->site_favicon = '/storage/'.$this->settings_form->site_favicon->store('site_logos', 'public');
        }

        if($this->settings_form->site_alt_logo!=$this->settings->site_alt_logo) {
            $this->settings_form->site_alt_logo = '/storage/'.$this->settings_form->site_alt_logo->store('site_logos', 'public');
        }

        $this->settings->update($this->settings_form->all());
        $this->dispatch('settings-updated', 'Settings updated successfully.');
    }

}
