<?php

namespace App\Repositories\Eloquent;

use App\Models\Student;
use Illuminate\Database\Eloquent\Builder;

class StudentRepository extends BaseRepository
{
    protected function model(): string
    {
        return Student::class;
    }

    /** Listing query with the relations the index table needs. */
    public function listing(array $filters = []): Builder
    {
        return $this->query()
            ->with(['family', 'schoolClass', 'section'])
            ->when($filters['class_id'] ?? null, fn ($q, $v) => $q->where('class_id', $v))
            ->when($filters['section_id'] ?? null, fn ($q, $v) => $q->where('section_id', $v))
            ->when($filters['status'] ?? null, fn ($q, $v) => $q->where('status', $v))
            ->when($filters['free'] ?? null, fn ($q) => $q->whereHas('concessions', fn ($c) => $c
                ->where('is_active', true)
                ->whereNull('fee_type_id')
                ->where('type', 'percentage')
                ->where('value', '>=', 100)))
            ->when($filters['search'] ?? null, function ($q, $term) {
                $like = '%'.$term.'%';
                $q->where(function ($w) use ($like) {
                    $w->where('name', 'like', $like)
                        ->orWhere('admission_number', 'like', $like)
                        ->orWhere('registration_number', 'like', $like)
                        ->orWhere('gr_number', 'like', $like)
                        ->orWhere('roll_number', 'like', $like)
                        ->orWhere('b_form_number', 'like', $like)
                        ->orWhereHas('family', fn ($f) => $f->where('family_code', 'like', $like)
                            ->orWhere('father_name', 'like', $like)
                            ->orWhere('mother_name', 'like', $like)
                            ->orWhere('guardian_name', 'like', $like)
                            ->orWhere('father_mobile', 'like', $like)
                            ->orWhere('father_cnic', 'like', $like));
                });
            })
            ->latest('id');
    }
}
