<?php

// you may change these values to your own
$secret_key = 'my_simple_secret_key';
$secret_iv = 'my_simple_secret_iv';

function encrypt_array( $string, $action = 'e' ) {

    global $secret_key;
    global $secret_iv;
    if( is_array($string) || gettype($string) == object ){
      $string = serialize($string);
    }
    $output = false;
    $encrypt_method = "AES-256-CBC";
    $key = hash( 'sha256', $secret_key );
    $iv = substr( hash( 'sha256', $secret_iv ), 0, 16 );

    if( $action == 'e' ) {
        $output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $iv ) );
    }
    else if( $action == 'd' ){
        $output1 = openssl_decrypt( base64_decode( $string ), $encrypt_method, $key, 0, $iv );
        $output = unserialize($output1);
    }

    return $output;
}


function encrypt_string( $string, $action = 'e' ) {
    global $secret_key;
    global $secret_iv;
    $output = false;
    $encrypt_method = "AES-256-CBC";
    $key = hash( 'sha256', $secret_key );
    $iv = substr( hash( 'sha256', $secret_iv ), 0, 16 );

    if( $action == 'e' ) {
        $output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $iv ) );
    }
    else if( $action == 'd' ){
        $output = openssl_decrypt( base64_decode( $string ), $encrypt_method, $key, 0, $iv );
    }
      return $output;
}


function generateToken($key){
    session_start();
    return  $_SESSION[$key] = base64_encode( openssl_random_pseudo_bytes(32) ) ;
}

function checkToken($key,$token){
    session_start();
        if( $token === $_SESSION[$key] ){
            unset($_SESSION[$key]);
            return true;    
        }
    
    return false;
}

function checkTokenMyAccount($key,$token){
    session_start();
    
        if( $token === $_SESSION[$key] ){
          
            return true;    
    }
    
    return false;
}

function payloadToken($array){
    // Create token header as a JSON string
        $header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);

        // Create token payload as a JSON string
        $payload = json_encode($array);

        // Encode Header to Base64Url String
        $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));

        // Encode Payload to Base64Url String
        $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));

        // Create Signature Hash
        $signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, strtotime( date('Y-m-d H:i:s') ), true);

        // Encode Signature to Base64Url String
        $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));

        // Create JWT
        return $jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;

        
}