<?php
/**
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Application\Controller;

use Application\Master;
use Zend\View\Model\ViewModel;
use Khansia\Generic\Result;

class ApiController extends \Application\Master\GlobalActionController {

    public function __construct($headScript)
    {
        $this->headScript = $headScript;
    }
    
    public function loginAction(){

        $this->loadUseri();
        
        // generate token if valid user
        $payload = ['email' => 'danirsdan@gmail.com', 'name' => 'dani'];

        //print_r($payload);die;
        $this->apiResponse['token'] = $this->generateJwtToken($payload);

        $this->apiResponse['message'] = 'Logged in successfully.';
        return $this->createResponse();
    }
	
	public function testAction(){
        $result     = new Result();
        $data       = $this->getData();
        
        //$name       = $this->isFieldMandatory(@$data['name'], 'name');

        $storage 	= \Application\Model\Test\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Test($storage);

        $getDataRes = $test->getDataTest();

        $payload    = $this->tokenPayload;

        $result->guid = $this->generateJwtToken($payload);
        $result->code = $result::CODE_SUCCESS;
        $result->info = $result::INFO_SUCCESS;
        $result->data = $payload;

        return $this->getOutput($result->toJson());
    }

	public function savedataAction(){
        if($this->isLoggedIn()){
			$result 	= new Result();
			$request 	= $this->getRequest();
			$post 		= $request->getPost();

			if ($request->isPost()) {
				try{
                    $id      = $post->id;
                    $nama    = $post->inama;
                    $nim     = $post->inim;
                    $klass   = $post->iklas;
                    
                    $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
                    $param    	= new \Application\Model\Param($storage);
                   
                    $tabel      = 'masiwa';


                    $seqBefore1 = $param->getLastSeqPostgree($tabel, 'id');
                    
                    $dataArray =  array (
                        'nama'          => $nama,
                        'nim'           => $nim,
                        'kelas'         => $klass,
                        'create_date'   => gmdate("Y-m-d H:i:s", time()+60*60*7),
                    );

                    
                    if($id){ // edit
                        $array_merge = array_merge($dataArray, array('id' => $id));
                        $where       = 'id='.$id;
                        $x           = $param->updateGlobal($tabel, $dataArray, $where);

                        $result->code = $result::CODE_SUCCESS; // code 0
                        $result->info = $result::INFO_SUCCESS;
                        $result->data = $id;
                    }else{ // insert
                        $param->saveGlobal($dataArray, $tabel);
                    
                        $seqAfter1     = $param->getLastSeqPostgree($tabel, 'id');

                        if($seqAfter1->data['total'] > $seqBefore1->data['total']){
                            $result->code = $result::CODE_SUCCESS; // code 0
                            $result->info = $result::INFO_SUCCESS;
                            $result->data = $seqAfter1->data['total'];
                        }else{
                            $result->code = 1; 
                            $result->info = 'Gagal insert';
                        }
                    }
				}catch (\Exception $exc) {
					$result = new Result(0,1,$exc->getMessage() .'-'.$exc->getTraceAsString());
				}
			}else{
				$result = new Result(0,401,'Silahkan masuk untuk melanjutkan');
			}
		}else{
			$result = new Result(0,401,'Silahkan masuk untuk melanjutkan');
		}
		return $this->getOutput($result->toJson());
    }

    public function generatetokenAction(){
        $result     = new Result();
        $request    = $this->getRequest();
        $post       = $request->getPost();
        $tabel      = 'website_list';

        //$token      = hash_hmac('sha512', uniqid(), 'Useranalytics');;
        //print_r($token);die;
        if($request->isPost()){
            try{
                $id           = $post->id_web;
                $webName      = $post->website_name;
                $webDomain    = $post->website_domain;
                $averageAge   = $post->average_age_visitor;
                $token        = $post->token;
                $id_user      = $post->id_user;

                $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
                $param    	= new \Application\Model\Param($storage);

                
                $dataArray  = array (
                    'website_name'          => $webName,
                    'website_domain'        => $webDomain,
                    'create_date'           => gmdate("Y-m-d H:i:s", time()+60*60*7),
                    'average_age_visitor'   => $averageAge,
                    'token'                 => $token,
                    'id_user'               => $id_user
                );
                
                $param->saveGlobal($dataArray, $tabel);

            }catch(\Exception $exc){
                $result = new Result(0,1,$exc->getMessage() .'-'.$exc->getTraceAsString());
            }

        }else{
            $result = new Result(0,401,'Silahkan masuk untuk melanjutkan');
        }

        return $this->getOutput($result->toJson());

    }

    public function registeruserAction(){
        $result     = new Result();
        $request    = $this->getRequest();
        $post       = $request->getPost();
        $tabel      = 'user_data_header';

        if($request->isPost()){
            try{
                $idUser     = $post->id;
                $username   = $post->username;
                $email      = $post->email;
                $password   = $post->password;

                $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
                $param    	= new \Application\Model\Param($storage);
                
                $dataArray  = array (
                    'username'      => $username,
                    'email'         => $email,
                    'password'      => md5($password),
                    'create_dtm'    => gmdate("Y-m-d H:i:s", time()+60*60*7),
                    'role'          => 10,
                    'status'        => 10,
                    'name'          => "user_".mt_rand(),
                );
                
                $param->saveGlobal($dataArray, $tabel);
                
            }catch(\Exception $exc){
                $result = new Result(0,1,$exc->getMessage() .'-'.$exc->getTraceAsString());
            }

        }else{
            $result = new Result(0,401,'Silahkan masuk untuk melanjutkan');
        }
        return $this->getOutput($result->toJson());
    }

    public function loaddataAction(){
        $result     = new Result();
        $request 	= $this->getRequest();
		$post 		= $request->getPost();
        
        //$name       = $this->isFieldMandatory(@$data['name'], 'name');

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Param($storage);


        $load       = $test->loadUser($post->id);
        

        if($load->code == 0){
            $result->code = $result::CODE_SUCCESS;
            $result->info = $result::INFO_SUCCESS;
            $result->data = $load->data;
        }else{
            $result->code = 1;
            $result->info = 'Not Found';
        }
        return $this->getOutput($result->toJson());
    }

    //load chart
    public function loadchartAction(){
        $result     = new Result();
        $request 	= $this->getRequest();
		$post 		= $request->getPost();
        
        //$name       = $this->isFieldMandatory(@$data['name'], 'name');

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Param($storage);

        $token = $post->token;
        $web = $test->getweb($token);
        $idweb = $web->data[0]['id_web'];

        $loadPieLocation       = $test->loadChart($idweb);

        if($loadPieLocation->code == 0){
            $result->code = $result::CODE_SUCCESS;
            $result->info = $result::INFO_SUCCESS;
            $result->data = $loadPieLocation->data;
        }else{
            $result->code = 1;
            $result->info = 'Not Found';
        }

        return $this->getOutput($result->toJson());
    }

    public function loadchartimageAction(){
        $result     = new Result();
        $request 	= $this->getRequest();
		$post 		= $request->getPost();
        
        //$name       = $this->isFieldMandatory(@$data['name'], 'name');

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Param($storage);

        $token = $post->token;
        $web = $test->getweb($token);
        $idweb = $web->data[0]['id_web'];

        $loadimage       = $test->loadChartimage($idweb);
        
        if($loadimage->code == 0){
            $result->code = $result::CODE_SUCCESS;
            $result->info = $result::INFO_SUCCESS;
            $result->data = $loadimage->data;
        }else{
            $result->code = 1;
            $result->info = 'Not Found';
        }

        return $this->getOutput($result->toJson());
    }

    public function loadbuttonAction(){
        $result     = new Result();
        $request 	= $this->getRequest();
		$post 		= $request->getPost();
        
        //$name       = $this->isFieldMandatory(@$data['name'], 'name');

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Param($storage);

        $token = $post->token;
        $web = $test->getweb($token);
        $idweb = $web->data[0]['id_web'];
        // print_r($idweb);die;

        $loadbutton       = $test->loadChartbutton($idweb);
        // print_r($loadbutton);die;
        if($loadbutton->code == 0){
            $result->code = $result::CODE_SUCCESS;
            $result->info = $result::INFO_SUCCESS;
            $result->data = $loadbutton->data;
        }else{
            $result->code = 1;
            $result->info = 'Not Found';
        }

        return $this->getOutput($result->toJson());
    }

    public function loadchartbrowserAction(){
        $result     = new Result();
        $request 	= $this->getRequest();
		$post 		= $request->getPost();
        
        //$name       = $this->isFieldMandatory(@$data['name'], 'name');

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Param($storage);


        //$loadPieLocation       = $test->loadChart($post->id);
    
        $loadPieBrowser        = $test->loadChartBrowser($post->id);

        

        if($loadPieBrowser->code == 0){
            $result->code = $result::CODE_SUCCESS;
            $result->info = $result::INFO_SUCCESS;
            $result->data = $loadPieBrowser->data;
        }else{
            $result->code = 1;
            $result->info = 'Not Found';
        }

        return $this->getOutput($result->toJson());
    }

    public function loaduserwebAction(){
        $result     = new Result();
        $request 	= $this->getRequest();
		$post 		= $request->getPost();
        
        //$name       = $this->isFieldMandatory(@$data['name'], 'name');

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Param($storage);
        
        $token = $post->token;
        $web = $test->getweb($token);
        $idweb = $web->data[0]['id_web'];
        
        $loadTableUser           = $test->loadTableUser($idweb);
        
        // print_r($loadTableUser);die;

        if($loadTableUser->code == 0){
            $result->code = $result::CODE_SUCCESS;
            $result->info = $result::INFO_SUCCESS;
            $result->data = $loadTableUser->data;
        }else{
            $result->code = 1;
            $result->info = 'Not Found';
        }

        return $this->getOutput($result->toJson());
    }

    public function loadchartpengunjungAction(){
        $result     = new Result();
        $request 	= $this->getRequest();
		$post 		= $request->getPost();
        
        //$name       = $this->isFieldMandatory(@$data['name'], 'name');

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Param($storage);


        //$loadPieLocation       = $test->loadChart($post->id);
        //$loadPieBrowser        = $test->loadChartBrowser($post->id);
        //$loadTableUser           = $test->loadTableUser($post->id);
        $loadAreaPengunjung           = $test->loadChartPengunjung($post->id);

        if($loadPieLocation->code == 0){
            $result->code = $result::CODE_SUCCESS;
            $result->info = $result::INFO_SUCCESS;
            $result->data = $loadAreaPengunjung->data;
        }else{
            $result->code = 1;
            $result->info = 'Not Found';
        }

        return $this->getOutput($result->toJson());
    }

    public function loadcharthalamanAction(){
        $result     = new Result();
        $request 	= $this->getRequest();
		$post 		= $request->getPost();
        
        //$name       = $this->isFieldMandatory(@$data['name'], 'name');

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Param($storage);
        $token = $post->token;
        $web = $test->getweb($token);
        $idweb = $web->data[0]['id_web'];
       
        // print_r($idweb);die;

        $loadBarHalaman           = $test->loadChartHalaman($idweb);
        
        if($loadPieLocation->code == 0){
            $result->code = $result::CODE_SUCCESS;
            $result->info = $result::INFO_SUCCESS;
            $result->data = $loadBarHalaman->data;
        }else{
            $result->code = 1;
            $result->info = 'Not Found';
        }

        return $this->getOutput($result->toJson());
    }

    public function loadchartbuttonAction(){
        $result     = new Result();
        $request 	= $this->getRequest();
		$post 		= $request->getPost();
        
        //$name       = $this->isFieldMandatory(@$data['name'], 'name');

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Param($storage);


        //$loadPieLocation       = $test->loadChart($post->id);
        //$loadPieBrowser        = $test->loadChartBrowser($post->id);
        //$loadTableUser           = $test->loadTableUser($post->id);
        $loadBarButton           = $test->loadChartButton($post->id);

        if($loadPieLocation->code == 0){
            $result->code = $result::CODE_SUCCESS;
            $result->info = $result::INFO_SUCCESS;
            $result->data = $loadBarButton->data;
        }else{
            $result->code = 1;
            $result->info = 'Not Found';
        }

        return $this->getOutput($result->toJson());
    }

    public function loginuserAction(){
        $result     = new Result();
        $request 	= $this->getRequest();
		$post 		= $request->getPost();
        
        //$name       = $this->isFieldMandatory(@$data['name'], 'name');

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Param($storage);


        //$loadPieLocation       = $test->loadChart($post->id);
        //$loadPieBrowser        = $test->loadChartBrowser($post->id);
        //$loadTableUser           = $test->loadTableUser($post->id);
        //$loadBarButton           = $test->loadChartButton($post->id);
        $loadUser         = $test->loadUserLogin($post->id);

        if($loadPieLocation->code == 0){
            $result->code = $result::CODE_SUCCESS;
            $result->info = $result::INFO_SUCCESS;
            $result->data = $loadUser->data;
        }else{
            $result->code = 1;
            $result->info = 'Not Found';
        }

        return $this->getOutput($result->toJson());
    }



    public function deletedataAction(){
        $result     = new Result();
        $request 	= $this->getRequest();
		$post 		= $request->getPost();
        
        //$name       = $this->isFieldMandatory(@$data['name'], 'name');

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Param($storage);


        $tabel3     = 'masiwa';
        $where3     = 'id='.$post->id;
        $res        = $test->deleteGlobal($tabel3, $where3);

        if($load->code == 0){
            $result->code = $result::CODE_SUCCESS;
            $result->info = $result::INFO_SUCCESS;
        }else{
            $result->code = 1;
            $result->info = 'Not Found';
        }

        return $this->getOutput($result->toJson());
    }

    public function deletewebsiteAction(){
        $result     = new Result();
        $request 	= $this->getRequest();
		$post 		= $request->getPost();
        
        //$name       = $this->isFieldMandatory(@$data['name'], 'name');

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Param($storage);


        $tabel3     = 'website_list';
        $where3     = 'id_web='.$post->id;
        //print_r($where3);die;
        $res        = $test->deleteGlobal($tabel3, $where3);

        if($load->code == 0){
            $result->code = $result::CODE_SUCCESS;
            $result->info = $result::INFO_SUCCESS;
        }else{
            $result->code = 1;
            $result->info = 'Not Found';
        }

        return $this->getOutput($result->toJson());
    }

    public function websitelistAction(){
        $result     = new Result();
        $request 	= $this->getRequest();
		$post 		= $request->getPost();
        $session_data   =   $this->getSession();

        $id = $session_data->get('user_id');
        
        
        //$name       = $this->isFieldMandatory(@$data['name'], 'name');

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Param($storage);

        // if($post->id_user == null){
        //     $loadWebsite           = $test->loadWebsiteUser($post->id_user);
        // }else{
        //     $loadWebsite           = $test->loadWebsiteUser($id);
        // }
        //$loadPieLocation       = $test->loadChart($post->id);
        //$loadPieBrowser        = $test->loadChartBrowser($post->id);
        //$loadTableUser           = $test->loadTableUser($post->id);
        $loadWebsite           = $test->loadWebsiteUser($post->id_user);

        if($loadWebsite->code == 0){
            $result->code = $result::CODE_SUCCESS;
            $result->info = $result::INFO_SUCCESS;
            $result->data = $loadWebsite->data;
        }else{
            $result->code = 1;
            $result->info = 'Not Found';
        }

        return $this->getOutput($result->toJson());
    }

    public function loadusernameAction(){
        $result     = new Result();
        $request 	= $this->getRequest();
		$post 		= $request->getPost();
        
        //$name       = $this->isFieldMandatory(@$data['name'], 'name');

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Param($storage);

        $id = $post->id;


      
        $loadUsername           = $test->loadUsername($id);

        if($loadUsername->code == 0){
            $result->code = $result::CODE_SUCCESS;
            $result->info = $result::INFO_SUCCESS;
            $result->data = $loadUsername->data;
        }else{
            $result->code = 1;
            $result->info = 'Not Found';
        }

        return $this->getOutput($result->toJson());
    }

    public function checkDomainAction(){
        $result     = new Result();
        $isOnline   = false;
        $request 	= $this->getRequest();
        $post 		= $request->getPost();
        $domain     = $post->domain;
        // print_r($domain);die;

        if($socket =@ fsockopen($domain, 80, $errno, $errstr, 30)) {
           // echo 'online!';
            $isOnline = TRUE;
            fclose($socket);
            } else {
            //echo 'offline.';
            $isOnline = FALSE;
            }

        $result->data = $isOnline;
        //return $isOnline;
        return $this->getOutput($result->toJson());
    }

    public function websiteRowMatchesAction(){
        $result     = new Result();
        $request    = $this->getRequest();
        $post       = $request->getPost();

        $websiteName    = $post->websiteName;
        $token          = $post->token;

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Param($storage);

        $loadRow           = $test->validateWebToken($websiteName, $token);

        if($loadRow->code == 0){
            $result->code = $result::CODE_SUCCESS;
            $result->info = $result::INFO_SUCCESS;
            $result->data = $loadRow->data;
        }else{
            $result->code = 1;
            $result->info = 'Not Found';
        }

        return $this->getOutput($result->toJson());
    }

    public function updateProfileAction(){
        $result     = new Result();
        $request    = $this->getRequest();
        $post       = $request->getPost();
        $session    = $this->getSession();
        $tabel      = 'user_data_header';

        if($request->isPost()){
            try{
                $idUser     = $post->id;
                $username   = $post->username;
                $email      = $post->email;
                $name       = $post->name;

                $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
                $param    	= new \Application\Model\Param($storage);
                
                $where      = "iduser=".$idUser;

                $dataArray  = array (
                    'username'      => $username,
                    'email'         => $email,
                    'name'          => $name,
                );
                

                $param->updateGlobal($tabel, $dataArray, $where);
                $session->put(null, array('usernamed' => $username));
                
            }catch(\Exception $exc){
                $result = new Result(0,1,$exc->getMessage() .'-'.$exc->getTraceAsString());
            }

        }else{
            $result = new Result(0,401,'Silahkan masuk untuk melanjutkan');
        }
        return $this->getOutput($result->toJson());
    }

    public function updatePasswordAction(){
        $result     = new Result();
        $request    = $this->getRequest();
        $post       = $request->getPost();
        $session    = $this->getSession();
        $tabel      = 'user_data_header';

        if($request->isPost()){
            try{
                $code           = $post->code;
                $idUser         = $post->id;
                
                //var for user update
                $currentPass    = $post->currentPas;
                $newPass        = $post->newPas;
                $confirmPass    = $post->confirmPassword;
                $passinDB       = $post->passDB;
                
                //var for admin update
                $defaultPass    = "username";
                

                $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
                $param    	= new \Application\Model\Param($storage);
                
                $where      = "iduser=".$idUser;
                
                
                
                if($code == 10){
                    if(md5($currentPass) != $passinDB){
                        // print_r('gagal');die;
                        $result->info   = "Wrong Current Password!";
                    }else if($confirmPass != $newPass){
                        // print_r('dontmatch');die;
                        $result->info   = "New Password does not Match!";
                    } else {
                        // print_r('brhasil');die;
                        $dataArray  = array (
                            'password'      => md5($confirmPass)
                        );

                        $param->updateGlobal($tabel, $dataArray, $where);
                        $result->info   = "Change Password Success!";
                    }
                } else if($code == 20){
                    $dataArray = array(
                        'password'      => md5($defaultPass)
                    );

                    $param->updateGlobal($tabel, $dataArray, $where);
                        $result->info   = "Reset Password Success!";
                }
                

                // $param->updateGlobal($tabel, $dataArray, $where);
            }catch(\Exception $exc){
                $result = new Result(0,1,$exc->getMessage() .'-'.$exc->getTraceAsString());
            }

        }else{
            $result = new Result(0,401,'Silahkan masuk untuk melanjutkan');
        }
        return $this->getOutput($result->toJson());
    }

    public function deleteuserAction(){
        $result     = new Result();
        $request 	= $this->getRequest();
		$post 		= $request->getPost();
        
        //$name       = $this->isFieldMandatory(@$data['name'], 'name');

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Param($storage);


        $tabel3     = 'user_data_header';
        $where3     = 'iduser='.$post->id;
        //print_r($where3);die;
        $res        = $test->deleteGlobal($tabel3, $where3);

        if($load->code == 0){
            $result->code = $result::CODE_SUCCESS;
            $result->info = $result::INFO_SUCCESS;
        }else{
            $result->code = 1;
            $result->info = 'Not Found';
        }
        
        return $this->getOutput($result->toJson());
    }

    public function activateUserAction(){
        $result     = new Result();
        $request    = $this->getRequest();
        $post       = $request->getPost();
        $session = $this->getSession();
        $tabel      = 'user_data_header';

        if($request->isPost()){
            try{
                $idUser     = $post->id;
                $code       = $post->code;
               
                $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
                $param    	= new \Application\Model\Param($storage);
                
                $where      = "iduser=".$idUser;

                if($code == "ACTIVATE"){
                    $dataArray  = array (
                        'status'      => 10,
                    );
                    $result->info = "User Deactivation Sucess!";
                } else if ($code == "DEACTIVATE"){
                    $dataArray  = array (
                        'status'      => 30,
                    );
                    $result->info = "User Activation Sucess!";
                }

                $param->updateGlobal($tabel, $dataArray, $where);
                $result->info = "User Activation Sucess!";
                //$session['name'] = $name;
                
            }catch(\Exception $exc){
                $result = new Result(0,1,$exc->getMessage() .'-'.$exc->getTraceAsString());
            }

        }else{
            $result = new Result(0,401,'Silahkan masuk untuk melanjutkan');
        }
        return $this->getOutput($result->toJson());
    }



    

    public function savetojsonAction(){
        $result     = new Result();
        $request 	= $this->getRequest();
		$post 		= $request->getPost();
        

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Param($storage);


        if($request->isPost()){
            $nameweb = $post->myData['nameweb'];
            
            $foldername = "public/folder-json/".$nameweb;

            $data = $post->myData;
            $ipaddress = $post->myData['user_info']['ip_address_client'];
            $dateaccess = $post->myData['page']['date_access'];
            
            $timeaccess = $post->myData['page']['time_accessname'];

            try{
                // print_r(is_dir($foldername));die;
                if(is_dir($foldername)===false){
                    mkdir($foldername, 0777, false); 
                    if($ipaddress!=null && $dateaccess!=null && $timeaccess!=null){
                        $namaefile = $ipaddress."_".$dateaccess."_".$timeaccess;                      
                        $json = json_encode($data, JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);
                        file_put_contents ($foldername."/".$namaefile.".json", $json);
                    }else{
                        $result->data = "not found ipaddress";
                    }
                }else{
                    if($ipaddress!=null && $dateaccess!=null && $timeaccess!=null){
                        $namaefile = $ipaddress."_".$dateaccess."_".$timeaccess;                      
                        $json = json_encode($data, JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);
                        file_put_contents ($foldername."/".$namaefile.".json", $json);
                    }else{
                        $result->data = "not found ipaddress";
                    }
                }
            }catch(\Exception $exc){
                $result = new Result(0,1,$exc->getMessage() .'-'.$exc->getTraceAsString());
            }

        }else{
            $result = new Result(0,401,'Silahkan masuk untuk melanjutkan');
        }

        return $this->getOutput($result->toJson());
    }

    public function loadtokenaction(){
        $result     = new Result();
        $request 	= $this->getRequest();
		$post 		= $request->getPost();
        

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Param($storage);

        // print_r('masuk'); 

        if($request->isPost()){
            $token = $post->myData;
            $nameweb = $test->getnameweb($token);

            $result->code = 0;
            $result->info ='ok';
            $result->data = $nameweb->data;

        }else{
            $result = new Result(0,401,'token not define');
        }

        return $this->getOutput($result->toJson());
    }


    public function loadmacaddressAction(){
        $result     = new Result();
        $request 	= $this->getRequest();
		$post 		= $request->getPost();
        

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Param($storage);

        $_IP_SERVER = $_SERVER['SERVER_ADDR'];
        $_IP_ADDRESS = $_SERVER['REMOTE_ADDR'];
    
        $_HASIL ='';
        if($_IP_ADDRESS == $_IP_SERVER)
        {
            ob_start();
            system('ipconfig /all');
            $_PERINTAH  = ob_get_contents();
            ob_clean();
            $_PECAH = strpos($_PERINTAH, "Physical");
            $_HASIL = substr($_PERINTAH,($_PECAH+36),17);
        } else {
            $_PERINTAH = "arp -a $_IP_ADDRESS";
            ob_start();
            system($_PERINTAH);
            $_HASIL = ob_get_contents();
            ob_clean();
            $_PECAH = strstr($_HASIL, $_IP_ADDRESS);
            $_PECAH_STRING = explode($_IP_ADDRESS, str_replace(" ", "", $_PECAH));
            $_HASIL = substr($_PECAH_STRING[1], 0, 17);
        }

        if($_HASIL){
            $result->code = $result::CODE_SUCCESS;
            $result->info = $result::INFO_SUCCESS;
            $result->data = $_HASIL;
        }else{
            $result->code = 0;
            $result->info = 'not found mac address';
        }
            

        return $this->getOutput($result->toJson());
    }


    public function loadipaddressAction(){
        $result     = new Result();
        $request 	= $this->getRequest();
		$post 		= $request->getPost();
        

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Param($storage);

        $ipaddress = '';
        if (isset($_SERVER['HTTP_CLIENT_IP']))
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
        else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        else if(isset($_SERVER['HTTP_X_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
        else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
        else if(isset($_SERVER['HTTP_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
        else if(isset($_SERVER['REMOTE_ADDR']))
            $ipaddress = $_SERVER['REMOTE_ADDR'];
        else
            $ipaddress = 'UNKNOWN';
        
        if($ipaddress){
            $result->code = $result::CODE_SUCCESS;
            $result->info = $result::INFO_SUCCESS;
            $result->data = $ipaddress;
        }else{
            $result->code = 1;
            $result->info = 'Cant search ip address';
        }
           

        return $this->getOutput($result->toJson());
    }

    public function keyvalAction(){
        $result     = new Result();
        $request 	= $this->getRequest();
		$post 		= $request->getPost();
        
        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $test    	= new \Application\Model\Param($storage);
        
        $key = $post->myData;
        $keydb = $test->loadkey($key);

        if($keydb){
            $result->code = $result::CODE_SUCCESS;
            $result->info = $result::INFO_SUCCESS;
            $result->data =$keydb->data;
        }else{
            $result->code = 1;
            $result->info = 'Key not define';
        }
           
        return $this->getOutput($result->toJson());
    }

    public function getfileAction(){
        $result = new Result();
        $request = $this->getRequest();
        $post = $request->getPost();
        try{
            $tabel ='userweb_info';

            $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
            $param    	= new \Application\Model\Param($storage);
                        $token = $post->token;

            $namewebi = $param->getweb($token);
            
            $nameweb = $namewebi->data[0]['website_name'];
            // print_r($nameweb->data); 

            $files = glob("public/folder-json/".$nameweb."/*.json");
            // print_r($files); 

            if($files){
                foreach($files as $name){
    
                    $json = file_get_contents($name);
                    $json_data = json_decode($json, true);
    
                    //Action for USER INFO
                    if($json_data["user_info"]){
                        
                        $userinfo = $json_data["user_info"];
                        $nameweb = $json_data["nameweb"];
                        $location = $json_data["location"];
                        $page = $json_data["page"];
                        $browser = $json_data["browser"];
                        $behavbtn = $json_data['behavioruser']['button'];
                        $behavimg = $json_data['behavioruser']['image'];
                        $behavother = $json_data['behavioruser']['other'];
                        $behavvideo = $json_data['behavioruser']['video'];

                        // print_r($behavbtn); 

                            
                        $dataarray = array(
                            'ip_address_public' => $userinfo['ip_address_public'],
                            'ip_address_client' => $userinfo['ip_address_client'],
                            'mac_address'       => $userinfo['mac_address'],
                        ); 
                        
                        $arraylocation = array(
                            'city' => $location['city'],
                            'province'=>$location['province'],
                            'country'  => $location['country']
                        );

                        $arraypage = array(
                            'name_page'=> $page['name_page'],
                            'date_access'=> $page['date_access'],
                            'time_access'=>$page['time_access'],
                        );
                        
        
                        $arraybrowser = array(
                            'browser_name' => $browser['browserName'],
                            'browser_ver' => $browser['browserVer']
                        );

                      
                        $setuser = $param->setuserdb($dataarray, $arraylocation, $arraybrowser, $nameweb, $page);
                        
                        
                        foreach($behavbtn as $val){
                            // print_r($val); 
                            $savebtn = $param->setbehavbtn($val, $arraypage, $nameweb, $dataarray, $arraybrowser);
                            // print_r($savebtn); 
                        }

                        foreach($behavimg as $val){
                            $savebehav = $param->setbehavimg($val, $arraypage, $nameweb, $dataarray, $arraybrowser);
                        }

                        foreach($behavvideo as $val){
                            $savevideo = $param->setbehavideo($val, $arraypage, $nameweb, $dataarray, $arraybrowser);
                        }
                        foreach($behavother as $val){
                            $saveother = $param->setbehavother($val, $arraypage, $nameweb, $dataarray,  $arraybrowser);
                        }
                    
                    }else{
                        $result->code = 1;
                        $result->info = 'cant found data';
                    }
                    // print_r($setuser); 
                    if($setuser->code == 0 ){
                        // unlink($name);
                        $result->code = $result::CODE_SUCCESS;
                        $result->info = $result::INFO_SUCCESS;
                        $result->data = $setuser;
                    }else{
                        $result->code = 1;
                        $result->info = 'cant configuration to database';
                    }
                }
            }else{
                $result->code = 2;
                $result->info = 'cant found file';
            } 
        }catch(\Exception $exc){
            $result = new Result(0,1,$exc->getMessage() .'-'.$exc->getTraceAsString());
        }
        return $this->getOutput($result->toJson());
    }

    public function getdatavisitorAction(){
        $result = new Result();
        $request = $this->getRequest();
        $post = $request->getPost();

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $param    	= new \Application\Model\Param($storage);

        if($request->isPost()){
            $token = $post->token;
            // print_r($token); 
            $web = $param->getweb($token);
            $idweb = $web->data[0]['id_web'];

            if($idweb){
                $totalvisiti = $param->gettotalvisitor($idweb);
               
                $totalvisit = $totalvisiti->data['count'];

                $totallocation = $param->gettotalocation($idweb);
                // print_r($totallocation); 

                $pageviews = $param->getpageviews($idweb);

                $newvisitor = $param->getnewvisitor($idweb);
                // print_r($newvisitor); 

                $listdata = array(
                    'total_visit' => $totalvisit,
                    'total_cities' => $totallocation->data,
                    'page_views'   => $pageviews->data,
                    'new_visitor'   => $newvisitor->data
                );
    
                $result->info  = 'ok';
                $result->code  = 0;
                $result->data  = $listdata;
            }else{
                $result->info  = 'nok';
                $result->code  = 1;
            }

        }
        return $this->getOutput($result->toJson());
    }

    public function loadyearAction(){
        $result = new Result();
        $request = $this->getRequest();
        $post = $request->getPost();

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $param    	= new \Application\Model\Param($storage);

        if($request->isPost()){
            $token = $post->token;
            $web = $param->getweb($token);
            $idweb = $web->data[0]['id_web'];
            // print_r($idweb); 

            if($idweb){
                $year = $param->getyearvisitor($idweb);
                // print_r($year->data); 
                $result->info  = 'ok';
                $result->code  = 0;
                $result->data = $year->data;
            }else{
                $result->info  = 'nok';
                $result->code  = 1;
            }
            
        }
        return $this->getOutput($result->toJson());
    }

    function loadvisitorperyearAction(){
        $result = new Result();
        $request = $this->getRequest();
        $post = $request->getPost();

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $param    	= new \Application\Model\Param($storage);

        
        if($request->isPost()){
            $token = $post->token;
            $web = $param->getweb($token);
            $idweb = $web->data[0]['id_web'];
            $year = $post->year;

            $listdata = $param->getnumbervisitor($idweb, $year);
            $result->info  = 'ok';
            $result->code  = 0;
            $result->data = $listdata->data;
            
        }else{
            $result->info  = 'nok';
            $result->code  = 1;
        }
        return $this->getOutput($result->toJson());
    }

    function loadpiebrowserAction(){
        $result = new Result();
        $request = $this->getRequest();
        $post = $request->getPost();

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $param    	= new \Application\Model\Param($storage);

        $token = $post->token;
        $web = $param->getweb($token);
        $idweb = $web->data[0]['id_web'];

        $browser = $param->getpiebrowserdata($idweb);
        
        $result->info = 'ok';
        $result->code = 0;
        $result->data = $browser->data;

        return $this->getOutput($result->toJson());
    }

    function loadvisitormonthAction(){
        $result = new Result();
        $request = $this->getRequest();
        $post = $request->getPost();

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $param    	= new \Application\Model\Param($storage);
        $token = $post->token;
        $web = $param->getweb($token);
        $idweb = $web->data[0]['id_web'];
        
        $year = $post->year;

        $listdata = $param->getmonthvisitor($idweb, $year);

        $result->info = 'ok';
        $result->code = 0;
        $result->data = $listdata->data;

        return $this->getOutput($result->toJson());
    }

    function loadvisitorbymonthAction(){
        $result = new Result();
        $request = $this->getRequest();
        $post = $request->getPost();

        $storage 	= \Application\Model\Param\Storage::factory($this->getDb(), $this->getConfig());
        $param    	= new \Application\Model\Param($storage);
        $token = $post->token;
        $year = $post->year;
        $month = $post->month;

        $web = $param->getweb($token);
        $idweb = $web->data[0]['id_web'];
        
        $listdata = $param->getvisitorbymonth($idweb, $year, $month);

        $result->info = 'ok';
        $result->code = 0;
        $result->data = $listdata->data;

        return $this->getOutput($result->toJson());
    }
    
}