<?php

namespace App\Imports;

use App\Models\Company;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\SkipsErrors;
use Maatwebsite\Excel\Concerns\SkipsFailures;
use Maatwebsite\Excel\Concerns\SkipsOnError;
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithConditionalSheets;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Validators\Failure;
use Maatwebsite\Excel\Concerns\WithValidation;
use Throwable;

class EmployeesImport implements ToModel, WithHeadingRow, SkipsOnError, WithValidation, SkipsOnFailure, SkipsEmptyRows
{
    use WithConditionalSheets, SkipsErrors, Importable, SkipsFailures;
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        $company_id = Company::find(Auth::user()->CompanyId())->id;

        $max_employees = Company::find($company_id)
        ->join('plans', 'plans.id', '=', 'companies.plan_id')->get()->first()->max_users_employees;
        $max_employees_created = Company::find($company_id)->users()->role('Empleado')->count();

        if ($max_employees_created >= $max_employees) {
            throw new \Exception('No puedes crear más empleados, el plan de tu empresa ya no te permite crear más empleados.');
        }
        else{
            return
                $user = User::create([
                'document_type' => $row['tipo_documento'],
                'document' => $row['documento'],
                'first_name' => $row['nombre'],
                'last_name' => $row['apellido'],
                'email' => $row['email'],
                'phone' => $row['telefono'],
                'password' => bcrypt($row['password']),
                'civil_status' => $row['estado_civil'],
                'gender_user' => $row['genero'],
                'nationality' => $row['nacionalidad'],
                'birth_date' => Carbon::parse($row['fecha_nacimiento'])->format('Y-m-d'),
                'birth_place' => $row['lugar_nacimiento'],
                'address' => $row['direccion_residencia'],
                'state_residence' => $row['codigo_departamento_residencia'],
                'city_residence' => $row['codigo_ciudad_residencia'],
                'title_position' => $row['titulo_profesional'],
                'professional_license' => $row['nro_matricula_profesional'],
                ])->assignRole(['Empleado'])->companies()->attach($company_id);
        }
    }

    public function rules(): array
    {
        return [
            '*.documento' => ['required', 'unique:users,document'],
            '*.nombre' => ['required'],
            '*.apellido' => ['required'],
            '*.email' => ['required', 'email', 'unique:users,email'],
            '*.telefono' => ['required', 'unique:users,phone'],
            '*.password' => ['required', 'min:8'],
        ];
    }





    public function conditionalSheets(): array
    {
        return [
            'Empleados' => new EmployeesImport(),
        ];
    }
}
