<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'name', 'code', 'sort_order', 'default_probability', 'is_won', 'is_lost',
        'status', 'description', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'name'                => 'required|min_length[2]|max_length[100]',
        'code'                => 'required|max_length[20]|is_unique[sales_stages.code,id,{id}]',
        'default_probability' => 'permit_empty|integer|greater_than_equal_to[0]|less_than_equal_to[100]',
        'status'              => 'permit_empty|in_list[active,inactive]',
    ];

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

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

        return $this;
    }

    public function getActive(): array
    {
        return $this->where('status', 'active')
            ->orderBy('sort_order', 'ASC')
            ->orderBy('name', 'ASC')
            ->findAll();
    }

    public function isCodeTaken(string $code, ?int $excludeId = null): bool
    {
        $builder = $this->where('code', strtoupper($code));
        if ($excludeId) {
            $builder->where('id !=', $excludeId);
        }

        return $builder->countAllResults() > 0;
    }
}
