<?php

namespace App\Http\Livewire;

use App\Models\AcademicFormation;
use App\Models\EducationalLevel;
use App\Traits\OrderByTable;
use Livewire\Component;
use Livewire\WithFileUploads;

class CV_AcademicFormationController extends Component
{
    use OrderByTable;
    use WithFileUploads;

    public $componentName, $selected_AF_id;
    public $institution_name, $educational_level, $educational_level_name, $modality, $study_area, $status, $initial_date_month, $initial_date_year;
    public $final_date_month, $final_date_year, $academic_formation_support, $professional_card_support;
    public $academic_formation_support_view, $professional_card_support_view;
    public $activeButtonSaveUpdate;

    public function mount($user_sel_id, $activeButtonSaveUpdate)
    {
        $this->user_sel_id = $user_sel_id;
        $this->componentName = 'Formación Académica';
        $this->activeButtonSaveUpdate = $activeButtonSaveUpdate;
    }

    public function render()
    {
        $educational_levels = EducationalLevel::all();
        $academic_formations = AcademicFormation::join('educational_levels', 'academic_formations.educational_level_id', '=', 'educational_levels.id')
            ->select('academic_formations.*', 'educational_levels.name as educational_level_name')
            ->where('academic_formations.user_id', $this->user_sel_id)
            ->orderBy('academic_formations.id', 'desc')
            ->get();
        return view('livewire.cv-employee.detail.partials.academic-formation.component', compact('educational_levels', 'academic_formations'));
    }

    public function openAddAF()
    {
        if (EmployeeOtherCompany($this->user_sel_id, true)[0] == NULL)
        {
            $this->emit('item-error-AF', EmployeeOtherCompany($this->user_sel_id, true)[1]);
            return false;
        }
        $this->selected_AF_id = 0;
        $this->resetUI();
        $this->emit('show-modal-AF','Abrir Modal');
    }

    public function resetUI()
    {
        $this->institution_name = '';
        $this->educational_level = '';
        $this->modality = '';
        $this->study_area = '';
        $this->status = '';
        $this->initial_date_month = '';
        $this->initial_date_year = '';
        $this->final_date_month = '';
        $this->final_date_year = '';
        $this->academic_formation_support = '';
        $this->professional_card_support = '';
        $this->resetValidation();
    }

    public function StoreAF()
    {
        if (EmployeeOtherCompany($this->user_sel_id, true)[0] == NULL)
        {
            $this->emit('item-error-AF', EmployeeOtherCompany($this->user_sel_id, true)[1]);
            return false;
        }
        $rules = [
            'institution_name' => 'required|max:99',
            'educational_level' => 'required|not_in:Seleccionar',
            'modality' => 'required|not_in:Seleccionar',
            'status' => 'required|not_in:Seleccionar',
            'study_area' => ['required_if:educational_level,==,4', 'required_if:educational_level,==,5', 'required_if:educational_level,==,6', 'required_if:educational_level,==,7', 'required_if:educational_level,==,8', 'required_if:educational_level,==,9', 'max:99'],
            'initial_date_month' => 'required|not_in:Seleccionar',
            'initial_date_year' => 'required|not_in:Seleccionar',
            'final_date_month' => ['required_if:status,==,1', 'required_if:status,==,3', 'not_in:Seleccionar'],
            'final_date_year' => ['required_if:status,==,1', 'required_if:status,==,3', 'not_in:Seleccionar'],

        ];

        $messages = [
            'institution_name.required' => 'El campo es obligatorio',
            'institution_name.max' => 'El campo debe tener máximo 99 caracteres',
            'educational_level.required' => 'El campo es obligatorio',
            'educational_level.not_in' => 'Selecciona un nivel educativo diferente a Seleccionar',
            'modality.required' => 'El campo es obligatorio',
            'modality.not_in' => 'Selecciona una modalidad diferente a Seleccionar',
            'status.required' => 'El campo es obligatorio',
            'status.not_in' => 'Selecciona un estado diferente a Seleccionar',
            'study_area.required_if' => 'El campo es obligatorio',
            'study_area.max' => 'El campo debe tener máximo 99 caracteres',
            'initial_date_month.required' => 'El campo es obligatorio',
            'initial_date_month.not_in' => 'Selecciona un mes diferente a Seleccionar',
            'initial_date_year.required' => 'El campo es obligatorio',
            'initial_date_year.not_in' => 'Selecciona un año diferente a Seleccionar',
            'final_date_month.required_if' => 'El campo es obligatorio',
            'final_date_month.not_in' => 'Selecciona un mes diferente a Seleccionar',
            'final_date_year.required_if' => 'El campo es obligatorio',
            'final_date_year.not_in' => 'Selecciona un año diferente a Seleccionar',

        ];

        $this->validate($rules, $messages);
        if($this->status != '1'){
            $this->final_date_month = $this->initial_date_month;
            $this->final_date_year = $this->initial_date_year;
        }
        $academic_formation = AcademicFormation::create([
            'user_id' => $this->user_sel_id,
            'institution_name' => $this->institution_name,
            'educational_level_id' => $this->educational_level,
            'modality' => $this->modality,
            'study_area' => $this->study_area,
            'status' => $this->status,
            'initial_date_month' => $this->initial_date_month,
            'initial_date_year' => $this->initial_date_year,
            'final_date_month' => $this->final_date_month,
            'final_date_year' => $this->final_date_year,
        ]);

        if($this->academic_formation_support)
        {
            $customFileName = uniqid(time(), false).'.'.$this->academic_formation_support->extension();
            $this->academic_formation_support->storeAs('public/users/'.$this->user_sel_id.'/academic_formation_supports', $customFileName);
            $academic_formation->academic_formation_support = $customFileName;
            $academic_formation->save();
        }
        if ($this->professional_card_support)
        {
            $customFileName = "professional_card_".uniqid(time(), false).'.'.$this->professional_card_support->extension();
            $this->professional_card_support->storeAs('public/users/'.$this->user_sel_id.'/academic_formation_supports', $customFileName);
            $academic_formation->professional_card_support = $customFileName;
            $academic_formation->save();
        }
        $this->resetUI();
        $this->emit('item-added-AF', 'Formación acádemica registrada');
    }


