<?php

namespace Teknisa\Libs\Util;

class DelphiCrypt {
    private static function bround($num) {
        if (strpos($num, '.') === false)
            return $num;

        $num = $num;
        $num_arr = explode('.', $num);
        if (empty($num_arr[1])) return $num;
        if($num_arr[1] == 5) {
            if($num_arr[0] % 2) return $num_arr[0]+1;
            else return $num_arr[0];
        } else return round($num);
    }

    public static function encrypt($stString, $inOffset = 2) {
        $inTamanho = intval(strlen($stString));
        $inMeioAnt = intval($inTamanho/2);
        $inMeioPos = intval(self::bround(($inTamanho/2) + 0.1) + 1);

        $stVetor = $stString;

        for($byAux = 1; $byAux <= $inMeioAnt; $byAux++) {
            $chAux = $stVetor[$byAux-1];
            $stVetor[$byAux-1] = $stVetor[$byAux*2-1];
            $stVetor[$byAux*2-1] = $chAux;
        }
        
        for($byAux = $inTamanho; $byAux >= $inMeioPos; $byAux--) {
            $chAux = $stVetor[$byAux*2 - ($inTamanho + 1)-1];
            $stVetor[$byAux*2 - ($inTamanho + 1)-1] = $stVetor[$byAux-1];
            $stVetor[$byAux-1] = $chAux;
        }

        $stString = '';

        for($byAux = 1; $byAux <= $inTamanho; $byAux++) {
            $stString = $stString.(chr(ord($stVetor[$byAux-1]) + $inOffset));
        }

        return $stString;
    }

    public static function decrypt($stString, $inOffset = 2) {
        if($stString == null || $stString == ""){
            return null;
        }
        
        $inTamanho = intval(strlen($stString));
        $inMeioAnt = intval($inTamanho/2); 
        $inMeioPos = intval(self::bround(($inTamanho/2) + 0.1) + 1);

        $stVetor = $stString;

        for($byAux = $inMeioPos; $byAux <= $inTamanho; $byAux++) {
            $chAux = $stVetor[intval($byAux*2 - ($inTamanho + 1))-1];
            $stVetor[intval($byAux*2 - ($inTamanho + 1))-1] = $stVetor[intval($byAux)-1];
            $stVetor[intval($byAux)-1] = $chAux;
        }

        for($byAux = $inMeioAnt; $byAux >= 0; $byAux--) {
            $chAux = $stVetor[$byAux-1];
            $stVetor[$byAux-1] = $stVetor[$byAux*2-1];
            $stVetor[$byAux*2-1] = $chAux;
        }
        
        $stString = '';

        for($byAux = 1; $byAux <= $inTamanho; $byAux++) {
            $stString = $stString.(chr(ord($stVetor[$byAux-1]) - $inOffset));
        }

        return $stString;
    }

} 