<?php

# Validate Bank Data;

Events::addListener('udash:ajax', function() {

    if( $_POST['route'] != 'ud-signup' ) return;

    $bank = $_POST['bank'];

    if( $bank['security']['pin'] != $bank['security']['confirm_pin'] ) {

        $message = "Security Pin does not match";

    } else {

        $regexp = "/^[a-z0-9_\-\s]+$/i";
        
        $not_required = [
            'phone'
        ];

        foreach( ['bio', 'address', 'nok', 'system'] as $group ) {

            if( in_array($group, ['nok']) ) {
                continue;
            };
            
            foreach( $bank[ $group ] as $key => $value ) {

                # Ignore unrequired fields;

                if( in_array($key, $not_required) ) continue;

                if( !preg_match( $regexp, trim($value)) ) {
                    $message = "{$key} is not valid";
                    break(2);
                };

            };

        };

    };

    // If error! Stop script;

    if( !empty($message) ) {
        Uss::exit(ucfirst( $message ), false);
    };
    
    unset($bank['security']['confirm_pin']);

    $_POST['bank'] = $bank;

}, "ajax-before-signup");


# User Signed Up;

Events::addListener("udash:ajax/signup", function($result) {
        
    if( !$result['status'] ) return;

    $user = $result['user'];

    Bank::setUserMeta( $user['id'] );

    Uss::$global['usermeta']->set( 'bank:info', $_POST['bank'], $user['id'] );

});