<?php
namespace App\Controllers\Accounting;

use App\Controllers\BaseController;
use App\Models\ChartOfAccountModel;
use CodeIgniter\I18n\Time;

class ChartOfAccounts extends BaseController
{
    public function index()
    {
        $model = new ChartOfAccountModel();
        $q = trim($this->request->getGet('q') ?? '');
        $builder = $model->orderBy('code','ASC');
        if ($q !== '') {
            $builder = $builder->like('code', $q)->orLike('name_en', $q)->orLike('name_ar', $q);
        }
        $accounts = $builder->findAll();

        return view('accounting/accounts/index', [
            'title' => lang('App.chart_of_accounts'),
            'accounts' => $accounts,
            'query' => $q,
        ]);
    }

    public function create()
    {
        return view('accounting/accounts/form', [
            'title' => lang('App.add_account'),
            'account' => null,
            'errors' => [],
            'types' => ['Asset','Liability','Equity','Revenue','Expense'],
            'normalBalances' => ['Debit','Credit'],
            'parents' => (new ChartOfAccountModel())->orderBy('code','ASC')->findAll(),
        ]);
    }

    public function store()
    {
        $data = $this->request->getPost([
            'code','name_en','name_ar','type','parent_id','is_postable','normal_balance','is_active'
        ]);
        $data['level'] = 1; // simplified
        $data['parent_id'] = $data['parent_id'] ?: null;
        $data['is_postable'] = (int)($data['is_postable'] ?? 1);
        $data['is_active'] = (int)($data['is_active'] ?? 1);

        $model = new ChartOfAccountModel();
        if (!$model->insert($data)) {
            return view('accounting/accounts/form', [
                'title' => lang('App.add_account'),
                'account' => null,
                'errors' => $model->errors(),
                'types' => ['Asset','Liability','Equity','Revenue','Expense'],
                'normalBalances' => ['Debit','Credit'],
                'parents' => $model->orderBy('code','ASC')->findAll(),
            ]);
        }
        return redirect()->to('/accounting/accounts');
    }

    public function edit(int $id)
    {
        $model = new ChartOfAccountModel();
        $account = $model->find($id);
        if (!$account) return redirect()->to('/accounting/accounts');
        return view('accounting/accounts/form', [
            'title' => lang('App.edit_account'),
            'account' => $account,
            'errors' => [],
            'types' => ['Asset','Liability','Equity','Revenue','Expense'],
            'normalBalances' => ['Debit','Credit'],
            'parents' => $model->orderBy('code','ASC')->findAll(),
        ]);
    }

    public function update(int $id)
    {
        $data = $this->request->getPost([
            'code','name_en','name_ar','type','parent_id','is_postable','normal_balance','is_active'
        ]);
        $data['parent_id'] = $data['parent_id'] ?: null;
        $data['is_postable'] = (int)($data['is_postable'] ?? 1);
        $data['is_active'] = (int)($data['is_active'] ?? 1);

        $model = new ChartOfAccountModel();
        if (!$model->update($id, $data)) {
            $account = $model->find($id);
            return view('accounting/accounts/form', [
                'title' => lang('App.edit_account'),
                'account' => $account,
                'errors' => $model->errors(),
                'types' => ['Asset','Liability','Equity','Revenue','Expense'],
                'normalBalances' => ['Debit','Credit'],
                'parents' => $model->orderBy('code','ASC')->findAll(),
            ]);
        }
        return redirect()->to('/accounting/accounts');
    }
}
