<?php
class Balance extends controller
{
    public function index($id = '')
    {
        include_once "Bonus.php";

        try {
            $bonus = new Bonus();
            $revenue = $bonus->revenue($id);
            $balance = $bonus->balance($id);

            $topupdate = $this->DB->dbFetchColumn("SELECT topup_date FROM topup WHERE uid=? ORDER BY topup_date DESC LIMIT 1", [$id]);

            if ($topupdate) {
                $wdRequest = $this->DB->dbFetchColumn("SELECT SUM(amount) FROM withdraw WHERE bba_id=? AND withdraw_date>=? AND wd_status=?", [$id, $topupdate, 'request']);
                $wdPaid = $this->DB->dbFetchColumn("SELECT SUM(amount) FROM withdraw WHERE bba_id=? AND withdraw_date>=? AND wd_status=?", [$id, $topupdate, 'paid']);
            } else {
                $wdRequest = $this->DB->dbFetchColumn("SELECT SUM(amount) FROM withdraw WHERE bba_id=? AND wd_status=?", [$id, 'request']);
                $wdPaid = $this->DB->dbFetchColumn("SELECT SUM(amount) FROM withdraw WHERE bba_id=? AND wd_status=?", [$id, 'paid']);
            }

            $rw = $this->DB->dbFetchColumn("SELECT amount FROM register_wallet WHERE uid=?", [$id]);
            $rw= $rw?? 0;

            $wdRequest = $wdRequest ?? 0;
            $wdPaid = $wdPaid ?? 0;

            $cash_wallet = $balance * 0.8;
            $register_wallet = ($balance * 0.2) + $rw;

            echo json_encode([
                'revenue' => $revenue,
                'balance' => $balance,
                'cash_wallet' => number_format($cash_wallet, 2),
                'register_wallet' => number_format($register_wallet, 2),
                'roi' => number_format($wdPaid, 2),
                'wd_request' => number_format($wdRequest, 2),
                'date' => (new DateTime('now'))->format("d M Y")
            ]);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
}
