<?php

namespace App\Http\Livewire;

use App\Models\Company;
use App\Models\DocumentType;

use App\Models\User;
use App\Models\UserDocument;
use App\Models\WorkPermit;
use App\Traits\OrderByTable;
use Carbon\Carbon;

use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\WithPagination;
use Illuminate\Support\Str as Str;


class Employee_DocumentsController extends Component
{
    use WithFileUploads;
    use WithPagination;
    use OrderByTable;

    public $user, $user_id, $company_id, $first_name, $last_name, $search, $count_reg, $selected_id;
    public $document_type_id, $document_type_name, $support_document, $status, $rejected_reason, $reviewed_by;

    public $breadcrumb_show = true;

    private $pagination = 10;

    protected $paginationTheme = 'bootstrap';

    public function updatingSearch(){
        $this->resetPage();
    }

    public function mount()
    {
        UserAuthPermission('Employee_documents_index');
        $user = User::find(auth()->user()->id);
        EmployeeOtherCompany($user->id); //Verifica que el empleado pertenezca a la empresa

        $this->user = $user;
        $this->user_id = $user->id;
        $this->first_name = $user->first_name;
        $this->last_name = $user->last_name;
        $company = Company::find(Auth::user()->CompanyInfo('id'));
        $this->company_id = $company->id;
        $this->pageTitle = 'Lista';
        $this->componentName = 'Documentos del empleado';
    }

    public function render()
    {
        if (strlen($this->search) > 0){
            $documents_company = DocumentType::select('document_types.*')
                            ->where('company_id', $this->company_id)
                            ->where(function($query) {
                                $query->where('document_types.name', 'like', '%' . $this->search . '%')
                                    ->orWhere('document_types.description', 'like', '%' . $this->search . '%');
                            })
                            ->orderBy('document_types.name', 'asc')
                            ->paginate($this->pagination);
        }
        else{
            $documents_company = DocumentType::select('document_types.*')
                            ->where('company_id', $this->company_id)
                            ->orderBy('document_types.name', 'asc')
                            ->paginate($this->pagination);
        }

        $user_documents = UserDocument::select('user_documents.document_type_id', 'user_documents.status')
                            ->where('user_id', $this->user_id)
                            ->where('company_id', $this->company_id)
                            ->get();

        $this->count_reg = $documents_company->count();
        return view('livewire.employee.documents.component', compact('documents_company', 'user_documents'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function resetUI(){
        $this->search = '';
        $this->selected_id = '';
        $this->name = '';
        $this->description = '';
        $this->support_document = '';
        $this->resetErrorBag();
    }

    public function CheckStatusDocument($id){
        $user_document = UserDocument::where('user_id', $this->user_id)
                            ->where('document_type_id', $id)
                            ->where('company_id', $this->company_id)
                            ->first();

        if ($user_document){
            $status = $user_document->status;
            if ($user_document->support_document == null)
                    $upload = true;
            else
                    $upload = false;
        }
        else{
            $status = '0';
            $upload = true;
        }

        return array($status, DataTypeStatusStandard($status), $upload); // retornamos el estado, el nombre del estado y si se puede subir o no el documento
    }

    public function ViewDocument($id){
        $user_document = UserDocument::where('user_id', $this->user_id)
                            ->where('document_type_id', $id)
                            ->where('company_id', $this->company_id)
                            ->first();
        return $user_document->support_document;
    }


    public function openViewRejectWorkPermit($id){
        $useractions = UserAuthPermissionActions('Employee_documents_index');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $work_permits = WorkPermit::find($id);
        $this->selected_id = $id;
        $this->rejected_reason = $work_permits->rejected_reason;

        $this->emit('show-modal-reject','Abrir Modal');
    }

    public function openUploadSupportDocument($id){
        $useractions = UserAuthPermissionActions('Employee_documents_index');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        if (ItemNotCompany($id, $this->company_id, 'document_types', true) == NULL){
            $this->emit('item-error', ItemNotCompany($id, $this->company_id, 'document_types', true)[1]);
            return false;
        }

        $documents_company = DocumentType::find($id);

        $user_document = UserDocument::where('user_id', $this->user_id)->where('document_type_id', $id)->first();

        if ($user_document != NULL){
            if ($user_document->status == '1'){
                $this->emit('item-error', 'El tipo de documento seleccionado ya fue aprobado.');
                return false;
            }
            $this->status = $user_document->status;
            $this->selected_id = $user_document->id;
            $this->rejected_reason = $user_document->rejected_reason;
        }
        else{
            $this->status = '0';
            $this->selected_id = 0;
        }
        $this->document_type_id = $id;
        $this->document_type_name = $documents_company->name;



        $this->emit('show-modal-support-document','Abrir Modal');
    }

    public function uploadSupportDocument(){
        $rules=[
            'support_document' => 'required|mimes:pdf,jpg,jpeg,png',
        ];

        $messages=[
            'support_document.required' => 'El campo documento es obligatorio',
            'support_document.mimes' => 'El documento debe ser un archivo de tipo PDF, JPG, JPEG o PNG',
        ];

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

        $type_document_name = Str::slug($this->document_type_name);


        if ($this->selected_id == 0){
            $user_document = UserDocument::create([
                'user_id' => $this->user_id,
                'company_id' => $this->company_id,
                'document_type_id' => $this->document_type_id,
                'status' => '0',
            ]);
        }
        else{
            $user_document = UserDocument::find($this->selected_id);
            $user_document->Update(
                ['status' => '0',]
            );
            $this->status_support_document = '0';
        }

        if ($user_document->status == '0' && $user_document->support_document != NULL){
            $this->emit('item-error', 'El tipo de documento seleccionado esta en proceso de aprobación.');
            return false;
        }
        if ($this->support_document)
        {

            $customFileName = $type_document_name.'_'.$this->user_id.'_'.Carbon::now()->format('YmdHis').'.'.$this->support_document->extension();
            $this->support_document->storeAs('public/users/'.$this->user_id.'/documents', $customFileName);
            $user_document->support_document = $customFileName;
            $user_document->save();
        }

        $this->emit('hide-modal-support-document','El documento se ha subido correctamente');
        $this->resetUI();
    }
}
