<?php
namespace App\Controllers\Accounting;

use App\Controllers\BaseController;
use Config\Database;

class Ledger extends BaseController
{
    public function index()
    {
        $db = Database::connect();
        $req = $this->request;
        $isArabic = (service('language')->getLocale() === 'ar');

        // Filters
        $accountCode = trim((string) ($req->getGet('account') ?? ''));
        $fromDate = trim((string) ($req->getGet('from') ?? ''));
        $toDate = trim((string) ($req->getGet('to') ?? ''));
        if ($fromDate === '') { $fromDate = date('Y-m-01'); }
        if ($toDate === '') { $toDate = date('Y-m-d'); }

        // Accounts for dropdown
        $accounts = [];
        try {
            $rows = $db->table('chart_of_accounts')->where('is_postable', 1)->orderBy('code','asc')->get()->getResultArray();
            foreach ($rows as $r) {
                $name = $isArabic ? ($r['name_ar'] ?? $r['name_en']) : ($r['name_en'] ?? $r['name_ar']);
                $accounts[] = [ 'code' => $r['code'], 'name' => $name ];
            }
        } catch (\Throwable $e) { $accounts = []; }

        // Build query for ledger entries
        $builder = $db->table('general_ledger')->select('*')->where('entry_date >=', $fromDate)->where('entry_date <=', $toDate)->orderBy('entry_date','asc')->orderBy('id','asc');
        if ($accountCode !== '') { $builder = $builder->where('account_code', $accountCode); }

        $entries = [];
        try { $entries = $builder->get()->getResultArray(); } catch (\Throwable $e) { $entries = []; }

        // Map account display and running balance if filtered single account
        $displayEntries = [];
        $running = 0.0;
        foreach ($entries as $i => $en) {
            $displayEntries[] = [
                'date' => $en['entry_date'] ?? null,
                'voucher_no' => $en['voucher_no'] ?? '',
                'source' => $en['source_type'] ?? '',
                'account_code' => $en['account_code'] ?? '',
                'description' => $en['description'] ?? '',
                'debit' => (float) ($en['debit'] ?? 0),
                'credit' => (float) ($en['credit'] ?? 0),
                'balance' => null,
            ];
            if ($accountCode !== '') {
                $running += ((float)($en['debit'] ?? 0)) - ((float)($en['credit'] ?? 0));
                $displayEntries[$i]['balance'] = $running;
            }
        }

        return view('accounting/ledger/index', [
            'title' => lang('App.ledger'),
            'accounts' => $accounts,
            'selected' => [ 'account' => $accountCode, 'from' => $fromDate, 'to' => $toDate ],
            'entries' => $displayEntries,
        ]);
    }
}
