<?php

namespace App\Models;

use CodeIgniter\Model;

class LeadAssignmentRuleModel extends Model
{
    protected $table         = 'lead_assignment_rules';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';

    protected $allowedFields = [
        'name', 'lead_source_id', 'assign_to_user_id', 'priority', 'status',
        'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'name'                => 'required|min_length[2]|max_length[100]',
        'assign_to_user_id'   => 'required|integer',
        'status'              => 'permit_empty|in_list[active,inactive]',
    ];

    public function getActiveOrdered(): array
    {
        return $this->where('status', 'active')
            ->orderBy('priority', 'ASC')
            ->orderBy('id', 'ASC')
            ->findAll();
    }

    public function scopeForList(?string $search = null, ?string $status = null): self
    {
        if ($search) {
            $this->like('name', $search);
        }

        if ($status) {
            $this->where('status', $status);
        }

        return $this;
    }
}
