<?php

namespace App\Http\Livewire;

use App\Models\City;
use App\Models\Company;
use App\Models\PublicHealthEntity;
use App\Models\State;
use App\Models\User;
use App\Traits\OrderByTable;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Livewire\WithFileUploads;

class CvEmployeeDetailsController extends Component
{
    use WithFileUploads;
    use OrderByTable;

    public $first_name, $last_name, $document_type, $document, $gender_user, $civil_status, $nationality, $address, $imageName, $image;
    public $phone, $city_residence, $state_residence, $professional_profile, $title_position, $professional_license;
    public $social_facebook, $social_linkedin, $social_instagram, $social_twitter;
    public $cities, $states, $epss, $eps_id;
    public $search, $user_id, $pageTitle, $componentName, $customFileName, $count_reg;
    public $employee_update_time, $opc_update_cv, $profile_employee;
    public $selectedState, $breadcrumb_show = true;

    protected $listeners = [
        'resetUI' => 'resetUI'
    ];

    public function mount($id,$breadcrumb_show=true)
    {
        $user_auth = auth()->user();
        $roleUser = $user_auth->getRoleNames()[0];
        if ($roleUser == 'Empleado'){
            UserAuthPermission('CvEmployee_detail_index');
            $this->user_id = $user_auth->id;
            $this->pageTitle = $user_auth->first_name . ' ' . $user_auth->last_name;
            $this->componentName = 'Empleado';
            $company = Company::find(Auth::user()->CompanyId());
            $this->company_id = $company->id;
            $this->profile_employee = $company->users()->wherePivot('user_id', $this->user_id)->get()->first();

            if ($this->profile_employee->pivot->initial_date_cv == null){
                $company->users()->updateExistingPivot($this->user_id, ['initial_date_cv' => Carbon::now()]);
                $this->updateDateCv(true);
            }
            else{
                if (getDifferenceDateWithDays($this->profile_employee->pivot->initial_date_cv, $company->company_employee_update_time)['status'] == '0'){
                    $this->updateDateCv(false);
                }
                else{
                    $this->updateDateCv(true);
                }
            }
            //$company->users()->updateExistingPivot($this->user_id, ['initial_date_cv' => Carbon::now()->subDays($company->company_employee_update_time)]);
        }
        else{
            UserAuthPermission('CvEmployee_index');
            EmployeeOtherCompany($id);
            $this->user_id = $id;
            $this->pageTitle = 'Hoja de Vida';
            $this->componentName = 'Empleado';
        }


        $this->states = State::all();
        $this->cities = collect();
        $this->epss = PublicHealthEntity::all();
        $this->selectedState = NULL;
        $user = User::find($this->user_id);
        $this->document_type = $user->document_type;
        $this->document = $user->document;
        $this->first_name = $user->first_name;
        $this->last_name = $user->last_name;
        $this->gender_user = $user->gender_user;
        $this->email = $user->email;
        $this->phone = $user->phone;
        $this->civil_status = $user->civil_status;
        $this->nationality = $user->nationality;
        $this->birth_date = $user->birth_date;
        $this->birth_place = $user->birth_place;
        $this->address = $user->address;

        $this->city_residence = $user->city_residence;
        $this->state_residence = $user->state_residence;
        $this->selectedState = $user->state_residence;
        $this->updatedSelectedState($this->selectedState);
        $this->eps_id = $user->eps_id;

        $this->title_position = $user->title_position;
        $this->professional_license = $user->professional_license;
        $this->professional_profile = $user->professional_profile;
        $this->social_facebook = $user->social_facebook;
        $this->social_linkedin = $user->social_linkedin;
        $this->social_instagram = $user->social_instagram;
        $this->social_twitter = $user->social_twitter;
        $this->breadcrumb_show = $breadcrumb_show;

    }

