<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'name', 'code', 'site_type', 'address', 'city', 'country',
        'description', 'status', 'notes', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'name'   => 'required|min_length[2]|max_length[150]',
        'code'   => 'required|max_length[30]|is_unique[customer_sites.code,id,{id}]',
        '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('site_type', $search)
                ->orLike('city', $search)
                ->groupEnd();
        }

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

        return $this;
    }

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

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

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

    /**
     * @param list<int|string> $siteIds
     *
     * @return array<int, int>
     */
    public function countCustomersForSites(array $siteIds): array
    {
        if ($siteIds === []) {
            return [];
        }

        $rows = model(CompanyModel::class)
            ->select('site_id, COUNT(*) AS total')
            ->whereIn('site_id', $siteIds)
            ->groupBy('site_id')
            ->findAll();

        $counts = [];
        foreach ($rows as $row) {
            $counts[(int) $row['site_id']] = (int) $row['total'];
        }

        return $counts;
    }

    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;
    }

    public function countCustomers(int $siteId): int
    {
        return (int) model(CompanyModel::class)->where('site_id', $siteId)->countAllResults();
    }
}
