<?php
namespace lib;
if(!defined('ACCESS_CONTROL')) {header($_SERVER['SERVER_PROTOCOL']. ' 404'); exit('404 not found');}
use lib\Config;

class RC4{

    protected $_key;

    function __construct($key){
        $this->_key = $key;
    }

    public static function factory($key = null){

        return is_null($key) ? new RC4(Config::read('rc4_key')) : new RC4($key);
    }

    public function rc4($data, $key) {
        $hash        = array();
        $box         = array();
        $ret         = '';

        $key_length  = strlen($key);
        $data_length = strlen($data);

        for($x = 0; $x < 256; $x++)
        {
            $hash[$x] = ord($key[$x % $key_length]);
            $box[$x]  = $x;
        }

        for($y = $x = 0; $x < 256; $x++)
        {
            $y       = ($y + $box[$x] + $hash[$x]) % 256;
            $tmp     = $box[$x];
            $box[$x] = $box[$y];
            $box[$y] = $tmp;
        }

        for($z = $y = $x = 0; $x < $data_length; $x++)
        {
            $z = ($z + 1) % 256;
            $y = ($y + $box[$z]) % 256;

            $tmp     = $box[$z];
            $box[$z] = $box[$y];
            $box[$y] = $tmp;

            $k       = $box[(($box[$z] + $box[$y]) % 256)];
            $ret    .= chr(ord($data[$x]) ^ $k);
        }

        return $ret;
    }

    public function encode_bot_response($string)
    {
        return base64_encode($this->rc4($string, $this->_key));
    }

    public function decode_bot_request($string)
    {
        $str = $this->rc4(base64_decode(str_replace("_", "+", str_replace("\\", "-", $string))), $this->_key);
        parse_str($str, $return);
        return $return;
    }
}
