<?php
declare(strict_types=1);

namespace App\Modules\Accounting\Models;

use App\Core\Model;

class CostCenter extends Model
{
    protected static string $table = 'cost_centers';
    protected static array $fillable = [
        'code', 'name_ar', 'name_en', 'type', 'branch_id',
        'parent_id', 'is_active', 'description',
    ];
    protected static bool $timestamps = true;
    protected static bool $softDelete = true;

    public static function findByCode(string $code): ?static
    {
        $row = static::query()->where('code', '=', $code)->where('is_archived', '=', 0)->first();
        if ($row === null) {
            return null;
        }
        $instance = new static($row);
        $instance->exists = true;
        return $instance;
    }

    public static function getActive(): array
    {
        return static::query()
            ->where('is_active', '=', 1)
            ->where('is_archived', '=', 0)
            ->orderBy('code', 'ASC')
            ->get();
    }

    public static function findByBranch(int $branchId): ?static
    {
        $row = static::query()
            ->where('branch_id', '=', $branchId)
            ->where('is_archived', '=', 0)
            ->first();
        if ($row === null) {
            return null;
        }
        $instance = new static($row);
        $instance->exists = true;
        return $instance;
    }
}
