<?php

namespace App\Http\Livewire;

use App\Models\EducationalLevel;
use App\Models\FamilyUser;
use App\Models\PublicHealthEntity;
use Livewire\Component;
use Livewire\WithFileUploads;

class CV_FamilyUserController extends Component
{
public $componentName, $selected_NF_id, $type, $first_name, $last_name, $document_type, $document;
public $birth_date, $education_level, $occupation, $phone, $eps_id, $support_document, $support_document_view;
public $activeButtonSaveUpdate;

    use WithFileUploads;

    public function mount($user_sel_id, $activeButtonSaveUpdate)
    {
        $this->user_sel_id = $user_sel_id;
        $this->componentName = 'Núcleo Familiar';
        $this->activeButtonSaveUpdate = $activeButtonSaveUpdate;
    }

    public function render()
    {
        $members = FamilyUser::all();
        $epss = PublicHealthEntity::all();
        $education_levels = EducationalLevel::all();
        return view('livewire.cv-employee.detail.partials.family.component', compact('members', 'epss' , 'education_levels'));

    }

    public function resetUI()
    {
        $this->type = '';
        $this->first_name = '';
        $this->last_name = '';
        $this->document_type = '';
        $this->document = '';
        $this->birth_date = '';
        $this->education_level = '';
        $this->occupation = '';
        $this->phone = '';
        $this->eps_id = '';
        $this->support_document = '';
        $this->resetValidation();
    }
    public function openAddNF()
    {
        if (EmployeeOtherCompany($this->user_sel_id, true)[0] == NULL)
        {
            $this->emit('item-error-NF', EmployeeOtherCompany($this->user_sel_id, true)[1]);
            return false;
        }
        $this->selected_NF_id = 0;
        $this->emit('show-modal-NF','Abrir Modal');
    }
    public function StoreNF()
    {
        if (EmployeeOtherCompany($this->user_sel_id, true)[0] == NULL)
        {
            $this->emit('item-error-NF', EmployeeOtherCompany($this->user_sel_id, true)[1]);
            return false;
        }
        $rules = [
            'type' => 'required',
            'first_name' => 'required|max:99',
            'last_name' => 'required|max:99',
            'document_type' => 'required',
            'document' => 'required|max:15|unique:family_users,document,NULL,id,user_id,'.$this->user_sel_id,
            'birth_date' => 'required|date',
            'support_document' => 'required',

        ];

        $messages = [
            'type.required' => 'El campo Tipo es obligatorio',
            'first_name.required' => 'El campo Nombre es obligatorio',
            'first_name.max' => 'El campo Nombre debe contener máximo 99 caracteres',
            'last_name.required' => 'El campo Apellido es obligatorio',
            'last_name.max' => 'El campo Apellido debe contener máximo 99 caracteres',
            'document_type.required' => 'El campo Tipo de Documento es obligatorio',
            'document.required' => 'El campo Documento es obligatorio',
            'document.max' => 'El campo Documento debe contener máximo 15 caracteres',
            'document.unique' => 'El número de documento ya ha sido registrado',
            'birth_date.required' => 'El campo Fecha de Nacimiento es obligatorio',
            'birth_date.date' => 'El campo Fecha de Nacimiento debe contener una fecha válida',
            'support_document.required' => 'El campo Documento de Soporte es obligatorio',
        ];

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

        $familyUser = FamilyUser::create([
            'user_id' => $this->user_sel_id,
            'type' => $this->type,
            'first_name' => $this->first_name,
            'last_name' => $this->last_name,
            'document_type' => $this->document_type,
            'document' => $this->document,
            'birth_date' => $this->birth_date,
            'education_level' => $this->education_level,
            'occupation' => $this->occupation,
            'phone' => $this->phone,
            'eps_id' => $this->eps_id,

        ]);

        if ($this->support_document) {
            $customFileName = uniqid(time(), false).'.'.$this->support_document->extension();
            $this->support_document->storeAs('public/users/'.$this->user_sel_id.'/family_users', $customFileName);
            $familyUser->support_document = $customFileName;
            $familyUser->save();
        }
        $this->resetUI();
        $this->emit('item-added-NF', 'Familiar agregado');
    }

