<?php

namespace App\Http\Livewire;

use App\Imports\EmployeesImport;
use App\Models\Company;
use App\Models\Plan;
use App\Models\User;
use App\Traits\OrderByTable;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\WithPagination;
use Maatwebsite\Excel\Facades\Excel;
use Maatwebsite\Excel\Validators\ValidationException;

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

    public $componentName, $pageTitle, $search, $file;
    public $company_id,  $company_name, $company_plan_name, $company_plan_id, $company_employees_count, $company_employees_max;

    private $pagination = 25;

    protected $paginationTheme = 'bootstrap';

    public $breadcrumb_show = true;

    public function mount(){
        UserAuthPermission('Company_employees_import');


        $this->company_id = Auth::user()->CompanyInfo('id');
        $this->componentName = 'Empleados';
        $this->pageTitle = 'Importar información';
        $this->company_name = Company::find($this->company_id )->name;
        $this->company_plan_name = Company::find($this->company_id )->plan->name;
        $this->company_plan_id = Company::find($this->company_id )->plan->id;

    }

    public function resetUI(){
        $this->search = '';
        $this->file = null;
        $this->resetValidation();
        $this->resetPage();
    }
    public function render()
    {
        if (strlen($this->search) > 0)
            {

                $users= User::role('Empleado')
                            ->join('company_user', 'users.id', '=', 'company_user.user_id')
                            ->join('companies', 'company_user.company_id', '=', 'companies.id')
                            ->select('users.*','companies.name as company_name', 'company_user.job_position_id')
                            ->where('companies.id', Auth::user()->CompanyId())
                            ->where(function ($query) {
                            $query->where('first_name', 'like', '%' . $this->search . '%')
                                    ->orWhere('last_name', 'like', '%' . $this->search . '%')
                                    ->orWhere('document', 'like', '%' . $this->search . '%');
                            })
                            ->orderBy($this->sortBy, $this->sortDirection)->paginate($this->pagination);
            }
            else
            {
                $users= User::role('Empleado')
                            ->join('company_user', 'users.id', '=', 'company_user.user_id')
                            ->join('companies', 'company_user.company_id', '=', 'companies.id')
                            ->where('companies.id', Auth::user()->CompanyId())
                            ->select('users.*','companies.name as company_name', 'company_user.job_position_id')
                            ->orderBy($this->sortBy, $this->sortDirection)
                            ->paginate($this->pagination);
            }
        $this->company_employees_count = $users->total();

        $this->company_employees_max = Plan::find($this->company_plan_id)->max_users_employees;


        return view('livewire.company.import.employees.component',compact('users'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function openImportModal(){
        $this->emit('show-modal', 'importModal');
    }

    public function importData(){
        $rules = [
            'file' => 'required|mimes:xlsx,xls',
        ];
        $messages = [
            'file.required' => 'El archivo es requerido.',
            'file.mimes' => 'El archivo debe ser un archivo de Excel.',
        ];
        $this->validate($rules, $messages);
       //$customFileName = 'import-employees.'.$this->file->extension();
       // $file = $this->file->storeAs('public/company/'.$this->company_id, $customFileName);
        $file = $this->file;
        //dd($this->file);
        $import = new EmployeesImport;
        $import->onlySheets('Empleados');
        //dd($import);
        $import->import($file);
        //dd($import);

       //dd($import->failures());
        if ($import->failures()->isNotEmpty()) {
            return back()->withFailures($import->failures());
        }
        //dd('Importación completada');
        //dd($import);
        //Excel::import(new EmployeesImport, $file);

        $this->resetUI();

        $this->emit('item-updated','Se ha importado la información correctamente.');
    }


}
