<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'name', 'code', 'website', 'strengths', 'weaknesses', 'status', 'notes',
        'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'name'   => 'required|min_length[2]|max_length[150]',
        '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)
                ->orLike('website', $search)
                ->groupEnd();
        }

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

        return $this;
    }

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

    public function isCodeTaken(string $code, ?int $excludeId = null): bool
    {
        if ($code === '') {
            return false;
        }

        $builder = $this->where('code', strtoupper($code));
        if ($excludeId) {
            $builder->where('id !=', $excludeId);
        }

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