<?php

namespace App\Http\Livewire;

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

class CompaniesUsersController extends Component
{
    use WithPagination;
    use OrderByTable;
    use QuotaRolesCompany;

    public $search, $selected_id, $pageTitle, $componentName, $user_id, $search_modal, $users_modal;
    public $roleModal, $selectedCompany, $modalName;
    public $company_name, $company_plan_name;
    public $first_name, $last_name;
    public $title_position, $salary, $payment_method, $start_date_work, $end_date_work, $place_hired, $place_work, $work_day, $eps_id;
    public $breadcrumb_show = true;

    private $pagination = 10;
    public $limit_users = 25;

    protected $paginationTheme = 'bootstrap';

    public function mount($id)
    {
        $this->selected_id = $id;
        $this->pageTitle = 'Listado';
        $this->componentName = 'Empresas';
        $this->selectedState = 0;
        $this->users_modal = User::all();
        $this->roleModal = '';

        $this->setCompanyId($id);// obtiene el id de la empresa para usarlo en los métodos de la clase QuotaRolesCompany
        $this->roles_company_allowed();//función trait QuotaRolesCompany
        $this->company_name = Company::find($id)->name;
        $this->company_plan_name = Company::find($id)->plan->name;
    }

    public function render()
    {
        $epss = PublicHealthEntity::all();
        if (strlen($this->search) > 0)
            $users = Company::find($this->selected_id)
                            ->users()->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 = Company::find($this->selected_id)
                            ->users()->orderBy($this->sortBy, $this->sortDirection)
                            ->paginate($this->pagination);

        $this->count_reg = $users->total();

        //buscar los usuarios de la empresa en la ventana modal
        //$this->roleModal='Empleado';
        if (strlen($this->search_modal) > 0)
            $this->users_modal = User::whereHas('roles', function ($query) { // todos los roles menos SuperAdmin y Soporte
                                        $query->where('name','!=', 'Super Admin')
                                            ->where('name','!=', 'Soporte');
                                    })
                                    ->where(function ($query) {
                                        $query->where('first_name', 'like', '%' . $this->search_modal . '%')
                                            ->orWhere('last_name', 'like', '%' . $this->search_modal . '%')
                                            ->orWhere('document', 'like', '%' . $this->search_modal . '%');
                                    })
                                    ->whereNotExists(function ($query) {
                                        $query->select(DB::raw(1))
                                            ->from('company_user')
                                            ->whereRaw('company_user.user_id = users.id');

                                    })
                                    ->where(function ($query) {
                                        if ($this->roleModal != '') {
                                            $query->role($this->roleModal);
                                        }
                                    })
                                    ->orderBy($this->sortBy, $this->sortDirection)
                                    ->take($this->limit_users)
                                    ->get();
        else
            $this->users_modal = User::whereHas('roles', function ($query) { // todos los roles menos SuperAdmin y Soporte
                                        $query->where('name','!=', 'Super Admin')
                                            ->where('name','!=', 'Soporte');
                                    })
                                    ->where(function ($query) {
                                        if ($this->roleModal != '') {
                                            $query->role($this->roleModal);
                                        }
                                    })
                                    ->orderBy($this->sortBy, $this->sortDirection)
                                    ->whereNotExists(function ($query) {
                                        $query->select(DB::raw(1))
                                            ->from('company_user')
                                            ->whereRaw('company_user.user_id = users.id');
                                    })
                                    ->take($this->limit_users)
                                    ->get();


        return view('livewire.companies.users.component',compact('users', 'epss'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }


    public function openAddUser()
    {
        $this->user_id = '';
        $this->roles_company_allowed();
        $this->emit('show-modal', 'addUser');
    }

    public function resetUI()
    {
        $this->search_modal = '';
        $this->selected_id_user = 0;
        $this->roleModal = 'Empleado';
    }

    public function AddUserCompany(User $user)
    {
        $company = Company::find($this->selected_id);
        $userReg = DB::table('company_user')->where('user_id', $user->id)->get()->first();
        if ($userReg != NULL)
        {
            $this->emit('item-error', 'El usuario ya se encuentra registrado en una empresa');
            return false;
        }
        $user = User::find($user->id);
        $roleUser = $user->getRoleNames()[0]; //
        $quota_role=$this->role_quota_max($roleUser);//método trait QuotaRolesCompany
        if ($quota_role <= 0){
            $this->emit('item-error', 'El rol seleccionado ya tiene una cuota máxima de usuarios registrados');
            return false;
        }
        $company->users()->attach($user->id);
        $this->roles_company_allowed();
        $this->emit('item-added', 'Usuario Agregado correctamente');
    }

    public function removeUserCompany(User $user)
    {
        $company = Company::find($this->selected_id);
        $company->users()->detach($user->id);
        $this->roles_company_allowed();
        $this->emit('item-deleted', 'Usuario Eliminado correctamente');
    }

    public function openProfile(User $user)
    {
        $this->user_id = $user->id;
        $user = User::find($this->user_id);
        $this->first_name = $user->first_name;
        $this->last_name = $user->last_name;
        $company = Company::find($this->selected_id)->users()->wherePivot('user_id', $this->user_id)->get()->first();
        debug($this->user_id);
        debug($company->pivot->title_position);
        $this->title_position = $company->pivot->title_position;
        $this->salary = $company->pivot->salary;
        $this->payment_method = $company->pivot->payment_method;
        $this->start_date_work = $company->pivot->start_date_work;
        $this->end_date_work = $company->pivot->end_date_work;
        $this->place_hired = $company->pivot->place_hired;
        $this->place_work = $company->pivot->place_work;
        $this->work_day = $company->pivot->work_day;
        $this->eps_id = $company->pivot->eps_id;
        $this->emit('show-modal-profile', 'profile');
    }

    public function storeProfile(){
        $company = Company::find($this->selected_id);
        $rules = [
            'title_position' => 'required|max:99',
            'salary' => 'required',
            'payment_method' => 'required',
            'start_date_work' => 'required|date',
            'end_date_work' => 'required|date|after:start_date_work',
            'place_hired' => 'required|max:99',
            'place_work' => 'required|max:99',
            'work_day' => 'required',
            'eps_id' => 'required',
        ];
        $messages = [
            'title_position.required' => 'El campo "Cargo u Oficio" es obligatorio',
            'title_position.max' => 'El campo "Cargo u Oficio" no puede tener más de 99 caracteres',
            'salary.required' => 'El campo "Salario" es obligatorio',
            'payment_method.required' => 'El campo "Forma de Pago" es obligatorio',
            'start_date_work.required' => 'El campo "Fecha de Inicio de Labores" es obligatorio',
            'start_date_work.date' => 'El campo "Fecha de Inicio de Labores" debe ser una fecha',
            'end_date_work.required' => 'El campo "Fecha de Fin de Labores" es obligatorio',
            'end_date_work.date' => 'El campo "Fecha de Fin de Labores" debe ser una fecha',
            'end_date_work.after' => 'El campo "Fecha de Fin de Labores" debe ser mayor a la fecha de inicio de labores',
            'place_hired.required' => 'El campo "Lugar donde ha sido contratado" es obligatorio',
            'place_hired.max' => 'El campo "Lugar donde ha sido contratado" no puede tener más de 99 caracteres',
            'place_work.required' => 'El campo "Lugar donde desempeñará labores" es obligatorio',
            'place_work.max' => 'El campo "Lugar donde desempeñará labores" no puede tener más de 99 caracteres',
            'work_day.required' => 'El campo "Jornada laboral" es obligatorio',
            'eps_id.required' => 'El campo "EPS" es obligatorio',
        ];

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

        $company->users()->updateExistingPivot($this->user_id, [
            'title_position' => $this->title_position,
            'salary' => (float)str_replace(',', '', $this->salary),
            'payment_method' => $this->payment_method,
            'start_date_work' => $this->start_date_work,
            'end_date_work' => $this->end_date_work,
            'place_hired' => $this->place_hired,
            'place_work' => $this->place_work,
            'work_day' => $this->work_day,
            'eps_id' => $this->eps_id,
        ]);
        $this->emit('hide-modal-profile', 'Perfil actualizado correctamente');
    }
}
