<?php
namespace App\Models;

use CodeIgniter\Model;

class ChartOfAccountModel extends Model
{
    protected $table            = 'chart_of_accounts';
    protected $primaryKey       = 'id';
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;

    protected $allowedFields    = [
        'code', 'name_en', 'name_ar', 'type', 'parent_id', 'level',
        'is_postable', 'normal_balance', 'is_active'
    ];

    protected $useTimestamps    = true;
    protected $createdField     = 'created_at';
    protected $updatedField     = 'updated_at';

    protected $validationRules  = [
        'code' => 'required|min_length[3]|max_length[20]',
        'name_en' => 'required|min_length[3]|max_length[120]',
        'type' => 'required|in_list[Asset,Liability,Equity,Revenue,Expense]',
        'normal_balance' => 'required|in_list[Debit,Credit]',
        'is_postable' => 'permit_empty|in_list[0,1]',
        'is_active' => 'permit_empty|in_list[0,1]'
    ];

    protected $validationMessages = [];

    public function getTree()
    {
        $rows = $this->orderBy('code', 'ASC')->findAll();
        $byParent = [];
        foreach ($rows as $row) {
            $byParent[$row['parent_id'] ?? 0][] = $row;
        }
        $tree = [];
        $this->buildTree($tree, $byParent, 0);
        return $tree;
    }

    private function buildTree(array &$out, array $byParent, int $parentId)
    {
        if (!isset($byParent[$parentId])) return;
        foreach ($byParent[$parentId] as $row) {
            $row['children'] = [];
            $this->buildTree($row['children'], $byParent, (int)($row['id'] ?? 0));
            $out[] = $row;
        }
    }
}
