<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'name', 'code', 'employee_id', 'territory_id', 'email', 'phone',
        '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
    {
        $this->select('sales_representatives.*, sales_territories.name as territory_name')
            ->join('sales_territories', 'sales_territories.id = sales_representatives.territory_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('sales_representatives.name', $search)
                ->orLike('sales_representatives.code', $search)
                ->orLike('sales_representatives.email', $search)
                ->groupEnd();
        }

        if ($status) {
            $this->where('sales_representatives.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;
    }
}
