<?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 Carbon\Carbon;
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_ReportsController 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()
    {
        $salary_type = $this->reportSalaryType()['chart_data'];
        $age_users = $this->reportAgeUsers();
        return view('livewire.company.reports.component', compact('salary_type', 'age_users'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function reportSalaryType(){
        $user_company_salary_type = User::role('Empleado')
            ->join('company_user', 'users.id', '=', 'company_user.user_id')
            ->join('companies', 'company_user.company_id', '=', 'companies.id')
            ->select(
                DB::raw("(count(*)) as salary_type")
                )
            ->where('companies.id', $this->company_id)
            ->where('users.status','ACTIVO')
            ->where('company_user.salary_type', '!=', null)
            ->groupBy('salary_type')
            ->get();
        if ($user_company_salary_type->count() > 0) {
            $data = [];
            foreach ($user_company_salary_type as $row) {
                $data['salary_type'][] = $row->salary_type;
                $data['count'] = $user_company_salary_type->count();
            }
            $data['chart_data'] = json_encode($data['salary_type']);
        }
        else{
            $data['salary_type'] = ['0','0','0'];
            $data['chart_data'] = json_encode(['0','0','0']);
        }
        return $data;
    }

    public function reportAgeUsers(){
        //agrupar por edad tomando la fecha de nacimiento
        $ranges =[ //rango de edad
            '0-17' => [
                'min' => 0,
                'max' => 17,
                ],
            '18-25' => [
                'min' => 18,
                'max' => 25,
                ],
            '26-35' => [
                'min' => 26,
                'max' => 35,
                ],
            '36-45' => [
                'min' => 36,
                'max' => 45,
                ],
            '46-55' => [
                'min' => 46,
                'max' => 55,
                ],
            '56-65' => [
                'min' => 56,
                'max' => 65,
                ],
            '65+' => [
                'min' => 66,
                'max' => 100,
                ],
            ];
        $array_range_default=[ //array para el rango de edad por defecto
            '0-17'  => 0,
            '18-25' => 0,
            '26-35' => 0,
            '36-45' => 0,
            '46-55' => 0,
            '56-65' => 0,
            '65+' => 0,
        ];

        $output = User::role('Empleado')
        ->join('company_user', 'users.id', '=', 'company_user.user_id')
        ->join('companies', 'company_user.company_id', '=', 'companies.id')
        ->where('companies.id', $this->company_id)
        ->where('users.status','ACTIVO')
        ->where('users.birth_date', '!=', null)
        ->get()
        ->map(function ($user) use ($ranges) {
            $age = Carbon::parse($user->birth_date)->age; //calcular la edad

            foreach ($ranges as $key => $value) {
                if($age >= $value['min'] && $age <= $value['max']){//si la edad esta dentro del rango
                    $user->range = $key;
                    break;//terminar el ciclo
                }
            }
            return $user;
        })
        ->mapToGroups(function ($user, $key) {// usar el rango de edad para agrupar los usuarios
            return [$user->range => $user];
        })
        ->map(function ($group){//calcular el total de usuarios por rango de edad
            return $group->count();
        })
        ->toArray();

            $output=combineArray($array_range_default, $output);
        $output = json_encode($output);
        return $output;
    }


}
