<?php

class token_unique {

    private static $__instance = null;
    private static $__tmp_tokens = array();

    //we put it private to prevent initiation with outer code
    private function __construct() {
        
    }

    public static function generate_token($prefix) {
        $unique_id = 'trusto_' . $prefix . '_' . uniqid() . '_' . microtime(true);
        smc_session()['duplicate_check'][$unique_id] = true;
        return $unique_id;
    }

    public static function duplicate_msg() {
        return CommonLanguage::getMessage('duplicate_record');
    }

    public static function is_valid_token($token_name = 'unique_id') {
        $error_arr = array();
        $submitted_token = empty($_POST[$token_name]) ? null : $_POST[$token_name];
        if (empty($submitted_token) || empty(smc_session()['default_setting']['is_production']))
            return $error_arr;
        if (!isset(smc_session()['duplicate_check'][$submitted_token])) {
            $error_arr[0] = self::duplicate_msg();
            return $error_arr;
        }
        //we must unset it directly at load to prevent multi submit, specially if submit and insert ft. is taking time
        unset(smc_session()['duplicate_check'][$submitted_token]);
        //now we put it on a temp var. so in case of success it is already unset 
        //but in case of error we set it again in the destruct class
        self::$__tmp_tokens[$submitted_token] = true;
        //we initialize the class to load the destuct automatic, we need to call the 
        //destruct automatic so in case of error to automatic set token in session again
        if (is_null(self::$__instance))
            self::$__instance = new self();
        //
        return $error_arr;
    }

    //in case of success to remove the token from session and temp. variable
    public static function remove_token($token_name = 'unique_id') {
        $submitted_token = empty($_POST[$token_name]) ? null : $_POST[$token_name];
        if (empty($submitted_token))
            return;
        if (isset(smc_session()['duplicate_check'][$submitted_token]))
            unset(smc_session()['duplicate_check'][$submitted_token]);
        if (isset(self::$__tmp_tokens[$submitted_token]))
            unset(self::$__tmp_tokens[$submitted_token]);
    }

    public function __destruct() {
        foreach (self::$__tmp_tokens as $token => $tmp_val)
            smc_session()['duplicate_check'][$token] = true;
    }

}
