<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\web\Response;

use iDServer\iDServer;
use iDServer\Basic\KeyStore;
use iDServer\Saml\AuthnRequestData;
use iDServer\Saml\NameIdPolicy;
use iDServer\Saml\AttributeData;


class Kau_loginController extends Controller
{

    public $layout = 'response_layout';

    CONST OLDAL=[
        'fiz_mod_valt',  	// fizetési mód váltás
        'reszletfiz_1',  	// részletfizetési kérés
        'nyito_egyenleg',
    ];

    CONST WELCOME = [ 'KauAdapter' => 'v.1.1', 'result'=>null ];
    CONST ERROR = [  'message' => null  ];
    CONST AUTH_KEY = "KADF45-I2DG46-LHA4J2-02ADO8";
    CONST TTTTContainer = ['KAU_ID'=>null,'firstName'=>null,'lastName'=>null,'City'=>null,'motherName'=>null,'DateOfBirth'=>null];
    CONST URL_SAP = 'ftv-wt3-qav01.fotdhu.fotav.hu';
    CONST URL_SAP_CALLBACK = 'http://ftv-wd3-dvv02.fotdhu.fotav.hu:8000/kau_login';
    CONST URL_KAU = 'https://teszt.kau.gov.hu/dap/'; 


    private $_welcome;
    private $_error;
    private $_header;    

    public function __construct($id, $module)
    {
        parent::__construct($id,$module);
    }

    public function beforeAction($action)
    {

        $this->_error = self::ERROR;

        //echo "<pre>";print_r($_SERVER);exit;

        $this->_welcome = self::WELCOME;
        $this->_welcome['hash'] = hash("SHA256",self::AUTH_KEY);
        $this->_welcome['timestamp'] = date("Y-m-d H:i:s",time());
        $this->_welcome['remoteIP'] = $_SERVER['REMOTE_ADDR'];
        $this->_welcome['localIP'] = $_SERVER['SERVER_ADDR'];
        $this->_welcome['localHOST'] = $_SERVER['HTTP_HOST'];
        $this->_welcome['localSCHEME'] = @$_SERVER['REQUEST_SCHEME'];
        if( empty($this->_welcome['localSCHEME']) ){
            $this->_welcome['localSCHEME'] = (@$_SERVER['HTTPS']=='on' || @$_SERVER['SERVER_PORT']==443) ?  'https' : 'http';
        }

        // make callback url(s)  - amig nincs url kezeles tesztau.fotav.hu: missing
        switch($this->_welcome['localIP']){
            case '10.170.16.17': // dev
            case '10.170.16.1':  // PROD
                $this->_welcome['localURL'] = $this->_welcome['localSCHEME'].'://'.$this->_welcome['localIP'];
                break;
            case '87.229.120.165';
                $this->_welcome['localURL'] = $this->_welcome['localSCHEME'].'://'.$this->_welcome['localHOST'];
                break;
        }   

        if(!empty($_GET['guid'])){
            $this->_welcome['guid'] = $_GET['guid'];
        }

        if(!empty($_GET['oldal'])){
            $this->_welcome['oldal'] = $_GET['oldal'];
        }

        if(!empty($_GET['event'])){
            $this->_welcome['event'] = $_GET['event'];
        }

        //$this->_header['auth'] = @$_SERVER['HTTP_AUTH'];
/*
        if(empty($this->_header['auth'])){
            $this->_welcome['result'] = "error";
            $this->_error['message'] = "Auth key missing";
        }elseif( $this->_header['auth'] != $this->_welcome['hash'] ){
            $this->_welcome['result'] = "error";
            $this->_error['message'] = "Auth key mismatch";
        }
*/
        if( !empty($this->_error['message']) ){
            $this->action->actionMethod = 'actionError';
            $this->action->id = 'error';
        }
        else
        {
             $this->_welcome['result'] = "success";
        }

        //$this->_welcome['secureData']['result'] = $this->_generate4T('Endre','Teszt','Budapest','Kovacs Kinga','20020202');

        return true;
    }


    private function _generate4T($firstName,$lastName,$motherName,$DateOfBirth,$City){
        
        $TTTT = self::TTTTContainer;
        
        $TTTT['KAU_ID']	      = 'beolvasni';
        $TTTT['firstName']    = $firstName;
        $TTTT['lastName']     = $lastName;
        $TTTT['motherName']   = $motherName;
        $TTTT['DateOfBirth']  = $DateOfBirth;
        $TTTT['City']         = $City;

        //$this->_welcome['TTTT'] = $TTTT;
        return $this->_securingSensitiveData( json_encode( $TTTT , JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_LINE_TERMINATORS | JSON_UNESCAPED_UNICODE) );
    }

    private function _securingSensitiveData($data){

        $method = "aes-256-cbc";    
     
        $ivFile = Yii::$app->basePath."/cert/sec.iv";
        $keyFile = Yii::$app->basePath."/cert/sec.key";
        
        if( !file_exists( $ivFile ) ){ 

            $iv_length = openssl_cipher_iv_length($method);
            $iv = openssl_random_pseudo_bytes($iv_length);
            $handle = fopen($ivFile,'w+');
            fwrite($handle,$iv);
            fclose($handle);
            
        }else{
            $iv = file_get_contents($ivFile);
        }
        
        if( !file_exists( $keyFile  ) ){
            $key = openssl_random_pseudo_bytes(32,$cstrong);
            $handle = fopen($keyFile,'w+');
            fwrite($handle,$key);
            fclose($handle);
        }else{
            $key = file_get_contents($keyFile);
            //print $key; exit;
        }
        
        $result = openssl_encrypt($data,$method,$key, OPENSSL_RAW_DATA ,$iv); 

        $this->_welcome['secureData']['bin2hex_key'] = bin2hex($key);
        $this->_welcome['secureData']['base64_key'] = base64_encode($key);
        //$this->_welcome['secureData']['raw_key'] = $key;
        //$this->_welcome['secureData']['StrongKey'] = $cstrong;
        //$this->_welcome['secureData']['raw_iv'] = $iv;
        $this->_welcome['secureData']['bin2hex_iv'] = bin2hex($iv);
        $this->_welcome['secureData']['base64_iv'] = base64_encode($iv);
        //$this->_welcome['secureData']['iv_length'] = $iv_length;

        return $result; 
        //return $result; 
    }
	    

