<?php

namespace App\Utility;

class PasswordCreator {
    
    private $secret = "@hnis!hsk@nos";
    
    public function customEncryptionDecryption($value, $action) {
        $secret_key = $this->secret;
        if ($action == 'encrypt') {
            $value = $this->encrypt($value, $secret_key);
            return $value;
        } elseif ($action == 'decrypt') {

            
            return $this->decrypt($value, $secret_key);
        }
        return $value;
    }

    private function encrypt($data, $password) {
        if (empty($data)) {
            return $data;
        }
        $iv = substr(sha1(mt_rand()), 0, 16);
        $password = sha1($password);

        $salt = substr(sha1(mt_rand()), 0, 4);
        $saltWithPassword = hash('sha256', $password . $salt);

        $encrypted = openssl_encrypt(
                "$data", 'aes-256-cbc', "$saltWithPassword", null, $iv
        );
        $msg_encrypted_bundle = "$iv:$salt:$encrypted";
        return $msg_encrypted_bundle;
    }

    private function decrypt($msg_encrypted_bundle, $password) {
        if (empty($msg_encrypted_bundle)) {
            return $msg_encrypted_bundle;
        }
        $password = sha1($password);

        $components = explode(':', $msg_encrypted_bundle);
        if (count($components) < 3) {
            return $msg_encrypted_bundle;
        }

        $iv = $components[0] ?? '';
        $salt = $components[1] ?? '';
        $salt = hash('sha256', $password . $salt);
        $encrypted_msg = $components[2] ?? '';

        $decrypted_msg = openssl_decrypt(
                $encrypted_msg, 'aes-256-cbc', $salt, null, $iv
        );

        if ($decrypted_msg === false) {
            return $msg_encrypted_bundle;
        }

//        $msg = substr( $decrypted_msg, 41 );
        return $decrypted_msg;
    }

}
