<?php

namespace frontend\controllers;

use Yii;
use common\models\CargoEventLog;
use common\models\CargoEventLogSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * AppController implements the CRUD actions for CargoEventLog model.
 */
class AppController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all CargoEventLog models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new CargoEventLogSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single CargoEventLog model.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new CargoEventLog model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new CargoEventLog();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model-> Id]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing CargoEventLog model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model-> Id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing CargoEventLog model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the CargoEventLog model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return CargoEventLog the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = CargoEventLog::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }

    public function actionApp_event() {

        date_default_timezone_set('UTC');
//        $date = date('Y-m-d H:i:s', time());

        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');    // cache for 1 day
        }

        // Access-Control headers are received during OPTIONS requests
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
                header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
                header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
            exit(0);
        }

        $postdata = file_get_contents("php://input");
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $request = json_decode($postdata);
            if(!is_null($request)){
                $date = date('Y-m-d H:i:s', strtotime($request->date) + 60*60);
                if($request->event == "login") {
                    $userModel = \common\models\UserApp::find()->where('Usuario =:user', [':user'=> $request->username])->one();
                    if(!is_null($userModel)) {
                        if($this->decode($userModel->Password) == $request->password){
                            $event = new CargoEventLog();
                            $event->EventCategory = "sistema";
                            $event->EventType = "Iniciar sesion";
                            $event->UserId = $userModel->id;
                            $event->Date = date('Y-m-d H:i:s', strtotime($request->date));
                            $event->Latitude = $request->latitude;
                            $event->Longitude = $request->longitude;
                            $event->Altitude = $request->altitude;
                            if($event->save()) {
                                $user = array(
                                    'Id'=>$userModel->id,
                                    'Nombre'=>$userModel->Nombre,
                                    'Username'=>$userModel->Usuario,
                                    'Password'=> $this->decode($userModel->Password)
                                );
                                $unitModel = \common\models\Unit::find()->where('BranchId =:branch AND KindId =:kind', [':branch'=>20, ':kind'=>9])->all();
                                $units = array();
                                if(!is_null($unitModel)) {
                                    foreach ($unitModel as $unit) {
                                        array_push($units, ['Id'=>$unit->Id, 'EconomicNumber'=>$unit->EconomicNumber, 'UnitOwner'=>'propio']);
                                    }
                                }
                                $providerModel = \common\models\ProviderApp::find()->all();
                                $providers = array();
                                if(!is_null($providerModel)) {
                                    foreach ($providerModel as $provider) {
                                        array_push($providers, ['Id'=>$provider->Id, 'Name'=>$provider->Alias]);
                                    }
                                }
                                $branchModel = \common\models\Branch::find()->where('CustomerId =:customer', [':customer'=>35])->all();
                                $branches = array();
                                if(!is_null($branchModel)) {
                                    foreach($branchModel as $branch) {
                                        array_push($branches, ['Id'=>$branch->Id, 'Name'=>$branch->Name]);
                                    }
                                }
                              //  echo json_encode(array('value'=>1, 'mesage'=>'Inicio de sesion correcto', 'user'=>$user, 'units'=>$units, 'providers'=>$providers, 'branches'=>$branches));
                               return json_encode(array('value'=>1, 'mesage'=>'Inicio de sesion correcto', 'user'=>$user, 'units'=>$units, 'providers'=>$providers, 'branches'=>$branches));
                            //  \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                             //\Yii::$app->response->data  =  $data;
                            } else {
                                echo json_encode(array('value'=>3, 'mesage'=>'Se produjo un error intente de nuevo'));
                            }
                        } else {
                            echo json_encode(array('value'=>2, 'mesage'=>'La contraseña es incorrecta. Favor de verificarla'));
                        }
                    } else {
                        echo json_encode(array('value'=>3, 'mesage'=>'No se encontro el usuario verifique los datos'));
                    }
                } else if($request->event == "logout") {
                    $event = new CargoEventLog();
                    $event->EventCategory = "sistema";
                    $event->EventType = "Cerrar sesion";
                    $event->UserId = $request->userId;
                    $event->Unit = $request->unit;
                    $event->UnitOwner = $request->unitOwner;
                    $event->Date = date('Y-m-d H:i:s', strtotime($request->date));
                    $event->Latitude = $request->latitude;
                    $event->Longitude = $request->longitude;
                    $event->Altitude = $request->altitude;
                    if($event->save()) {
                        echo json_encode(array('value'=>1, 'mesage'=>'Cierre de sesion correcto'));
                    } else {
                        echo json_encode(array('value'=>0, 'mesage'=>'Se produjo un error intente de nuevo'));
                    }
                } else if($request->event == "pickunit") {
                    $event = new CargoEventLog();
                    $event->EventCategory = "sistema";
                    $event->EventType = "Seleccionar unidad";
                    $event->UserId = $request->userId;
                    $event->Unit = $request->unit;
                    $event->UnitOwner = $request->unitOwner;
                    $event->Date = date('Y-m-d H:i:s', strtotime($request->date));
                    $event->Latitude = $request->latitude;
                    $event->Longitude = $request->longitude;
                    $event->Altitude = $request->altitude;
                    if($event->save()) {
                        echo json_encode(array('value'=>1, 'mesage'=>'Seleccion de unidad correcto'));
                    } else {
                        echo json_encode(array('value'=>0, 'mesage'=>'Se produjo un error intente de nuevo'));
                    }
                } else if($request->event == "up") {
                    $containerUp;
                    if(strlen($request->containerUCode) > 5) {
                        $containerUp = \common\models\Unit::find()->where('`Order` =:order', [':order'=> $request->containerUCode])->one();
                    } else {
                        $containerUp = \common\models\Unit::find()->where('`EconomicNumber` =:ecoN', [':ecoN'=> $request->containerUCode])->one();
                    }
                    $destiny = $request->destiny;
                    if($destiny == "Patio") {
                        $destiny = $request->branch;
                    }
                    if(!is_null($containerUp)){
                        $event = new CargoEventLog();
                        $event->EventCategory = "maniobra";
                        $event->EventType = "Subir";
                        $event->UserId = $request->userId;
                        $event->Destiny = $destiny;
                        $event->Unit = $request->unit;
                        $event->UnitOwner = $request->unitOwner;
                        $event->ContainerUId = $containerUp->Id;
                        $event->ProviderId = $destiny == "Proveedor" ? $request->providerId : "";
                        $event->Date = date('Y-m-d H:i:s', strtotime($request->date));
                        $event->Latitude = $request->latitude;
                        $event->Longitude = $request->longitude;
                        $event->Altitude = $request->altitude;
                        $event->FirstData = $request->firstData ? $request->firstData : "";
                        $event->SecondData = $request->secondData ? $request->secondData : "";
                        $event->FirstPicture = $request->firstPicture ? $request->firstPicture : "";
                        $deviceUp = \common\models\Device::findOne($containerUp->DeviceId);
                        $equipoUp = \common\models\Equipos::find()->where('eqId =:id', [':id'=> $deviceUp->TerminalId])->one();
                        $deviceUp->Latitude = $request->latitude;
                        $deviceUp->Longitude = $request->longitude;
                        $deviceUp->Altitude = $request->altitude;
                        $deviceUp->ReportDate = $date;
                        $equipoUp->eqLatitud = $request->latitude;
                        $equipoUp->eqLongitud = $request->longitude;
                        $equipoUp->eqAltitud = $request->altitude;
                        $equipoUp->eqFechaActEq = $date;
                        $equipoUp->eqFechaActSer = $date;
                        $containerUp->OperativeStatusId = 1;

                        if($containerUp->save() && $event->save() && $deviceUp->save() && $equipoUp->save()) {
                            echo json_encode(array('value'=>1, 'mesage'=>'Registro de evento correcto', 'container'=>$containerUp->Order));
                        } else {
//                            print_r($deviceUp->errors);
//                            return;
                            echo json_encode(array('value'=>0, 'mesage'=>'Se produjo un error intente de nuevo'));
                        }
                    } else {
                        echo json_encode(array('value'=>0, 'mesage'=>'El contenedor no se encuentra registrado'));
                    }
                } else if($request->event == "down") {
                    $containerDown = \common\models\Unit::find()->where('`Order` =:order', [':order'=>$request->containerDCode])->one();
                    $destiny = $request->destiny;
                    if($destiny == "Patio") {
                        $destiny = $request->branch;
                    }
                    $event = new CargoEventLog();
                    $event->EventCategory = "maniobra";
                    $event->EventType = "Bajar";
                    $event->UserId = $request->userId;
                    $event->Destiny = $destiny;
                    $event->Unit = $request->unit;
                    $event->UnitOwner = $request->unitOwner;
                    $event->ContainerDId = $containerDown->Id;
                    $event->ProviderId = $destiny == "Proveedor" ? $request->providerId : "";
                    $event->Date = date('Y-m-d H:i:s', strtotime($request->date));
                    $event->Latitude = $request->latitude;
                    $event->Longitude = $request->longitude;
                    $event->Altitude = $request->altitude;
                    $event->FirstData = $request->firstData ? $request->firstData : "";
                    $event->SecondData = $request->secondData ? $request->secondData : "";
                    $event->FirstPicture = $request->firstPicture ? $request->firstPicture : "";
                    $deviceDown = \common\models\Device::findOne($containerDown->DeviceId);
                    $equipoDown = \common\models\Equipos::find()->where('eqId =:id', [':id'=> $deviceDown->TerminalId])->one();
                    $deviceDown->Latitude = $request->latitude;
                    $deviceDown->Longitude = $request->longitude;
                    $deviceDown->Altitude = $request->altitude;
                    $deviceDown->ReportDate = $date;
                    $equipoDown->eqLatitud = $request->latitude;
                    $equipoDown->eqLongitud = $request->longitude;
                    $equipoDown->eqAltitud = $request->altitude;
                    $equipoDown->eqFechaActEq = $date;
                    if($request->destiny == "Proveedor"){
                        $containerDown->OperativeStatusId = 2;
                    } else if($request->destiny == "Mantenimiento") {
                        $containerDown->OperativeStatusId = 3;
                    } else if($request->destiny == "Patio") {
                        $containerDown->OperativeStatusId = 4;
                    }
                    if($event->save() && $containerDown->save() && $deviceDown->save() && $equipoDown->save()) {
                        echo json_encode(array('value'=>1, 'mesage'=>'Registro de evento correcto'));
                    } else {
                        echo json_encode(array('value'=>0, 'mesage'=>'Se produjo un error intente de nuevo'));
                    }
                } else if($request->event == "change") {
                    $containerUp;
                    if(strlen($request->containerUCode) > 5) {
                        $containerUp = \common\models\Unit::find()->where('`Order` =:order', [':order'=> $request->containerUCode])->one();
                    } else {
                        $containerUp = \common\models\Unit::find()->where('`EconomicNumber` =:ecoN', [':ecoN'=> $request->containerUCode])->one();
                    }
                    $containerDown = \common\models\Unit::find()->where('`Order` =:order', [':order'=>$request->containerDCode])->one();
                    $destiny = $request->destiny;
                    if($destiny == "Patio") {
                        $destiny = $request->branch;
                    }
                    if(!is_null($containerUp)){
                        $event = new CargoEventLog();
                        $event->EventCategory = "maniobra";
                        $event->EventType = "Cambio";
                        $event->UserId = $request->userId;
                        $event->Destiny = $destiny;
                        $event->Unit = $request->unit;
                        $event->UnitOwner = $request->unitOwner;
                        $event->ContainerDId = $containerDown->Id;
                        $event->ContainerUId = $containerUp->Id;
                        $event->ProviderId = $destiny == "Proveedor" ? $request->providerId : "";
                        $event->Date = date('Y-m-d H:i:s', strtotime($request->date));
                        $event->Latitude = $request->latitude;
                        $event->Longitude = $request->longitude;
                        $event->Altitude = $request->altitude;
                        $event->FirstData = $request->firstData ? $request->firstData : "";
                        $event->SecondData = $request->secondData ? $request->secondData : "";
                        $event->FirstPicture = $request->firstPicture ? $request->firstPicture : "";
                        $event->SecondPicture = $request->secondPicture ? $request->secondPicture : "";
                        $event->ThirdPicture = $request->thirdPicture ? $request->thirdPicture : "";
                        $deviceUp = \common\models\Device::findOne($containerUp->DeviceId);
                        $equipoUp = \common\models\Equipos::find()->where('eqId =:id', [':id'=> $deviceUp->TerminalId])->one();
                        $deviceDown = \common\models\Device::findOne($containerDown->DeviceId);
                        $equipoDown = \common\models\Equipos::find()->where('eqId =:id', [':id'=> $deviceDown->TerminalId])->one();
                        $deviceUp->Latitude = $request->latitude;
                        $deviceUp->Longitude = $request->longitude;
                        $deviceUp->Altitude = $request->altitude;
                        $deviceUp->ReportDate = $date;
                        $equipoUp->eqLatitud = $request->latitude;
                        $equipoUp->eqLongitud = $request->longitude;
                        $equipoUp->eqAltitud = $request->altitude;
                        $equipoUp->eqFechaActEq = $date;
                        $deviceDown->Latitude = $request->latitude;
                        $deviceDown->Longitude = $request->longitude;
                        $deviceDown->Altitude = $request->altitude;
                        $deviceDown->ReportDate = $date;
                        $equipoDown->eqLatitud = $request->latitude;
                        $equipoDown->eqLongitud = $request->longitude;
                        $equipoDown->eqAltitud = $request->altitude;
                        $equipoDown->eqFechaActEq = $date;
                        if($request->destiny == "Proveedor"){
                            $containerDown->OperativeStatusId = 2;
                        } else if($request->destiny == "Patio") {
                            $containerDown->OperativeStatusId = 4;
                        }
                        $containerUp->OperativeStatusId = 1;
                        if($event->save() && $containerDown->save() && $containerUp->save() && $deviceDown->save() && $deviceUp->save() && $equipoDown->save() && $equipoUp->save()) {
                            echo json_encode(array('value'=>1, 'mesage'=>'Registro de evento correcto', 'container'=>$containerUp->Order));
                        } else {
                            echo json_encode(array('value'=>0, 'mesage'=>'Se produjo un error intente de nuevo'));
                        }
                    } else {
                        echo json_encode(array('value'=>0, 'mesage'=>'El contenedor a subir no se encuentra registrado'));
                    }
                } else if($request->event == "pickup") {
                    $containerDown;
                    if(strlen($request->containerDCode) > 5) {
                        $containerDown = \common\models\Unit::find()->where('`Order` =:order', [':order'=> $request->containerDCode])->one();
                    } else {
                        $containerDown = \common\models\Unit::find()->where('`EconomicNumber` =:ecoN', [':ecoN'=> $request->containerDCode])->one();
                    }
                    $containerUp = \common\models\Unit::find()->where('`Order` =:order', [':order'=> $request->containerUCode])->one();
                    $destiny = $request->destiny;
                    if($destiny == "Patio") {
                        $destiny = $request->branch;
                    }
                    if(!is_null($containerDown)){
                        $event = new CargoEventLog();
                        $event->EventCategory = "maniobra";
                        $event->EventType = "Recoleccion";
                        $event->UserId = $request->userId;
                        $event->Destiny = $destiny;
                        $event->Unit = $request->unit;
                        $event->UnitOwner = $request->unitOwner;
                        $event->ContainerDId = $containerDown->Id;
                        $event->ContainerUId = $containerUp->Id;
                        $event->ProviderId = $destiny == "Proveedor" ? $request->providerId : "";
                        $event->Date = date('Y-m-d H:i:s', strtotime($request->date));
                        $event->Latitude = $request->latitude;
                        $event->Longitude = $request->longitude;
                        $event->Altitude = $request->altitude;
                        $event->SecondData = $request->secondData ? $request->secondData : "";
                        $event->FirstPicture = $request->firstPicture ? $request->firstPicture : "";
                        $event->SecondPicture = $request->secondPicture ? $request->secondPicture : "";
                        $deviceUp = \common\models\Device::findOne($containerUp->DeviceId);
                        $equipoUp = \common\models\Equipos::find()->where('eqId =:id', [':id'=> $deviceUp->TerminalId])->one();
                        $deviceDown = \common\models\Device::findOne($containerDown->DeviceId);
                        $equipoDown = \common\models\Equipos::find()->where('eqId =:id', [':id'=> $deviceDown->TerminalId])->one();
                        $deviceUp->Latitude = $request->latitude;
                        $deviceUp->Longitude = $request->longitude;
                        $deviceUp->Altitude = $request->altitude;
                        $deviceUp->ReportDate = $date;
                        $equipoUp->eqLatitud = $request->latitude;
                        $equipoUp->eqLongitud = $request->longitude;
                        $equipoUp->eqAltitud = $request->altitude;
                        $equipoUp->eqFechaActEq = $date;
                        $deviceDown->Latitude = $request->latitude;
                        $deviceDown->Longitude = $request->longitude;
                        $deviceDown->Altitude = $request->altitude;
                        $deviceDown->ReportDate = $date;
                        $equipoDown->eqLatitud = $request->latitude;
                        $equipoDown->eqLongitud = $request->longitude;
                        $equipoDown->eqAltitud = $request->altitude;
                        $equipoDown->eqFechaActEq = $date;
                        if($request->destiny == "Proveedor"){
                            $containerDown->OperativeStatusId = 2;
                        } else if($request->destiny == "Patio") {
                            $containerDown->OperativeStatusId = 4;
                        }
                        $containerUp->OperativeStatusId = 1;
                        if($event->save() && $containerDown->save() && $containerUp->save() && $deviceDown->save() && $deviceUp->save() && $equipoDown->save() && $equipoUp->save()) {
                            echo json_encode(array('value'=>1, 'mesage'=>'Registro de evento correcto', 'container'=>$containerUp->Order));
                        } else {
                            echo json_encode(array('value'=>0, 'mesage'=>'Se produjo un error intente de nuevo'));
                        }
                    } else {
                        echo json_encode(array('value'=>0, 'mesage'=>'El contenedor no se encuentra registrado'));
                    }
                }
            } else {
                    echo json_encode(array('value'=>0, 'mesage'=>'No trae datos'));
            }
        } else {
            echo json_encode(array('value'=>0, 'mesage'=>'No es post'));
        }
    }

    public function decode($codedString){
        $xorFormedString = $this->extendString($codedString);
        $shuffledString = $this->xorDeform($this->xorDeform($xorFormedString));
        $reversedString = $this->shuffle($shuffledString);
        unset($shuffledString);
        $extendedString = strrev($reversedString);
        unset($reversedString);
        $string = $this->contractString($extendedString);
        unset($extendedString);
        return $string;
    }

    protected function extendString($string){
        $extendedString = "";
        for($i=0;$i<strlen($string);$i++){
            $char = $string[$i];
            $extendedString .= $this->extendChar($char);
        }
        return $extendedString;
    }

    protected function extendChar($char){
        $decodedCharString = decbin(ord($char));
        $offset=8-strlen($decodedCharString);
        for ($i=0;$i<$offset;$i++){
            $decodedCharString = '0'.$decodedCharString;
        }
        return $decodedCharString;
    }

    protected function xorDeform($xorFormedString){
        $extendedString = "";
        for($i=0;$i<strlen($xorFormedString);$i=$i+4){
            $extendedString .= $this->denyChar($xorFormedString[$i+1]);
            $extendedString .= $this->compareChars($xorFormedString[$i],$xorFormedString[$i+1]);
            $extendedString .= $this->denyChar($xorFormedString[$i+3]);
            $extendedString .= $this->compareChars($xorFormedString[$i+2],$xorFormedString[$i+3]);
            $extendedString = $this->swapChars($extendedString,$i+1,$i+2);
        }
        return $extendedString;
    }

    protected function compareChars($a,$b){
        if ($a===$b) return "1";
        else return "0";
    }

    protected function swapChars($string, $positionA, $positionB){
        $char = $string[$positionA];
        $string[$positionA] = $string[$positionB];
        $string[$positionB] = $char;
        return $string;
    }

    protected function denyChar($a){
        if ($a==="1") return "0";
        else return "1";
    }

    protected function xorChar($a,$b){
        if ($a=="0"){
            if ($b=="1") return "1";
            else /*$b=="0"*/ return "0";
        } else { //$a=="1"
            if ($b=="1") return "0";
            else /*$b=="0"*/ return "1";
        }
    }

    protected function shuffle($extendedString){
        $splitString = $this->splitString($extendedString);
        $firstHalf = $splitString['firstHalf'];
        $secondHalf = strrev($splitString['secondHalf']);
        $length = strlen($secondHalf);
        for($i=0;$i<$length;$i=$i+2){
            if (isset($firstHalf[$i])){
                $char = $firstHalf[$i];
                $firstHalf[$i] = $secondHalf[$i];
                $secondHalf[$i] = $char;
            }  else {
                $char = $secondHalf[$i];
                $secondHalf[$i] = $secondHalf[$i+1];
                $secondHalf[$i+1] = $char;
            }
        }
        //var_dump($secondHalf);

        return $firstHalf.strrev($secondHalf);
    }

    protected function contractString($string){
        $contractedString = "";
        for($i=0;$i<strlen($string);$i=$i+8){
            $subString = substr($string,$i,8);
            $contractedString .= $this->contractChar($subString);
        }
        return $contractedString;
    }

    protected function contractChar($substring){
        $intByte = $this->_binaryToDecimal($substring);
        return sprintf("%c",$intByte);

    }

    protected function _binaryToDecimal($string){
        /* Remember EXTENDED_BYTES means char * */
        $value = 0;
        for ($i=strlen($string)-1, $position=0; $i>=0;$i--,$position++){
            $bit = $string[$i];
            if ($bit!=="0") $value += pow(2,$position);
        }
        return $value;
    }

    protected function splitString($extendedString){
        $length = strlen($extendedString);
        $totalBytes = $length/8;
        $flooredHalfLength = floor($totalBytes/2);
        $bytesToFirstHalf = $flooredHalfLength*8;
        $firstHalf = "";
        $secondHalf = "";
        for ($i=0;$i<$length;$i++){
            if ($i<$bytesToFirstHalf)
                $firstHalf .= $extendedString[$i];
            else
                $secondHalf .= $extendedString[$i];
        }
        return array(
            'firstHalf'=>$firstHalf,
            'secondHalf'=>$secondHalf
        );
    }

}