    public function EditAF(AcademicFormation $academic_formation)
    {
        if (EmployeeOtherCompany($this->user_sel_id, true)[0] == NULL)
        {
            $this->emit('item-error-AF', EmployeeOtherCompany($this->user_sel_id, true)[1]);
            return false;
        }
        $this->selected_AF_id = $academic_formation->id;
        $this->institution_name = $academic_formation->institution_name;
        $this->educational_level = $academic_formation->educational_level_id;
        $this->modality = $academic_formation->modality;
        $this->study_area = $academic_formation->study_area;
        $this->status = $academic_formation->status;
        $this->initial_date_month = $academic_formation->initial_date_month;
        $this->initial_date_year = $academic_formation->initial_date_year;
        $this->final_date_month = $academic_formation->final_date_month;
        $this->final_date_year = $academic_formation->final_date_year;
        $this->academic_formation_support_view = $academic_formation->academic_formation_support;
        $this->proffesional_card_support_view = $academic_formation->proffesional_card_support;
        $this->educational_level_name = $academic_formation->educational_level_name;
        $this->emit('show-modal-AF', 'Abrir Modal');
    }

    public function UpdateAF()
    {
        if (EmployeeOtherCompany($this->user_sel_id, true)[0] == NULL)
        {
            $this->emit('item-error-AF', EmployeeOtherCompany($this->user_sel_id, true)[1]);
            return false;
        }
        $rules = [
            'institution_name' => 'required|max:99',
            'educational_level' => 'required|not_in:Seleccionar',
            'modality' => 'required|not_in:Seleccionar',
            'status' => 'required|not_in:Seleccionar',
            'study_area' => ['required_if:educational_level,==,4', 'required_if:educational_level,==,5', 'required_if:educational_level,==,6', 'required_if:educational_level,==,7', 'required_if:educational_level,==,8', 'required_if:educational_level,==,9', 'max:99'],
            'initial_date_month' => 'required|not_in:Seleccionar',
            'initial_date_year' => 'required|not_in:Seleccionar',
            'final_date_month' => ['required_if:status,==,1', 'required_if:status,==,3', 'not_in:Seleccionar'],
            'final_date_year' => ['required_if:status,==,1', 'required_if:status,==,3', 'not_in:Seleccionar'],
        ];
        $messages = [
            'institution_name.required' => 'El campo es obligatorio',
            'institution_name.max' => 'El campo debe tener máximo 99 caracteres',
            'educational_level.required' => 'El campo es obligatorio',
            'educational_level.not_in' => 'Selecciona un nivel educativo diferente a Seleccionar',
            'modality.required' => 'El campo es obligatorio',
            'modality.not_in' => 'Selecciona una modalidad diferente a Seleccionar',
            'status.required' => 'El campo es obligatorio',
            'status.not_in' => 'Selecciona un estado diferente a Seleccionar',
            'study_area.required_if' => 'El campo es obligatorio',
            'study_area.max' => 'El campo debe tener máximo 99 caracteres',
            'initial_date_month.required' => 'El campo es obligatorio',
            'initial_date_month.not_in' => 'Selecciona un mes diferente a Seleccionar',
            'initial_date_year.required' => 'El campo es obligatorio',
            'initial_date_year.not_in' => 'Selecciona un año diferente a Seleccionar',
            'final_date_month.required' => 'El campo es obligatorio',
            'final_date_month.not_in' => 'Selecciona un mes diferente a Seleccionar',
            'final_date_year.required' => 'El campo es obligatorio',
            'final_date_year.not_in' => 'Selecciona un año diferente a Seleccionar',
        ];

        $this->validate($rules, $messages);
        $academic_formation = AcademicFormation::find($this->selected_AF_id);
        $academic_formation->update([
            'institution_name' => $this->institution_name,
            'educational_level_id' => $this->educational_level,
            'modality' => $this->modality,
            'study_area' => $this->study_area,
            'status' => $this->status,
            'initial_date_month' => $this->initial_date_month,
            'initial_date_year' => $this->initial_date_year,
            'final_date_month' => $this->final_date_month,
            'final_date_year' => $this->final_date_year,
        ]);

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

            $academic_formation->academic_formation_support = $customFileName; //asignamos el nuevo nombre de la imagen
            $academic_formation->save();
            //debug($supportName);
            if ($supportName != null)//si la consulta devuelve el nombre de una imagen
            {
                if(file_exists('storage/users/'.$this->user_sel_id.'/academic_formation_supports/'. $supportName))//verificamos que la imagen exista fisicamente
                {
                    unlink('storage/users/'.$this->user_sel_id.'/academic_formation_supports/' . $supportName); //eliminamos la imagen
                }
            }
        }

