<?php

namespace App\Http\Livewire;

use App\Models\Company;
use App\Models\Contract;
use App\Models\JobPosition;
use App\Models\PublicHealthEntity;
use App\Models\User;
use App\Traits\OrderByTable;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
use Livewire\WithPagination;

class Company_EmployeesController extends Component
{
    use WithPagination;
    use OrderByTable;

    public $search, $company_id, $selected_user_id, $pageTitle, $componentName, $user_id, $search_modal, $count_reg_modal, $status_contract, $type_contract, $sub_type_contract;
    public $selectedCompany, $company_employee_update_time, $value_update_time;
    public $company_name, $company_plan_name, $company_plan_id;
    public $first_name, $last_name, $document, $phone, $email, $status, $password, $image, $selected_id, $fileLoaded;
    public $title_position, $salary, $payment_method, $start_date_work, $end_date_work, $place_hired, $place_work, $work_day, $eps_id, $expiration_contract, $contract_modality;
    public $breadcrumb_show=true;

    private $pagination = 10;
    private $pagination_modal = 5;

    protected $paginationTheme = 'bootstrap';

    public function updatingSearch(){
        $this->emit('show-modal', 'modal-contract');
    }

    public function mount()
    {
        UserAuthPermission('Company_employees_index');
        $this->company_id = Company::find(Auth::user()->CompanyId())->id;
        $company = Company::find(Auth::user()->CompanyId());
        $this->pageTitle = 'Empleados';
        $this->componentName = 'Empresa';
        $this->company_name = $company->name;
        $this->company_plan_name = $company->plan->name;
        $this->company_plan_id = $company->plan->id;
        $this->company_employee_update_time = $company->company_employee_update_time;
    }

