<?php

namespace App\Models;

use CodeIgniter\Model;

class CategoryModel extends Model
{
    protected $table            = 'categories';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = true;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'user_id',
        'name',
        'is_active',
    ];
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    /**
     * Logical unique key is user_id + name among non-deleted rows.
     */
    public function findOwned(int $userId, int $categoryId): ?array
    {
        $row = $this->where('user_id', $userId)->find($categoryId);

        return $row === null ? null : $row;
    }

    public function nameExistsForUser(int $userId, string $name, ?int $exceptId = null): bool
    {
        $builder = $this->where('user_id', $userId)
            ->where('LOWER(name)', strtolower($name));
        if ($exceptId !== null) {
            $builder->where('id !=', $exceptId);
        }

        return $builder->first() !== null;
    }
}
