<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;

class DetInitialStep extends Model
{
    use HasFactory;

    protected $table = "tbl_det_initial_step";
    protected $primaryKey = "id";

    protected $fillable = [
        'idinitial_step',
        'key_plan',
        'order',
        'status'
    ];

    protected $hidden = [
        'created_at',
        'updated_at'
    ];

    #Relaciones
    public function initialStep():HasOne
    {
        return $this->hasOne(InitialStep::class, 'id', 'idinitial_step');
    }

    # Query scopes
    public function scopeActiveForID($query, $id)
    {
        return $query->where('id', $id)->where('status', 1);
    }

    public function scopeActive($query)
    {
        return $query->where('status', 1);
    }

    # Filtros
    public function scopeDetInitialStepFilters($query)
    {
        #Filtro de Buscador
        $query->when(
            request('search'),
            fn ($query) => $query->whereHas('initialStep', fn($q) => $q->where('description', 'LIKE', '%' . request('description') . '%'))
        );

        #Filtro de nombre de descripcion
        $query->when(
            request('description'),
            fn ($query) => $query->whereHas('initialStep', fn($q) => $q->where('description', 'LIKE', '%' . request('description') . '%'))
        );

        #Filtro de paso inicial
        $query->when(
            request('idinitial_step'),
            fn ($query) => $query->where('idinitial_step', request('idinitial_step'))
        );

        #Filtro de plan
        $query->when(
            request('plan'),
            fn ($query) => $query->where('key_plan', request('plan'))
        );

        #Filtro de estados
        $query->when(
            request('status'),
            fn ($query) => $query->where('status', request('status'))
        )->when(
            !request('status'),
            fn ($query) => $query->where('status', 1)
        );
    }
}
