<?php
class Activation extends controller
{
    public function index($bba = '')
    {
        $data = [];
        $obj = $this->DB->dbFetchAll("SELECT T.*, DATE_FORMAT(T.transfer_date, '%d-%m-%Y %H:%i') AS transfer_date, CONCAT('$',T.amount) AS amount, P.usd, P.package FROM activation AS T JOIN (package AS P) ON (T.package_id=P.package_id) ORDER BY T.transfer_date ASC");

        foreach ($obj as $val) {
            $data[] = $val;
        }

        echo json_encode($data);
    }

    private function generateUID()
    {
        $id = "";
        for ($i = 0; $i < 5; $i++)
            $id .= rand(0, 9);
        $uid = $this->DB->dbFetchObject("SELECT uid FROM member WHERE uid=?", [$id]);
        if ($uid)
            $this->generateUID();
        else return 'BBAAI-' . $id;
    }

    private function checkBBA($bba)
    {
        $bba_address = $this->DB->dbFetchColumn("SELECT COUNT(*) FROM member WHERE bba_address=?", [$bba]);
        return $bba_address ? false : true;
    }

    private function cekID($id)
    {
        $uid = $this->DB->dbFetchColumn("SELECT uid FROM member WHERE uid=?", [$id]);
        if ($uid) return ['status' => true];
        else {
            return [
                'status' => false,
                'message' => 'ID not available'
            ];
        }
    }

    private function cekFoot($id, $foot)
    {
        $tot = $this->DB->dbFetchColumn("SELECT COUNT(*) FROM member WHERE upline_id=?", [$id]);
        if ($tot < 2) {
            $uid = $this->DB->dbFetchColumn("SELECT uid FROM member WHERE upline_id=? AND foot=?", [$id, $foot]);
            if ($uid) {
                return [
                    'status' => false,
                    'message' => "Position $foot not available"
                ];
            } else
                return ['status' => true];
        } else {
            return [
                'status' => false,
                'message' => "Error Placement, max 2 branch on Upline"
            ];
        }
    }

    private function checkNode($sponsor_id, $upline_id, $foot)
    {
        if ($upline_id == 'TOP' && $sponsor_id == 'TOP') return true;
        else {
            $sponsor = $this->cekID($sponsor_id);
            $upline = $this->cekID($upline_id);
            $placement = $this->cekFoot($upline_id, $foot);

            if ($sponsor['status'] && $upline['status'] && $placement['status']) {
                return ['status' => true];
            } else {
                return !$sponsor['status'] || !$upline['status'] ? $sponsor : $placement;
            }
        }
    }


    private function generateReferralHash($str)
    {
        $code = strtolower(substr(md5($str . 'pegasusbitbossai'), 0, 16));

        $tot = $this->DB->dbFetchColumn("SELECT COUNT(*) FROM member WHERE refferal_left=? OR refferal_right=?", [$code, $code]);

        if ($tot) $this->generateReferralHash(uniqid());

        return $code;
    }

    private function checkAvailableFoot($id, $foot)
    {
        $uid = null;
        $obj = $this->DB->dbFetchObject("SELECT uid FROM member WHERE upline_id=? AND foot=?", [$id, $foot]);

        if ($obj && $obj->uid) $val = $this->checkAvailableFoot($obj->uid, $foot);

        $uid = $val ? $val : ($obj->uid ?? $id);

        return $uid;
    }

    public function approve()
    {
        $data = [];

        $bba_address = $_POST['bba_address'];
        $account_type = $_POST['account_type'];

        $obj = $this->DB->dbFetchObject("SELECT * FROM approval_activation WHERE bba_address=? AND paid_confirm=?", [$bba_address, true]);

        if ($obj) {
            $ref = $obj->refferal;
            $package = $obj->package;
            $name = $obj->name;

            $refferal = $this->DB->dbFetchObject("SELECT * FROM member WHERE refferal_left=? OR refferal_right=?", [$ref, $ref]);
            if ($refferal) {
                $sponsor = $refferal->uid;
                $foot = ($ref == $refferal->refferal_left) ? 'Left' : 'Right';

                $upline = $this->checkAvailableFoot($sponsor, $foot);

                if ($this->checkBBA($bba_address)) {
                    $status = $this->checkNode($sponsor, $upline, $foot);

                    if ($status['status']) {
                        $id = $this->generateUID();
                        $refLeft = $this->generateReferralHash(uniqid());
                        $refRight = $this->generateReferralHash(uniqid());

                        try {
                            $this->DB->dbQuery(
                                "INSERT INTO member (uid, account_type, bba_address, package_id, sponsor_id, upline_id, foot, name, registration_date, refferal_right, refferal_left, input_by) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
                                [
                                    $id,
                                    $account_type,
                                    $bba_address,
                                    $package,
                                    $sponsor,
                                    $upline,
                                    $foot,
                                    $name,
                                    date("Y-m-d H:i:s"),
                                    $refLeft,
                                    $refRight,
                                    'admin@bitboss.ai'
                                ]
                            );

                            $this->DB->dbQuery("UPDATE approval_activation SET approve=?, approve_date=? WHERE bba_address=?", [true, date("Y-m-d H:i:s"), $bba_address]);
                            $data = [
                                'status' => true,
                                'message' => 'Register success'
                            ];
                        } catch (PDOException $e) {
                            $data = [
                                'status' => false,
                                'message' => $e->getMessage() . '=' . $upline
                            ];
                        }
                    } else
                        $data = $status;
                } else {
                    $data = [
                        'status' => false,
                        'message' => 'BBA Address already exist'
                    ];
                }
            }
        }

        echo json_encode($data);
    }

    public function reject()
    {
        try {
            $this->DB->dbQuery("DELETE FROM approval_activation WHERE bba_address=?", [$_POST['bba_address']]);
            echo json_encode(['status' => true, 'message' => 'Delete transaction success']);
        } catch (Exception $e) {
            echo json_encode(['status' => false, 'message' => $e->getMessage()]);
        }
    }
}