    public function render()
    {
        //dd($this->opc_update_cv);
        $user = User::find($this->user_id);
        return view('livewire.cv-employee.detail.component',compact('user'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function updateDateCv($opc)
    {
        $this->employee_update_time = getDifferenceDateWithDays($this->profile_employee->pivot->initial_date_cv, $this->company_id)['difference'];
        $this->opc_update_cv = $opc;
    }

    public function activeButtonSaveUpdate()
    {
        $user_auth = auth()->user();
        $roleUser = $user_auth->getRoleNames()[0];
        if ($roleUser == 'Empleado'){
            if ($this->opc_update_cv == true){
                return true;
            }
            else{
                return false;
            }
        }
        else{
            return true;
        }
    }

    public function updatedSelectedState($state)
    {
        if (!is_null($state)) {
            $this->cities = City::where('state_code', $state)->get();
        }
    }

    public function Update()
    {
        if (EmployeeOtherCompany($this->user_id, true)[0] == NULL)
        {
            $this->emit('item-error', EmployeeOtherCompany($this->user_id, true)[1]);
            return false;
        }
        $rules = [
            'first_name' => 'required|min:3|max:99',
            'last_name' => 'required|min:3|max:99',
            'phone' => "required|unique:users,phone,{$this->user_id}|min:7max:15",
            'document_type' => 'required|not_in:Seleccionar',
            'document' => "required|unique:users,document,{$this->user_id}|min:7|max:15",
            'gender_user' => 'required',
            'email' => "required||email|unique:users,email,{$this->user_id}|max:99",
            'civil_status' => 'required|not_in:Seleccionar',
            'nationality' => 'required|min:3|max:50',
            'birth_date' => 'required|date',
            'birth_place' => 'required|min:3',
            'address' => 'required|min:3',
            'city_residence' => 'required|not_in:Seleccionar',
            'selectedState' => 'required|not_in:Seleccionar',
            'eps_id' => 'required',
            'title_position' => 'required|max:99',
            'professional_profile' => 'required'
        ];

        $messages = [
            'first_name.required' => 'Ingresa el Nombre',
            'first_name.min' => 'El Nombre debe tener como mínimo 3 caracteres',
            'first_name.max' => 'El Nombre debe tener como máximo 99 caracteres',
            'last_name.required' => 'Ingresa el Apellido',
            'last_name.min' => 'El Apellido debe tener como mínimo 3 caracteres',
            'last_name.max' => 'El Apellido debe tener como máximo 99 caracteres',
            'phone.required' => 'Ingresa el número de documento',
            'phone.min' => 'El Teléfono debe tener como mínimo 7 caracteres',
            'phone.max' => 'El Teléfono debe tener máximo 15 caracteres',
            'document_type.required' => 'Selecciona el tipo de documento',
            'document_type.not_in' => 'Selecciona un tipo de documento diferente a Seleccionar',
            'document.required' => 'Ingresa el número de documento',
            'document.min' => 'El Documento debe tener como mínimo 7 caracteres',
            'document.max' => 'El Documento debe tener máximo 15 caracteres',
            'gender_user.required' => 'Seleccione el género',
            'email.required' => 'Ingresa un Correo electrónico',
            'email.email' => 'Ingresa un Correo electrónico valido',
            'email.unique' => 'El Correo electrónico ya esta registrado',
            'email.max' => 'El Correo electrónico debe tener como máximo 99 caracteres',
            'civil_status.required' => 'Selecciona el estado civil',
            'civil_status.not_in' => 'Selecciona un estado civil diferente a Seleccionar',
            'nationality.required' => 'Ingresa la nacionalidad',
            'nationality.min' => 'La nacionalidad debe tener como mínimo 3 caracteres',
            'nationality.max' => 'La nacionalidad debe tener como máximo 50 caracteres',
            'birth_date.required' => 'Ingresa la fecha de nacimiento',
            'birth_date.date' => 'Ingresa una fecha valida',
            'birth_place.required' => 'Ingresa el lugar de nacimiento',
            'birth_place.min' => 'El lugar de nacimiento debe tener como mínimo 3 caracteres',
            'address.required' => 'Ingresa la dirección',
            'address.min' => 'La dirección debe tener como mínimo 3 caracteres',
            'city_residence.required' => 'Selecciona la ciudad de residencia',
            'city_residence.not_in' => 'Selecciona una ciudad diferente a Seleccionar',
            'selectedState.required' => 'Selecciona el departamento de residencia',
            'selectedState.not_in' => 'Selecciona un departamento diferente a Seleccionar',
            'eps_id.required' => 'Selecciona la EPS',
            'professional_profile.required' => 'Ingresa el perfil profesional',
            'title_position.required' => 'Ingresa el Cargo / titulo professional',
            'title_position.max' => 'El Cargo / titulo professional debe tener como máximo 99 caracteres',

        ];

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

        $user = User::find($this->user_id);
        $user->update([
            'first_name' => $this->first_name,
            'last_name' => $this->last_name,
            'phone' => $this->phone,
            'email' => $this->email,
            'document_type' => $this->document_type,
            'document' => $this->document,
            'gender_user' => $this->gender_user,
            'civil_status' => $this->civil_status,
            'nationality' => $this->nationality,
            'birth_date' => Carbon::parse($this->birth_date)->format('Y-m-d'),
            'birth_place' => $this->birth_place,
            'address' => $this->address,
            'state_residence' => $this->selectedState,
            'city_residence' => $this->city_residence,
            'eps_id' => $this->eps_id,
            'title_position' => $this->title_position,
            'professional_license' => $this->professional_license,
            'professional_profile' => $this->professional_profile,
            'social_linkedin' => $this->social_linkedin,
            'social_facebook' => $this->social_facebook,
            'social_twitter' => $this->social_twitter,
            'social_instagram' => $this->social_instagram,
        ]);

        if($this->image)
        {
            $customFileName = uniqid(). '.' . $this->image->extension();
            $this->image->storeAs('public/users/'.$user->id.'/',$customFileName);
            $imageName = $user->image; //nombre de la imagen actual guardada en la base de datos

            $user->image = $customFileName; //asignamos el nuevo nombre de la imagen
            $user->save();
            //debug($imageName);
            if ($imageName != null)//si la consulta devuelve el nombre de una imagen
            {
                if(file_exists('storage/users/'.$user->id.'/'. $imageName))//verificamos que la imagen exista fisicamente
                {
                    unlink('storage/users/'.$user->id.'/' . $imageName); //eliminamos la imagen
                }
            }
        }

        $this->resetUI();
        $this->emit('item-updated', 'Hoja de Vida Actualizada');
    }

    public function resetUI()
    {
        $this->resetValidation();
    }

}
