<?php

namespace App\Imports;

use App\Models\Department;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class DepartementsImport implements ToCollection, WithHeadingRow, ShouldQueue
{
    protected int $userId;

    public function __construct(?int $userId = null)
    {
        $this->userId = $userId ?? Auth::id();
    }

    //Validation des données 
    public function rules(): array
    {
        return [
            '*.nom' => 'required|string',
            '*.responsable' => 'required|string',
            '*.telephone' => 'required|string|min:12',
        ];
    }
    /**
     * @param array $row
     *
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function collection(Collection $rows)
    {

        //Parcourons les lignes du fichier excel
        foreach ($rows as $row) {
            //Récuperons tous les départements même ceux qui sont supprimés
            $department = Department::withTrashed()
                ->where('user_id', Auth::id())
                ->where('name', $row['nom'])
                ->first();

            //Vérification de la suppression et restauration
            if ($department) {

                //Restauration du département
                if ($department->trashed()) {
                    $department->restore();
                }

                //Mise à jour des données du département
                $department->update([
                    // 'name' => $row['name'],
                    'name_of_manager' => $row['responsable'],
                    'phone_of_manager' => $row['telephone'],
                ]);
            } else {
                //Créons le département
                Department::create([
                    'name' => $row['nom'],
                    'name_of_manager' => $row['responsable'],
                    'phone_of_manager' => $row['telephone'],
                    'user_id' => Auth::id(),
                ]);
            }
        }
    }
}