<?php

namespace frontend\extensions;

use Yii;
use common\models\Log;

class EngInterface {

    private static $baseUrl = 'https://tmph.engbms.it:8443/tmph/';

    public static function ip2msisdn($ip,$port) {

        $url = self::$baseUrl."api/ip2msisdn/v1/$ip?port=$port";
        $uuid = self::gen_uuid();

        $result = self::sendRequest($url, $uuid);
        $desc = ( $result['body']!= null && property_exists($result['body'], 'result') ) ? $result['body']->result : json_encode($result['body']);
        Log::log($uuid, 'EngInterface | ip2msisdn', ['url' => $url, 'ip' => $ip, 'port' => $port, 'result' => $result], $result['headers']['response_code'], $desc);

        return $result;

    }  

    public static function moo($msisdn) {
        $tel = substr( $msisdn, 0, 3 ) === '+39' ? trim($msisdn) : '+39'.$msisdn;
        $tel = str_replace([' ','.','/','-'],'',$tel);
        
        $url = self::$baseUrl.'api/moo/v1/'.$tel;
        $uuid = self::gen_uuid();

        $result = self::sendRequest($url, $uuid);
        $desc = ( $result['body']!= null && property_exists($result['body'], 'result') ) ? $result['body']->result : json_encode($result['body']);
        Log::log($uuid, 'EngInterface | moo', ['url' => $url, 'msisdn' => $msisdn, 'result' => $result], $result['headers']['response_code'], $desc);

        return $result;

    }    
    
    public static function customerProfile($msisdn) {
        $tel = substr( $msisdn, 0, 3 ) === '+39' ? trim($msisdn) : '+39'.$msisdn;
        $tel = str_replace([' ','.','/','-'],'',$tel);

        $url = self::$baseUrl.'api/customerprofile/v1/'.$tel;
        $uuid = self::gen_uuid();

        $result = self::sendRequest($url, $uuid);
        $desc = ( $result['body']!= null && property_exists($result['body'], 'result') ) ? $result['body']->result : json_encode($result['body']);
        Log::log($uuid, 'EngInterface | customerProfile', ['url' => $url, 'msisdn' => $msisdn, 'result' => $result], $result['headers']['response_code'], $desc);

        return $result;

    }   
    
    public static function sendOTP($msisdn) {
        $url = self::$baseUrl.'api/otp/v1';

        $tel = substr( $msisdn, 0, 3 ) === '+39' ? trim($msisdn) : '+39'.$msisdn;
        $tel = str_replace([' ','.','/','-'],'',$tel);

        $uuid = self::gen_uuid();

        $result = self::sendRequest($url, $uuid, $tel, 'POST');
        $desc = ( $result['body']!= null && property_exists($result['body'], 'result') ) ? $result['body']->result : json_encode($result['body']);
        Log::log($uuid, 'EngInterface | sendOTP', ['url' => $url, 'msisdn' => $msisdn, 'result' => $result], $result['headers']['response_code'], $desc);

        return $result;

    }	

    public static function checkOTP($msisdn, $otp) {
        $tel = substr( $msisdn, 0, 3 ) === '+39' ? trim($msisdn) : '+39'.$msisdn;
        $tel = str_replace([' ','.','/','-'],'',$tel);

        $url = self::$baseUrl.'api/otp/v1/'.$tel.'?password='.$otp;

        $uuid = self::gen_uuid();

        $result = self::sendRequest($url, $uuid);
        $desc = ( $result['body']!= null && property_exists($result['body'], 'result') ) ? $result['body']->result : json_encode($result['body']);
        Log::log($uuid, 'EngInterface | checkOTP', ['url' => $url, 'msisdn' => $msisdn, 'otp' => $otp, 'result' => $result], $result['headers']['response_code'], $desc);

        return $result;
        
    }

    private static function sendRequest($url, $uuid, $msisdn = null, $method = 'GET') {

        $auth = base64_encode('tim_coccole_cinema_armosia:ZE!e7uwr6++2adrep#ukaswu');

        $options = array(
            'http' => array(
                'header' => "Content-type: application/json\r\n" . "Authorization: Basic $auth\r\n" . "X-Tx-Id: $uuid \r\n" . "Cache-Control: no-cache \r\n",
                'method' => $method,
                // 'protocol_version'=>'1.1',
                ),
            "ssl"=>array(
                // "verify_peer" => false,
                // "verify_peer_name" => false,
                // "allow_self_signed"=> true,
                // 'cafile' => Yii::getAlias('@webroot/resources/cert.pem')
                'cafile' => Yii::getAlias('@webroot/resources/tmph.engbms.it.crt')
                ),
            );
        if ($msisdn) {
            $tel = substr( $msisdn, 0, 3 ) === '+39' ? trim($msisdn) : '+39'.$msisdn;
            $tel = str_replace([' ','.','/','-'],'',$tel);
        }
        if ($method == 'POST') {
            $data = array('address' => $tel, 'txId' => $uuid, 'text' => 'Il codice TIM Cinema è ');
            $options['http']['content'] = json_encode($data);
        }

        $context = stream_context_create($options);
        $ret = @file_get_contents($url, false, $context);
        $headers = self::parseHeaders($http_response_header);
        
        return ['headers' => $headers, 'body' => ($ret == null) ? null : json_decode($ret)];

    }

    private static function parseHeaders( $headers )
    {
        $head = array();
        foreach( $headers as $k=>$v )
        {
            $t = explode( ':', $v, 2 );
            if( isset( $t[1] ) )
                $head[ trim($t[0]) ] = trim( $t[1] );
            else
            {
                $head[] = $v;
                if( preg_match( "#HTTP/[0-9\.]+\s+([0-9]+)#",$v, $out ) )
                    $head['response_code'] = intval($out[1]);
            }
        }
        return $head;
    }

    private static function get_client_ip() {
        $ipaddress = '';
        if (getenv('HTTP_CLIENT_IP'))
            $ipaddress = getenv('HTTP_CLIENT_IP');
        else if (getenv('HTTP_X_FORWARDED_FOR'))
            $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
        else if (getenv('HTTP_X_FORWARDED'))
            $ipaddress = getenv('HTTP_X_FORWARDED');
        else if (getenv('HTTP_FORWARDED_FOR'))
            $ipaddress = getenv('HTTP_FORWARDED_FOR');
        else if (getenv('HTTP_FORWARDED'))
            $ipaddress = getenv('HTTP_FORWARDED');
        else if (getenv('REMOTE_ADDR'))
            $ipaddress = getenv('REMOTE_ADDR');
        else
            $ipaddress = 'UNKNOWN';
        return $ipaddress;
    }

    private static function gen_uuid() {
        return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            // 32 bits for "time_low"
            mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),

            // 16 bits for "time_mid"
            mt_rand( 0, 0xffff ),

            // 16 bits for "time_hi_and_version",
            // four most significant bits holds version number 4
            mt_rand( 0, 0x0fff ) | 0x4000,

            // 16 bits, 8 bits for "clk_seq_hi_res",
            // 8 bits for "clk_seq_low",
            // two most significant bits holds zero and one for variant DCE1.1
            mt_rand( 0, 0x3fff ) | 0x8000,

            // 48 bits for "node"
            mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
            );
    }

}


?>