<?php

namespace App\Repositories;

use App\Models\Etablissement;

class EtablissementRepository extends BaseRepository
{
    public function __construct(Etablissement $model)
    {
        parent::__construct($model);
    }

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

    public function findByWilaya($wilayaId)
    {
        return $this->query->where('wilaya_id', $wilayaId)->get();
    }

    public function findByMoughataa($moughataaId)
    {
        return $this->query->where('moughataa_id', $moughataaId)->get();
    }

    public function findByCommune($communeId)
    {
        return $this->query->where('commune_id', $communeId)->get();
    }

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

    public function getStatistics()
    {
        return [
            'total' => $this->count(),
            'by_cycle' => $this->query->select('cycle_id')
                ->selectRaw('count(*) as count')
                ->groupBy('cycle_id')
                ->get()
                ->pluck('count', 'cycle_id'),
            'by_commune' => $this->query->select('commune_id')
                ->selectRaw('count(*) as count')
                ->groupBy('commune_id')
                ->get()
                ->pluck('count', 'commune_id'),
        ];
    }
}
