<?php

namespace App\Repositories\Eloquent;

use App\Models\Profession;

class ProfessionManagementRepository
{
    public function paginate(array $filters = [])
    {
        return Profession::with('parent')->withCount(['professionals', 'children'])
            ->when($filters['q'] ?? null, fn ($query, $term) => $query->where('name', 'like', "%{$term}%"))
            ->when(($filters['type'] ?? '') === 'parent', fn ($query) => $query->where('parent_id', 0))
            ->when(($filters['type'] ?? '') === 'sub', fn ($query) => $query->where('parent_id', '>', 0))
            ->when(isset($filters['status']) && $filters['status'] !== '', fn ($query) => $query->where('status', (bool) $filters['status']))
            ->orderByRaw('CASE WHEN parent_id = 0 THEN id ELSE parent_id END')
            ->orderBy('parent_id')->orderBy('name')->paginate(12)->withQueryString();
    }

    public function stats(): array
    {
        return [
            'total' => Profession::count(),
            'parents' => Profession::where('parent_id', 0)->count(),
            'sub' => Profession::where('parent_id', '>', 0)->count(),
            'active' => Profession::where('status', true)->count(),
        ];
    }

    public function parents()
    {
        return Profession::where('parent_id', 0)->orderBy('name')->get();
    }

    public function parentExists(int $id): bool
    {
        return Profession::whereKey($id)->where('parent_id', 0)->exists();
    }

    public function create(array $data): Profession
    {
        return Profession::create($data);
    }

    public function update(Profession $profession, array $data): Profession
    {
        $profession->update($data);

        return $profession->refresh();
    }
}
