<?php
namespace App\Controllers\Accounting;

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

class Deposits extends BaseController
{
    public function index()
    {
        $db = Database::connect();
        $rows = [];
        try {
            $rows = $db->table('bank_deposits')->orderBy('id','desc')->get()->getResultArray();
        } catch (\Throwable $e) { $rows = []; }
        return view('accounting/deposits/index', [
            'title' => lang('App.bank_deposits'),
            'rows' => $rows,
        ]);
    }

    public function create()
    {
        $db = Database::connect();
        $accounts = [];
        try {
            // Fetch postable accounts likely to be bank accounts
            $accounts = $db->table('chart_of_accounts')
                ->where('is_postable', 1)
                ->groupStart()
                    ->like('name_en', 'Bank', 'both')
                    ->orLike('name_ar', 'بنكي', 'both')
                    ->orLike('code', '102', 'after')
                ->groupEnd()
                ->orderBy('code','asc')
                ->get()->getResultArray();
        } catch (\Throwable $e) { $accounts = []; }
        $isArabic = (service('language')->getLocale() === 'ar');
        $accountList = [];
        foreach ($accounts as $a) {
            $name = $isArabic ? ($a['name_ar'] ?? $a['name_en']) : ($a['name_en'] ?? $a['name_ar']);
            $accountList[] = [
                'code' => $a['code'],
                'display' => trim(($a['code'] ?? '') . ' - ' . ($name ?? '')),
            ];
        }
        return view('accounting/deposits/form', [
            'title' => lang('App.bank_deposits'),
            'accounts' => $accountList,
        ]);
    }

    public function store()
    {
        $db = Database::connect();
        $req = $this->request;
        $date = trim((string) $req->getPost('date'));
        $account = trim((string) $req->getPost('bank_account'));
        $description = trim((string) $req->getPost('description'));
        $amount = (float) ($req->getPost('amount'));

        if ($date === '' || $account === '' || $amount <= 0) {
            return redirect()->back()->withInput();
        }

        $now = date('Y-m-d H:i:s');
        $db->transStart();
        try {
            $db->table('bank_deposits')->insert([
                'deposit_no' => null,
                'date' => $date,
                'bank_account_code' => $account,
                'description' => $description ?: null,
                'amount' => $amount,
                'created_at' => $now,
                'updated_at' => $now,
            ]);
            $id = (int) $db->insertID();
            if ($id > 0) {
                $depNo = 'BD-' . date('Ymd') . '-' . str_pad((string)$id, 4, '0', STR_PAD_LEFT);
                $db->table('bank_deposits')->where('id', $id)->update(['deposit_no' => $depNo, 'updated_at' => $now]);
                // Post to general ledger: Debit Bank, Credit Cash on Hand (1010)
                $db->table('general_ledger')->insert([
                    'entry_date' => $date,
                    'source_type' => 'Deposit',
                    'source_id' => $id,
                    'line_no' => 1,
                    'voucher_no' => $depNo,
                    'account_code' => $account,
                    'description' => $description ?: 'Bank Deposit',
                    'debit' => $amount,
                    'credit' => 0,
                    'created_at' => $now,
                ]);
                $db->table('general_ledger')->insert([
                    'entry_date' => $date,
                    'source_type' => 'Deposit',
                    'source_id' => $id,
                    'line_no' => 2,
                    'voucher_no' => $depNo,
                    'account_code' => '1010',
                    'description' => $description ?: 'Bank Deposit',
                    'debit' => 0,
                    'credit' => $amount,
                    'created_at' => $now,
                ]);
            }
        } catch (\Throwable $e) {
            // rollback on failure
        }
        $db->transComplete();

        return redirect()->to('/accounting/deposits');
    }
}

