<?php

namespace App\Http\Livewire;

use App\Models\Company;
use App\Models\PaymentVoucher;
use App\Models\TypePsychotechnicsTest;
use App\Models\User;
use App\Models\UserPsychotechnicsTest;
use Illuminate\Support\Facades\Auth;
use Livewire\WithPagination;
use Livewire\WithFileUploads;
use Livewire\Component;
use App\Traits\OrderByTable;
use Illuminate\Support\Str as Str;

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

    public $search, $company_id, $pageTitle, $componentName, $user_id, $selected_PV_id;
    public $support_document, $month, $year, $support_document_view, $min_year, $max_year;
    public $company_name, $company_plan_name, $company_plan_id;
    public $first_name, $last_name;

    public $breadcrumb_show;

    private $pagination = 10;

    protected $paginationTheme = 'bootstrap';

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

        UserAuthPermission('Company_employee_payment_voucher_index');
        $user = User::find($id);
        $this->user_id = $user->id;
        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 = 'Desprendibles de pago';
        $this->componentName = 'Desprendibles de pago';

        $this->breadcrumb_show = $breadcrumb_show;

    }

    public function render()
    {



        $payment_vouchers_user = PaymentVoucher::where('user_id', $this->user_id)
            ->where('company_id', $this->company_id)
            ->where(function ($query) {
                if ($this->month != null) {
                    $query->where('payment_vouchers.month', $this->month);
                }
            })
            ->where(function ($query) {
                if ($this->year != null) {
                    $query->where('payment_vouchers.year', $this->year);
                }
            })
            ->orderBy($this->sortBy, $this->sortDirection)->paginate($this->pagination);

        $payment_vouchers = PaymentVoucher::where('user_id', $this->user_id)
            ->where('company_id', $this->company_id);
        $count_payment_vouchers = $payment_vouchers->count();
        if ($count_payment_vouchers > 0){

            $this->min_year = $payment_vouchers->min('year');
            $this->max_year= $payment_vouchers->max('year');
        }
        else{
            //seleccionar año actual
            $this->min_year = date('Y');
            $this->max_year = date('Y');
        }
        return view('livewire.company.employee.detail.payment-vouchers.component',compact('payment_vouchers_user'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function resetUI()
    {
        $this->selected_PST_id = 0;
        $this->type_psychotechnics_test_id = 0;
        $this->observations = '';
        $this->document_upload = '';
        $this->document_upload_view = '';
        $this->resetValidation();
    }

    public function openAddPV()
    {
        $useractions = UserAuthPermissionActions('Company_employee_payment_voucher_create');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $this->selected_PST_id = 0;
        $this->resetUI();
        $this->emit('show-modal-PV','Abrir Modal');
    }

    public function StorePV(){
        $useractions = UserAuthPermissionActions('Company_employee_payment_voucher_create');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }

        $rules = [
            'support_document' => 'required|file|mimes:pdf,jpg,jpeg,png|max:2048',
            'month' => 'required',
            'year' => 'required',
        ];

        $messages = [
            'support_document.required' => 'El documento es requerido',
            'support_document.file' => 'El documento debe ser un archivo',
            'support_document.mimes' => 'El documento debe ser un archivo de tipo: pdf, jpg, jpeg, png',
            'support_document.max' => 'El documento debe ser menor a 2MB',
            'month.required' => 'El mes es requerido',
            'year.required' => 'El año es requerido',
        ];

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

        $user_payment_voucher = PaymentVoucher::create([
            'user_id' => $this->user_id,
            'company_id' => $this->company_id,
            'month' => $this->month,
            'year' => $this->year,
        ]);
        $payment_voucher_name = 'payment_voucher_'.$this->user_id.'_'.$this->company_id.'_'.$this->month.'_'.$this->year.'_'.uniqid(time(), false);
        if ($this->support_document)
        {
            $customFileName = $payment_voucher_name.'.'.$this->support_document->extension();
            $this->support_document->storeAs('public/users/'.$this->user_id.'/payment_vouchers', $customFileName);
            $user_payment_voucher->support_document = $customFileName;
            $user_payment_voucher->save();
        }
        $this->resetUI();
        $this->emit('item-added-PV', 'Desprendible de pago agregado correctamente');
    }


    public function ViewPV(PaymentVoucher $payment_voucher){
        if (EmployeeOtherCompany($this->user_id, true)[0] == NULL)
        {
            $this->emit('item-error', EmployeeOtherCompany($this->user_sel_id, true)[1]);
            return false;
        }
        $useractions = UserAuthPermissionActions('Company_employee_psychotechnics_test_index');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $this->selected_PV_id = $payment_voucher->id;
        $this->month = $payment_voucher->month;
        $this->year = $payment_voucher->year;
        $this->support_document_view = $payment_voucher->support_document;
        $this->emit('show-modal-PV', 'Abrir Modal');
    }
    protected $listeners = ['deleteRowPV' => 'DestroyPV'];

    public function DestroyPV(PaymentVoucher $payment_voucher){
        if (EmployeeOtherCompany($this->user_id, true)[0] == NULL)
        {
            $this->emit('item-error-PV', EmployeeOtherCompany($this->user_id, true)[1]);
            return false;
        }
        $supportDocument = $payment_voucher->support_document;

        if ($supportDocument != null)//si la consulta devuelve el nombre del documento
        {
            if(file_exists('storage/users/'.$this->user_id.'/payment_vouchers/'. $supportDocument))//verificamos que el archivo exista fisicamente
            {
                unlink('storage/users/'.$this->user_id.'/payment_vouchers/' . $supportDocument); //eliminamos el archivo
            }
        }

        $payment_voucher->delete();
        $this->emit('item-deleted-PV', 'Se eliminó el desprendible de pago correctamente');
    }

}
