<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = ['branch_id', 'name', 'manager_id', 'status'];

    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, ?int $branchId = null): self
    {
        if ($search) {
            $this->like('name', $search);
        }

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

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

        return $this;
    }

    public function optionsForSelect(?int $branchId = null): array
    {
        $builder = $this->where('status', 'active')->orderBy('name', 'ASC');
        if ($branchId !== null) {
            $builder = $builder->where('branch_id', $branchId);
        }

        return array_column($builder->findAll(), 'name', 'id');
    }
}