        if($this->professional_card_support)
        {
            $customFileName = "professional_card_".uniqid(time(), false). '.' . $this->professional_card_support->extension();
            $this->professional_card_support->storeAs('public/users/'.$this->user_sel_id.'/academic_formation_supports',$customFileName);
            $cardProName = $academic_formation->professional_card_support; //nombre del archivo actual guardado en la base de datos

            $academic_formation->professional_card_support = $customFileName; //asignamos el nuevo nombre del archivo
            $academic_formation->save();
            if ($cardProName != null)//si la consulta devuelve el nombre de una imagen
            {
                if(file_exists('storage/users/'.$this->user_sel_id.'/academic_formation_supports/'. $cardProName))//verificamos que el archivo exista fisicamente
                {
                    unlink('storage/users/'.$this->user_sel_id.'/academic_formation_supports/' . $cardProName); //eliminamos el archivo
                }
            }
        }

        $this->resetUI();
        $this->emit('item-updated-AF', 'Formación acádemica Actualizada');

    }

    protected $listeners = ['deleteRowAF' => 'DestroyAF'];

    public function DestroyAF(AcademicFormation $academic_formation)
    {
        if (EmployeeOtherCompany($this->user_sel_id, true)[0] == NULL)
        {
            $this->emit('item-error-AF', EmployeeOtherCompany($this->user_sel_id, true)[1]);
            return false;
        }
        $supportDocument = $academic_formation->academic_formation_support;
        $professionalCard = $academic_formation->professional_card_support;
        if ($supportDocument != null)//si la consulta devuelve el nombre del documento
        {
            if(file_exists('storage/users/'.$this->user_sel_id.'/academic_formation_supports/'. $supportDocument))//verificamos que el archivo exista fisicamente
            {
                unlink('storage/users/'.$this->user_sel_id.'/academic_formation_supports/' . $supportDocument); //eliminamos el archivo
            }
        }
        if ($professionalCard != null)//si la consulta devuelve el nombre de un archivo
        {
            if(file_exists('storage/users/'.$this->user_sel_id.'/academic_formation_supports/'. $professionalCard))//verificamos que el archivo exista fisicamente
            {
                unlink('storage/users/'.$this->user_sel_id.'/academic_formation_supports/' . $professionalCard); //eliminamos el archivo
            }
        }
        $academic_formation->delete();
        $this->emit('item-deleted-AF', 'Se eliminó la Formación acádemica con éxito');
    }


}