	/**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        /*
        if(empty($_REQUEST) || !in_array($_REQUEST['oldal'], self::OLDAL )){
            //print "Nem vart oldal kérése";
            //Yii::$app->end();
            return $this->runAction('error',[
                "result"  => "error",
                "message" => "Nem vart oldal kerese",
            ]); 
        }*/
        
        if(empty( $this->_welcome['guid'] )){
            return $this->runAction('error',[
                "result"  => "error",
                "message" => "guid kotelezo!",
            ]); 
        }

              // logging
              $this->logging( @$_REQUEST  );
            
                    return $this->render('index',[
                        'data'  	=> json_encode($this->_welcome ,  JSON_UNESCAPED_SLASHES  ),
                        'status_button' => $this->_welcome['localURL'].'/status?guid='.$this->_welcome['guid'],
                        'callback_button' => $this->_welcome['localURL'].'/kau_login/callback?guid='.$this->_welcome['guid'],
                    ]);

                    // redirect 4 login                    
                    //$this->redirect( SELF::URL_KAU );
                    


       // nothing return.

    }
    
    private function logging($dt){
    
        $data = print_r($dt,true);
        
        if( !$ip = @$_SERVER['REMOTE_ADDR'] ){
             //return;            
        }
        if($ip=='127.0.0.1' && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
            $realIP = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
            $ip = trim(end( $realIP ));
        }
        
        //print Yii::$app->basePath;
        //print_r( $_SERVER );exit;
        $ts = time();
        $ts_readable = date("Y-m-d H:i:s",$ts);
        $file = Yii::$app->basePath."/log/".$_REQUEST['guid'].".log"; 
             
        $handle = fopen($file,'a');
        
        if(!empty( $_SERVER['REQUEST_URI'] )) fwrite($handle, "\n{$ts_readable} CALLING URL: ".$_SERVER['REQUEST_URI'] );
        fwrite($handle, "\n{$ts_readable} Received:\n".$data );
        fwrite($handle, "\n{$ts_readable} Server: ".$ip );
//        if( !empty($this->_welcome['secureData']) ) fwrite($handle, "\n{$ts_readable} KEY: ".$this->_welcome['secureData']['raw_key'] );
        fwrite($handle, "\n__________________________________________\n" );
        fclose( $handle );        
        
    
    }

    public function actionCallback(){

        $genData = $this->_generate4T('Endre','Teszt','Budapest','Kovacs Kinga','20020202');

        $url = SELF::URL_SAP_CALLBACK;
        $url .= '?guid='.$this->_welcome['guid'];
        $url .= '&data='.base64_encode( $genData );
        //$url .= '&data1='.base64_encode( urlencode( $genData ) );
        //$url .= '&data2='.urlencode( base64_encode($genData ) );
        $url .= '&iv='.$this->_welcome['secureData']['base64_iv'];

        //$url = urlencode( $url );
        //$url = htmlentities( $url );

        $this->_welcome['REDIRECT_URL'] = $url;

        // logging
        $this->logging( $this->_welcome );
        //$this->_welcome['secureData']['TTTT_base64_encoded'] = base64_encode($genData); 

        return $this->redirect( $url ) ; 
    
    }

    public function actionCall(){


        $spNameQualifier = "PROBA_SP";
        $audienceList = [];

        $client = new iDServer('https://myserver.example.com/proxy', 'myclient.example.com');

        $keyStore = new KeyStore();
        $keyStore
            ->setCertificate('myclient.example.com', [
                file_get_contents(Yii::$app->basePath."/cert/hitelesito.crt"),
                file_get_contents(Yii::$app->basePath."/cert/hitelesito.crt"), //'path/to/fallback-cert'
            ])
            ->setSigningKey(openssl_pkey_get_private(Yii::$app->basePath.'/cert/titkosito.crt', 'qwert'))
            ->setSigningCertificate(file_get_contents(Yii::$app->basePath.'/cert/titkosito.crt'))
            ->setCryptKey(openssl_pkey_get_private(Yii::$app->basePath.'/cert/titkosito.crt', 'qwert'))
        ;
        $client->setKeyStore($keyStore);

        ///////////////////////////////////

        $attributes = [
            (new AttributeData())
                ->setName('...')
                ->setNameFormat('...')
                ->setValue('...')
                ->setType('...'),
            // ...
        ];

        $data = new AuthnRequestData();
        $data
            ->setExtensionAttributes($attributes)
            ->setAudiences($audienceList)
            ->setResponseLandingPage('http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'])
            ->setNameIdPolicy(new NameIdPolicy($spNameQualifier))
        ;
        $client->login($data, 'HU_hu');

        print "ok";
        //print_r($client);
        exit;

    }


    public function actionError($result=null,$message=null)
    {
        if( !empty($result)) $this->_welcome['result'] = $result;
        if( !empty($message)) $this->_error['message'] = $message;
        //print_r($this);

        return $this->render('error',[
            "data" =>   array_merge($this->_welcome , $this->_error) ,
        ]);
    }

}