<?php

defined("BANK_DIR") OR DIE;

new class {

    private $user;

    public function __construct() {

        if($_SERVER['REQUEST_METHOD'] != 'POST' ) return;

        $this->user = Uss::$global['user'];

        array_walk_recursive($_POST, function(&$value) {
            $value = trim($value);
        });

        if( $_POST['type'] == 'password' ) {

            # handle password
            $this->handlePassword();

        } else {
            
            # handle pin
            $this->handlePin(); 

        };

    }

    public function handlePassword() {

        $is_valid_password = Udash::password($_POST['old_password'], $this->user['password']);

        if( !$is_valid_password ) {
            return Uss::console('@alert', "Sorry! Old password is wrong");
        };

        $same_password = $_POST['new_password'] === $_POST['confirm_password'];

        if( !$same_password ) {
            return Uss::console('@alert', "Oops! Password does not match");
        };

        $password = Udash::password( $_POST['new_password'] );

        $SQL = SQuery::update( DB_TABLE_PREFIX . "_users", array(
            "password" => $password
        ), "id = {$this->user['id']}");

        $updated = Uss::$global['mysqli']->query( $SQL );

        if( $updated ) {

            // Update Session
            Udash::setAccessToken( $this->user['id'] );

            // Show Succes Message
            Uss::console('@alert', "Your password was successfully updated!");

        } else {

            Uss::console('@alert', "Password update failed");

        };

    }

    public function handlePin() {

        foreach( ['old_pin', 'new_pin'] as $key ) {
            if( !preg_match("/^\\d{4}$/", $_POST[$key]) ) {
                Uss::console('@alert', "Invalid Pin Pattern! <br> Pin can only contain 4 digits");
                return;
            }
        };

        $userinfo = Uss::$global['usermeta']->get("bank:info", $this->user['id']);
        $userpin = $userinfo['security']['pin'];

        if( $_POST['old_pin'] !== $userpin ) {

            return Uss::console('@alert', "Sorry! The old pin is incorrect");

        } else if( $_POST['new_pin'] != $_POST['confirm_pin'] ) {

            return Uss::console("@alert", "Oops! The pin does not match");

        };

        $userinfo['security']['pin'] = $_POST['new_pin'];

        $update = Uss::$global['usermeta']->set("bank:info", $userinfo, $this->user['id']);

        if( !$update ) Uss::console('@alert', "Sorry! The pin could not be updated");
        else {
            Uss::console('@alert', "The pin was successfully updated");
        };

    }

};