    public function EditNF(FamilyUser $familyUser)
    {
        if (EmployeeOtherCompany($this->user_sel_id, true)[0] == NULL)
        {
            $this->emit('item-error-NF', EmployeeOtherCompany($this->user_sel_id, true)[1]);
            return false;
        }
        $this->selected_NF_id = $familyUser->id;
        $this->type = $familyUser->type;
        $this->first_name = $familyUser->first_name;
        $this->last_name = $familyUser->last_name;
        $this->document_type = $familyUser->document_type;
        $this->document = $familyUser->document;
        $this->birth_date = $familyUser->birth_date;
        $this->education_level = $familyUser->education_level;
        $this->occupation = $familyUser->occupation;
        $this->phone = $familyUser->phone;
        $this->eps_id = $familyUser->eps_id;

        $this->support_document_view = $familyUser->support_document;
        $this->emit('show-modal-NF','Abrir Modal');
    }

    public function UpdateNF()
    {
        if (EmployeeOtherCompany($this->user_sel_id, true)[0] == NULL)
        {
            $this->emit('item-error-NF', EmployeeOtherCompany($this->user_sel_id, true)[1]);
            return false;
        }
        $rules = [
            'type' => 'required',
            'first_name' => 'required|max:99',
            'last_name' => 'required|max:99',
            'document_type' => 'required',
            'document' => 'required|max:15|unique:family_users,document,'.$this->selected_NF_id.',id,user_id,'.$this->user_sel_id,
            'birth_date' => 'required|date',
        ];

        $messages = [
            'type.required' => 'El campo Tipo es obligatorio',
            'first_name.required' => 'El campo Nombre es obligatorio',
            'first_name.max' => 'El campo Nombre debe contener máximo 99 caracteres',
            'last_name.required' => 'El campo Apellido es obligatorio',
            'last_name.max' => 'El campo Apellido debe contener máximo 99 caracteres',
            'document_type.required' => 'El campo Tipo de Documento es obligatorio',
            'document.required' => 'El campo Documento es obligatorio',
            'document.max' => 'El campo Documento debe contener máximo 15 caracteres',
            'document.unique' => 'El número de documento ya ha sido registrado',
            'birth_date.required' => 'El campo Fecha de Nacimiento es obligatorio',
            'birth_date.date' => 'El campo Fecha de Nacimiento debe contener una fecha válida',
        ];

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

        $familyUser = FamilyUser::find($this->selected_NF_id);

        $familyUser->update([
            'type' => $this->type,
            'first_name' => $this->first_name,
            'last_name' => $this->last_name,
            'document_type' => $this->document_type,
            'document' => $this->document,
            'birth_date' => $this->birth_date,
            'education_level' => $this->education_level,
            'occupation' => $this->occupation,
            'phone' => $this->phone,
            'eps_id' => $this->eps_id,
            'support_document' => $this->support_document,
        ]);

        if ($this->support_document) {
            $customFileName = uniqid(time(), false).'.'.$this->support_document->extension();
            $this->support_document->storeAs('public/users/'.$this->user_sel_id.'/family_users', $customFileName);
            $supportName = $familyUser->support_document; //nombre de la imagen actual guardada en la base de datos

            $familyUser->support_document = $customFileName; //asignamos el nuevo nombre de la imagen
            $familyUser->save();

            if ($supportName != null)//si la consulta devuelve el nombre de una imagen
            {
                if(file_exists('storage/users/'.$this->user_sel_id.'/family_users/'.$supportName))
                {
                    unlink('storage/users/'.$this->user_sel_id.'/family_users/'.$supportName);
                }
            }
        }

        $this->resetUI();
        $this->emit('item-added-NF', 'Familiar actualizado');

    }
    protected $listeners = ['deleteRowNF' => 'DestroyNF'];

    public function DestroyNF(FamilyUser $familyUser)
    {
        if (EmployeeOtherCompany($this->user_sel_id, true)[0] == NULL)
        {
            $this->emit('item-error-NF', EmployeeOtherCompany($this->user_sel_id, true)[1]);
            return false;
        }
        $support_document = $familyUser->support_document;
        if ($support_document != null)//si la consulta devuelve el nombre de un archivo
        {
            if(file_exists('storage/family_users/'.$support_document))
            {
                unlink('storage/family_users/'.$support_document);
            }
        }
        $familyUser->delete();
        $this->emit('item-deleted-NF', 'Se eliminó el registro del familiar correctamente');
    }


}
