<?php

$account = new class {

    public function __construct() {
        $this->deleteAccount();
        if( $_SERVER['REQUEST_METHOD'] != 'POST' ) return;
        $this->addAccount();
    }

    public function addAccount() {
        $accounts = Uss::$global['options']->get('bank:accounts');
        $new_account = strtolower($_POST['account']);
        if( in_array($new_account, $accounts) ) {
            Bank::log('info', 'The account already exist');
        } else {
            $accounts[] = $new_account;
            $insert = Uss::$global['options']->set('bank:accounts', $accounts);
            if( $insert ) {
                Bank::log('success', 'The account has been added');
            } else {
                Bank::log('error', 'The account could not be added');
            };
        }
    }

    public function printTable() {
        $accounts = Uss::$global['options']->get('bank:accounts');
        $tablet = new DOMTablet('account');
        $tablet->columns([
            'account' => 'account type',
            'action' => ''
        ]);
        $data = [];
        foreach( $accounts as $key => $value ) {
            $data[] = [
                'account' => ucwords($value),
                'key' => $key
            ];
        };
        $tablet->data( $data );
        $tablet->wrap();
        $tablet->prepare(function($data) {
            $data['action'] = "
                <a href='?remove={$data['key']}' data-uss-confirm='Please confirm the process' class='btn btn-danger'>
                    <i class='bi bi-trash'></i>
                </a>
            ";
            return $data;
        }, true);
    }

    private function deleteAccount() {
        $id = $_GET['remove'] ?? null;
        if( is_null($id) ) return;
        $accounts = Uss::$global['options']->get('bank:accounts');
        if( array_key_exists($id, $accounts) ) {
            unset($accounts[$id]);
            Uss::$global['options']->set('bank:accounts', $accounts);
        };  
    }       

};