<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class Candidate extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'political_party_id',
        'department_id',
        'type',
        'number',
        'first_name',
        'last_name',
        'photo',
    ];

    public function politicalParty(): BelongsTo
    {
        return $this->belongsTo(PoliticalParty::class);
    }

    public function department(): BelongsTo
    {
        return $this->belongsTo(Department::class);
    }

    public function scopeOfType($query, string $type)
    {
        return $query->where('type', $type);
    }

    public function scopeOfParty($query, $partyId)
    {
        if ($partyId) {
            $query->where('political_party_id', $partyId);
        }
        return $query;
    }

    public function scopeOfDepartment($query, $departmentId)
    {
        if ($departmentId) {
            $query->where('department_id', $departmentId);
        }
        return $query;
    }

    public function scopeSearch($query, ?string $term)
    {
        if ($term) {
            $query->where(function ($q) use ($term) {
                $q->where('first_name', 'like', "%{$term}%")
                  ->orWhere('last_name', 'like', "%{$term}%");
            });
        }
        return $query;
    }
}
