<?php

namespace App\Http\Livewire;

use App\Models\Company;
use App\Models\DocumentType;
use App\Models\User;
use App\Models\UserDocument;
use Illuminate\Support\Facades\Auth;
use Livewire\WithPagination;
use Livewire\WithFileUploads;
use Livewire\Component;
use App\Traits\OrderByTable;



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

    public $search, $company_id, $pageTitle, $componentName, $user_id, $selected_id;
    public $reviewed_by, $rejected_reason, $support_document;
    public $status_document, $status, $document_type_id, $document_type_name;
    public $company_name, $company_plan_name, $company_plan_id;
    public $first_name, $last_name;

    public $breadcrumb_show;

    private $pagination = 10;

    protected $paginationTheme = 'bootstrap';

    protected $listeners = [
        'reload-list-documents' => 'searchList', // emit del componente WorkPermitDetailController para refrescar la lista de permisos laborales
        'UserDocumentAction'
    ];


    public function mount($id=null, $breadcrumb_show=true)
    {
        if ($id == null) {
            return redirect()->route('dashboard');
        }

        UserAuthPermission('Company_user_document_index');
        $user = User::find($id);
        $this->user_id = $user->id;
        $this->first_name = $user->first_name;
        $this->last_name = $user->last_name;
        if ($user->status == 'INACTIVO'){
            return redirect()->route('dashboard');
        }
        EmployeeOtherCompany($this->user_id); //Verifica que el empleado pertenezca a la empresa
        $this->company_id = Company::find(Auth::user()->CompanyId())->id;
        $this->pageTitle = 'Certificados Laborales';
        $this->componentName = 'Solicitudes';

        $this->breadcrumb_show = $breadcrumb_show;


        $this->sortBy= 'work_certificates.created_at';

    }

    public function render()
    {
        $documents_company = $this->searchList();
        $this->count_reg = $documents_company->total();

        return view('livewire.company.employee.detail.documents.component',compact('documents_company'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function searchList(){
        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);
        }
        return $documents_company;
    }

    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)
                    $view = false;
            else
                    $view = true;
        }
        else{
            $status = '0';
            $view = false;
        }

        return array($status, DataTypeStatusStandard($status), $view); // retornamos el estado, el nombre del estado y si existe documento para visualizar
    }

    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 UserDocumentAction($id, $opc, $reason=null){
        //dd($id, $opc, $reason);
        $useractions = UserAuthPermissionActions('Company_user_document_update');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }

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

        if ($opc == '1'){
            $this->status = '1';
                $this->rejected_reason = null;
                $message = 'El Documento se ha aprobado';
                $body ='Se ha aprobado el documento, para mas información consulte el módulo de Documentos.';
                $user_document->Update(
                    [
                        'status' => $this->status,
                        'reviewed_by' => Auth::user()->id,
                        'rejected_reason' => $reason,
                    ]
                );
        }
        else{
            $this->status = '2';
            $this->rejected_reason = $reason;
            $message = 'El documento se ha rechazado';
            $body= 'El documento ha sido rechazado, para mas información consulte el módulo de Documentos.';
            $imageName = $user_document->support_document; //nombre de la imagen actual guardada en la base de datos
            if ($imageName != null)//si la consulta devuelve el nombre de una imagen
            {
                if(file_exists('storage/users/'.$this->user_id.'/documents/'. $imageName))//verificamos que la imagen exista fisicamente
                {
                    unlink('storage/users/'.$this->user_id.'/documents/' . $imageName); //eliminamos la imagen
                }
            }
            $user_document->Update(
                [
                    'status' => $this->status,
                    'reviewed_by' => Auth::user()->id,
                    'rejected_reason' => $reason,
                    'support_document' => null,

                ]
            );
        }


        $this->emit('reload-list-documents','reload-documents');
        $message = NotifyMessageCustom(
            $title = $message,
            $body = $body,
            $url = route('empleado-documentos'),
            $button_text = 'Ver documentos',
            $via_from = 'Company',
            $user_to_id = $user_document->user_id,
            $user_from_id = Auth::user()->id
        );

        //$this->emit('work-certificate-updated', $message);
    }



}
