<?php

namespace App\Models;

use CodeIgniter\Model;

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

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

    protected $validationRules = [
        'name'   => 'required|min_length[2]|max_length[150]',
        'code'   => 'required|max_length[30]',
        '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('city', $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
    {
        $builder = $this->where('code', strtoupper($code));
        if ($excludeId) {
            $builder->where('id !=', $excludeId);
        }

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