    public function render()
    {
        if (strlen($this->search) > 0)
            {

                $users= User::role('Empleado')
                            ->join('company_user', 'users.id', '=', 'company_user.user_id')
                            ->join('companies', 'company_user.company_id', '=', 'companies.id')
                            ->select('users.*','companies.name as company_name', 'company_user.job_position_id')
                            ->where('companies.id', Auth::user()->CompanyId())
                            ->where(function ($query) {
                            $query->where('first_name', 'like', '%' . $this->search . '%')
                                    ->orWhere('last_name', 'like', '%' . $this->search . '%')
                                    ->orWhere('document', 'like', '%' . $this->search . '%');
                            })
                            ->orderBy($this->sortBy, $this->sortDirection)->paginate($this->pagination);
            }
            else
            {
                $users= User::role('Empleado')
                            ->join('company_user', 'users.id', '=', 'company_user.user_id')
                            ->join('companies', 'company_user.company_id', '=', 'companies.id')
                            ->where('companies.id', Auth::user()->CompanyId())
                            ->select('users.*','companies.name as company_name', 'company_user.job_position_id')
                            ->orderBy($this->sortBy, $this->sortDirection)
                            ->paginate($this->pagination);
            }
        $this->count_reg = $users->total();
        $epss = PublicHealthEntity::all();
        $jobs_positions_company = JobPosition::where('company_id', $this->company_id)->get();
        return view('livewire.company.employee.component',compact('users', 'epss', 'jobs_positions_company'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function resetUI()
    {
        $this->roleModal = '';
        $this->first_name = '';
        $this->last_name = '';
        $this->document = '';
        $this->phone = '';
        $this->email = '';
        $this->password = '';
        $this->image = '';
        $this->search = '';
        $this->status ='';
        $this->selected_user_id = 0;
        $this->resetValidation();
        $this->resetPage();
    }

    public function OpenUpdateTime()
    {
        $this->selected_id = $this->company_id;
        $this->value_update_time = $this->company_employee_update_time;
        $this->emit('show-modal-time', 'modal-update-time');
    }

    public function UpdateTime()
    {
        $company = Company::find($this->selected_id);

        if ($this->value_update_time < 1) $this->value_update_time = 1; //Valor mínimo de 1 día

        $company->update([
            'company_employee_update_time' => $this->value_update_time,
        ]);

        $this->company_employee_update_time = $this->value_update_time;
        $this->emit('hide-modal-time', 'modal-update-time');
    }
    public function jobPositionName($id)
    {
        $jobPosition = DB::table('job_positions')
            ->where('id', $id)
            ->get()->first();
        return $jobPosition->name;
    }

    public function openAdd()
    {
        $useractions = UserAuthPermissionActions('Company_employee_create');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $this->user_id = '';
        $this->emit('show-modal', 'Agregar Empleado');
    }

    public function Store()
    {
        $useractions = UserAuthPermissionActions('Company_employee_create');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $rules = [
            'first_name' => 'required|min:3',
            'last_name' => 'required|min:3',
            'phone' => 'required|unique:users|min:7|max:10',
            'document' => 'required|unique:users|min:7|max:15',
            'email' => 'required|unique:users|email',
            'status' => 'required|not_in:Seleccionar',
            'password' => 'required|min:6'
        ];

        $messages = [
            'first_name.required' => 'Ingresa el Nombre',
            'first_name.min' => 'El Nombre debe tener como mínimo 3 caracteres',
            'last_name.required' => 'Ingresa el Apellido',
            'last_name.min' => 'El Apellido debe tener como mínimo 3 caracteres',
            'phone.required' => 'Ingresa el número de documento',
            'phone.min' => 'El Teléfono debe tener como mínimo 6 caracteres',
            'phone.max' => 'El Teléfono debe tener máximo 10 caracteres',
            'document.required' => 'Ingresa el número de documento',
            'document.min' => 'El Documento debe tener como mínimo 6 caracteres',
            'document.max' => 'El Documento debe tener máximo 15 caracteres',
            'document.unique' => 'El Número de documento ya esta registrado',
            'email.required' => 'Ingresa un Correo electrónico',
            'email.email' => 'Ingresa un Correo electrónico valido',
            'email.unique' => 'El Correo electrónico ya esta registrado',
            'status.required' => 'Seleccione el Estado para el Usuario',
            'status.not_in' => 'Seleccione un Estado de Usuario diferente a "Seleccionar"',
            'password.required' => 'La Contraseña es requerida',
            'password.min' => 'La Contraseña debe tener mínimo 3 caracteres'
        ];

        $this->validate($rules, $messages);

        $user = User::create([
            'first_name' => $this->first_name,
            'last_name' => $this->last_name,
            'phone' => $this->phone,
            'email' => $this->email,
            'document' => $this->document,
            'status' => $this->status,
            'password' => bcrypt($this->password)
        ]);

        $user->syncRoles('Empleado');

        $company = Company::find($this->company_id);
        $company->users()->attach($user->id);

        if($this->image)
        {
            $customFileName = uniqid(time(), false).'.'.$this->image->extension();
            $this->image->storeAs('public/users', $customFileName);
            $user->image = $customFileName;
            $user->save();
        }

        $this->resetUI();
        $this->emit('item-added', 'Usuario registrado');

    }

    protected $listeners = [
        'deleteRow' => 'Destroy',
        'resetUI' => 'resetUI'
    ];

    public function Destroy(User $user)
    {
        $useractions = UserAuthPermissionActions('Company_employee_delete');

        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        if (EmployeeOtherCompany($user->id, true)[0] == NULL)
        {
            $this->emit('item-error', EmployeeOtherCompany($user->id, true)[1]);
            return false;
        }

        if ($user)
        {
            $contracts_user = DB::table('history_contracts_users')->where('user_id',$user->id)->count();
            if ($contracts_user > 0)
            {
                $this->emit('item-error', 'El usuario tiene contratos asociados');
            }
            else{
                $imageName = $user->image; //nombre de la imagen actual guardada en la base de datos
                if ($imageName != null)//si la consulta devuelve el nombre de una imagen
                {
                    if(file_exists('storage/users/'. $imageName))//verificamos que la imagen exista fisicamente
                    {
                        unlink('storage/users/' . $imageName); //eliminamos la imagen
                    }
                }
                $user->delete();
                $company = Company::find($this->company_id);
                $company->users()->detach($user->id);
                $this->resetUI();
                $this->emit('item-deleted', 'Usuario eliminado');
            }
        }
    }

    public function ToggleStatusEmployee($id)
    {
        $useractions = UserAuthPermissionActions('Company_employee_update');

        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $user = User::find($id);
        $user->status = $user->status == 'ACTIVO' ? 'INACTIVO' : 'ACTIVO';
        $user->save();
    }
}
