<?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 Laminas\View\Model\ViewModel;
use Khansia\Generic\Result;

class ApiController extends \Application\Master\GlobalActionController {


    public function getAccessAction(){

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

        if ($request->isPost()) {

            try{

                $username = $this->isFieldMandatory($post->usernam3, 'usernam3');
                $password = $this->isFieldMandatory($post->passw0rds, 'passw0rds');
                $devid    = $this->isFieldMandatory($post->devid, 'devid');

                $thisData = array(
                    'username'  => $username,
                    'password'  => $password,
                    'devid'     => $devid,
                );

                /* instance user */
                $access    = $this->authenticateApi($password, $thisData);     
                
                if($access->code == $result::CODE_SUCCESS){
                    $result->code = $access->code;
                    $result->info = $access->info;
                    $result->data = $access->data;
                }else{
                    $result->code = $access->code;
                    $result->info = $access->info;
                }


            }catch (\Exception $exc) {
                $result = new Result(0,1,$exc->getMessage() .'-'.$exc->getTraceAsString());
            }
        }else{
            $result = new Result(0,411,'Method is not compatible');
        }
        return $this->getOutput($result->toJson());
    }
	
	public function testAction(){
		$db = $this->getDb();
		
		echo '<pre>';
		print_r($db);die;
		
	}

    public function ssoLoginAction(){
        $result     = new Result();
        $request    = $this->getRequest();
        $post       = $request->getPost();
        // print_r($post->username);die;
        if($request->isPost()){

            try{
                $tag = 'ns1:loginResponse';
                $strip = 'ns1:';
                $strip2 = null;
                
                $username = $this->isFieldMandatory($post->username, 'username');
                $password = $this->isFieldMandatory($post->passwd, 'password');

                $curl = curl_init();

                curl_setopt_array($curl, array(
                  CURLOPT_URL => 'https://nic.itb.ac.id:443/riset/sson.php',
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_ENCODING => '',
                  CURLOPT_MAXREDIRS => 10,
                  CURLOPT_TIMEOUT => 0,
                  CURLOPT_FOLLOWLOCATION => true,
                  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                  CURLOPT_CUSTOMREQUEST => 'POST',
                  CURLOPT_POSTFIELDS =>'<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:loc="http://localhost/">
                   <soapenv:Header/>
                   <soapenv:Body>
                      <loc:login soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
                         <username xsi:type="xsd:string">'.$username.'</username>
                         <password xsi:type="xsd:string">'.$password.'</password>
                      </loc:login>
                   </soapenv:Body>
                </soapenv:Envelope>',
                  CURLOPT_HTTPHEADER => array(
                    'Content-Type: text/xml'
                  ),
                ));

                $response = curl_exec($curl);
                $err      = curl_error($curl);
                $info     = curl_getinfo($curl);
                $status   = array();
                curl_close($curl);

                $jsonResponse = $response;
                $xml = $jsonResponse;


                $offset = strpos($xml, $tag);
                if ($offset !== false) {
                    $xml = '<?xml version="1.0" encoding="utf-8"?>' . substr($xml, $offset-1);
                    $offset = strrpos($xml, '/' . $tag);
                    if ($offset !== false) {
                        $xml = substr($xml, 0, $offset-1) . '</' . $tag . '>';
                        if ($strip) {
                            $xml = str_replace($strip, '', $xml);
                        }

                        if($strip2){
                            $xml = str_replace($strip2, '', $xml);
                        }
                    }
                }

                $xmlres = simplexml_load_string($xml);

                $out = array ();
                $xmlObject = $xmlres;

                $status = json_decode(json_encode($xmlObject), true);

                if(is_array($status["return"])){
                  $out = false;
                }else{

                  foreach ( (array) $xmlObject as $index => $node )
                      $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

                }

                if($out){
                    $result->code = 0;
                    $result->info = 'success';
                    $result->data = $out;
                }else{
                    $result->code = 1;
                    $result->info = 'failed';
                }

                // print_r($result);die;
            }catch(\Exception $exc){
                $result = new Result(0,1,$exc->getMessage() .'-'.$exc->getTraceAsString());
            }
        }else{
            $result = new Result(0,411,'Method is not compatible');
        }
        return $this->getOutput($result->toJson());
    }

