<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'name', 'code', 'email', 'phone', 'website', 'industry',
        'customer_type', 'is_one_time',
        'customer_group_id', 'site_id', 'address', 'city', 'country', 'status', 'notes',
        'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'name'          => 'required|min_length[2]|max_length[150]',
        'email'         => 'permit_empty|valid_email|max_length[191]',
        'status'        => 'permit_empty|in_list[active,inactive]',
        'customer_type' => 'permit_empty|in_list[product,service,project]',
    ];

    public function scopeForList(
        ?string $search = null,
        ?string $status = null,
        ?int $groupId = null,
        ?string $customerType = null,
        ?int $isOneTime = null,
        ?int $siteId = null
    ): self {
        if ($search) {
            $this->groupStart()
                ->like('name', $search)
                ->orLike('code', $search)
                ->orLike('email', $search)
                ->orLike('phone', $search)
                ->orLike('industry', $search)
                ->groupEnd();
        }

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

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

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

        if ($isOneTime !== null) {
            $this->where('is_one_time', $isOneTime);
        }

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

        return $this;
    }

    public function getActiveByType(?string $customerType = null): array
    {
        $this->where('status', 'active');
        if ($customerType) {
            $this->where('customer_type', $customerType);
        }

        return $this->orderBy('name', 'ASC')->findAll();
    }

    public function getActive(?string $search = null, int $limit = 200): array
    {
        $builder = $this->where('status', 'active');

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

        return $builder->orderBy('name', 'ASC')->limit($limit)->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;
    }
}
