<?php

namespace App\Imports;

use App\Models\User;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class UserExcelImport implements ToCollection, WithHeadingRow
{
    protected $school;
    protected $role;
    public function __construct($school,  $role)
    {
        $this->school = $school;
        $this->role = $role;
    }

    /**
    * @param Collection $collection
    */
    public function collection(Collection $rows)
    {
        foreach($rows as $item){
            if(isset($item['nom']) && isset($item['prenoms']) && isset($item['sexe']) && $this->validEmail($item['adresse_email']) && $this->validContact($item['num_telephone']) && isset($item['autorisation'])){
                // Contenu de la partie
                if(!$this->verifyUser($item['adresse_email'], $item['num_telephone'])){
                    if($this->validatedate($item['autorisation'], $item['date_autorisation'])){
                        User::create([
                            'role_id' => $this->role ,
                            'first_name' => strtolower($item['nom']),
                            'last_name' => strtolower($item['prenoms']),
                            'sexe' => $item['sexe'] == 'Femme' ? 'F':'H',
                            'email' => $item['adresse_email'],
                            'telephon' => $item['num_telephone'],
                            'residence' => strtolower($item['lieu_de_residence']),
                            'matrimoniale' => $item['matrimoniale'],
                            'embauche' => $item['type_contrat'],
                            'typeEnseignant' => $item['type_enseignant'] == 'instituteur' ? 'maitre':'professeur',
                            'autorisation' => $this->valAutorisation($item['autorisation']),
                            'num_autorisation' => $item['autorisation'] == 'Non' ? $item['num_autorisation']:null,
                            'date_autorisation' => $item['autorisation'] == 'Non' ? $this->verifyDateAuto($item['date_autorisation']):null,
                            'diplome' => strtolower($item['diplome']),
                            'school_id' => $this->school,
                            'password' => Hash::make('000000'), // Mot de passe par defaut
                            'remember_token' => Str::random(10),
                        ]);
                    }
                }
            }
        }
    }

    // Vérification d'enseignant
    private function verifyUser($email, $numero)
    {
        $exist = User::where('email', $email)->orWhere('telephon', '0'.$numero)->count();
        return $exist ?? null;
    }

    private function valAutorisation($auto)
    { 
        return $auto == 'Oui' ? '1':'0';
    }

    private function validEmail($email)
    {
        return filter_var($email, FILTER_VALIDATE_EMAIL) ? $email:null;
    }

    private function validContact($valeur)
    {
        if (!empty($valeur) && !is_numeric($valeur)) {
            return null; // Non numérique
        }
        return $valeur ?? null;
    }

    private function verifyDateAuto($valeur)
    {
        return is_numeric($valeur) ? date('d-m-Y', strtotime(Carbon::instance(ExcelDate::excelToDateTimeObject($valeur)))):null;
    }

    private function validatedate($auto, $date)
    {
        return $auto == 'oui' ? $this->verifyDateAuto($date):true;
    }
    
}