    public function ssoGetAllAttributeAction(){

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

        if ($request->isPost()) {

            try{

                $tag = 'ns1:getAllAtributeResponse';
                $strip = 'ns1:';
                $strip2 = null;

                $username = $this->isFieldMandatory($post->username, 'usernam3');

                $curl = curl_init();

                curl_setopt_array($curl, array(
                  CURLOPT_URL => 'https://nic.itb.ac.id:443/riset/sson.php',
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_ENCODING => '',
                  CURLOPT_MAXREDIRS => 10,
                  CURLOPT_TIMEOUT => 0,
                  CURLOPT_FOLLOWLOCATION => true,
                  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                  CURLOPT_SSL_VERIFYPEER => false,
                  CURLOPT_CUSTOMREQUEST => 'POST',
                  CURLOPT_POSTFIELDS =>'<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:loc="http://localhost/">
                                         <soapenv:Header/>
                                         <soapenv:Body>
                                            <loc:getAllAtribute soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
                                               <SID xsi:type="xsd:string">'.$username.'</SID>
                                            </loc:getAllAtribute>
                                         </soapenv:Body>
                                      </soapenv:Envelope>',
                  CURLOPT_HTTPHEADER => array(
                    'Content-Type: text/xml'
                  ),
                ));

                $response = curl_exec($curl);
                $err      = curl_error($curl);
                $info     = curl_getinfo($curl);
                $status   = array();
                curl_close($curl);

                $jsonResponse = $response;
                $xml = $jsonResponse;


                $offset = strpos($xml, $tag);
                if ($offset !== false) {
                    $xml = '<?xml version="1.0" encoding="utf-8"?>' . substr($xml, $offset-1);
                    $offset = strrpos($xml, '/' . $tag);
                    if ($offset !== false) {
                        $xml = substr($xml, 0, $offset-1) . '</' . $tag . '>';
                        if ($strip) {
                            $xml = str_replace($strip, '', $xml);
                        }

                        if($strip2){
                            $xml = str_replace($strip2, '', $xml);
                        }
                    }
                }

                $xmlres = simplexml_load_string($xml);

                $out = array ();
                $xmlObject = $xmlres;
                $status = json_decode(json_encode($xmlObject), true);

                if(is_array($status["return"])){
                  $return = false;
                }else{
                  foreach ( (array) $xmlObject as $index => $node )
                      $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

                  $return = $out['return'];
                  $return = rtrim($return, ';');
                  $return = str_replace('=>','":"', $return);
                  $pattern = '/;(?!([\\p{P}]))/';
                  $return = preg_replace($pattern, '","', $return);
                  $return = '{"'.$return.'"}';
                  $return = json_decode($return,true);
                }

                  if($return){
                      $result->code = 0;
                      $result->info = 'success';
                      $result->data = $return;
                  }else{
                      $result->code = 1;
                      $result->info = 'failed';
                  }

            }catch (\Exception $exc) {
                $result = new Result(0,1,$exc->getMessage() .'-'.$exc->getTraceAsString());
            }
        }else{
            $result = new Result(0,411,'Method is not compatible');
        }
        return $this->getOutput($result->toJson());
    }

    public function ssoTestAction(){
        $this->cas = new \phpCAS();
        $this->cas_server_url = "https://login.itb.ac.id/cas";
        $defaults = array('path'=> '', 'port'=>443);
        $cas_url = array_merge($defaults, parse_url($this->cas_server_url));
        
        $this->cas::client(CAS_VERSION_2_0,
                        $cas_url['host'],
                        $cas_url['port'],
                        $cas_url['path']);

        $this->cas->forceAuthentication();
        
        $userProfile = $this->cas->getAttributes();
        
        $message = $this->param()->fromQuery('message', 'hello');
        
        
    }

}