<?php

namespace App\Repositories;

use App\Models\Inspecteur;

class InspecteurRepository extends BaseRepository
{
    public function __construct(Inspecteur $model)
    {
        parent::__construct($model);
    }

    public function findByMatricule($matricule)
    {
        return $this->query->where('matricule', $matricule)->first();
    }

    public function findByPole($poleId)
    {
        return $this->query->where('pole_id', $poleId)->get();
    }

    public function findByDiscipline($disciplineId)
    {
        return $this->query->where('discipline_id', $disciplineId)->get();
    }

    public function search($term)
    {
        return $this->query->where(function ($query) use ($term) {
            $query->where('nomfr', 'like', "%{$term}%")
                  ->orWhere('nomar', 'like', "%{$term}%")
                  ->orWhere('matricule', 'like', "%{$term}%")
                  ->orWhere('email', 'like', "%{$term}%");
        })->get();
    }

    public function getStatistics()
    {
        return [
            'total' => $this->count(),
            'by_pole' => $this->query->select('pole_id')
                ->selectRaw('count(*) as count')
                ->groupBy('pole_id')
                ->get()
                ->pluck('count', 'pole_id'),
            'by_discipline' => $this->query->select('discipline_id')
                ->selectRaw('count(*) as count')
                ->groupBy('discipline_id')
                ->get()
                ->pluck('count', 'discipline_id'),
        ];
    }
}
