<?php

namespace App\Http\Livewire;

use App\Models\Setting;
use Livewire\Component;

class SettingsController extends Component
{
    public $pageTitle, $componentName;
    public $minimum_salary, $transportation_allowance;
    public $breadcrumb_show = true;

    public function mount()
    {
        UserAuthPermission('Settings_index');
        $this->pageTitle = 'Ajustes';
        $this->componentName = 'Administración';
        $settings = Setting::first();
        $this->minimum_salary = number_format($settings->minimum_salary, 2, '.', ',');
        $this->transportation_allowance = number_format($settings->transportation_allowance, 2, '.', ',');
    }

    public function render()
    {
        return view('livewire.settings.component')
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function Update()
    {
        $useractions = UserAuthPermissionActions('Settings_update');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }

        $this->minimum_salary = (float) str_replace(',', '', $this->minimum_salary); // quitar punto y coma de data-currency en el input
        $this->transportation_allowance = (float) str_replace(',', '', $this->transportation_allowance); // quitar punto y coma de data-currency en el input
        $rules = [
            'minimum_salary' => 'required|numeric|max:99999999',
            'transportation_allowance' => 'required|numeric|max:99999999',
        ];

        $messages = [
            'minimum_salary.required' => 'El salario mínimo es requerido',
            'minimum_salary.numeric' => 'El salario mínimo debe ser un número',
            'transportation_allowance.required' => 'El transporte es requerido',
            'transportation_allowance.numeric' => 'El transporte debe ser un número',
        ];

        $this->validate($rules, $messages);
        $settings = Setting::first();
        $settings->update([
            'minimum_salary' => $this->minimum_salary,
            'transportation_allowance' => $this->transportation_allowance,
        ]);

        $this->minimum_salary = number_format($settings->minimum_salary, 2, '.', ',');
        $this->transportation_allowance = number_format($settings->transportation_allowance, 2, '.', ',');

        $this->emit('item-updated', 'Parámetros actualizados');
    }

}
