<?php

namespace App\Controllers;

use App\Models\Md_student;
use App\Models\Md_sms;
use App\Models\Md_cms;
$session = \Config\Services::session();

class Payment extends BaseController
{
    
    
    public function __construct() {
         $this->Md_login = new Md_student();
         $this->Md_sms= new Md_sms();
         $this->Md_cms= new Md_cms();
         helper('text');
    }
    
    
    
      public function PaymentRequestSend() {

        $ArrayFinal=$this->Md_login->PaymentGatewayConfig('CCAvenues');

        $url = "";
        $html = "";
        $Finalurl = "";
        $merchantkey = "";
        $workingkey = "";
        $accesskey = "";
        //get hostel list ::-

        if (!empty($ArrayFinal)) {
            $Finalurl = "";
            $merchantkey = "";
            $workingkey = "";
            $accesskey = "";
            if ($ArrayFinal->livenow == "1") {
                $Finalurl =$ArrayFinal->liveurl;
                $merchantkey =$ArrayFinal->livemerchantkey;
                $workingkey = $ArrayFinal->liveworkingkey;
                $accesskey = $ArrayFinal->liveaccesskey;
            } else if ($ArrayFinal->livenow == "2") {
                $Finalurl = $ArrayFinal->testurl;
                $merchantkey = $ArrayFinal->testmerchantkey;
                $workingkey = $ArrayFinal->testworkingkey;
                $accesskey = $ArrayFinal->testaccesskey;
            }
        }

         $Finalurl = $ArrayFinal->testurl;
         $merchantkey =$ArrayFinal->testmerchantkey;
         $workingkey = $ArrayFinal->testworkingkey;
         $accesskey =$ArrayFinal->testaccesskey;

        $merchant_data = $merchantkey;
        $working_key = $workingkey; //Shared by CCAVENUES
        $access_code = $accesskey; //Shared by CCAVENUES
        
        $url = $Finalurl;
   
        if (!empty($_POST)) {
           
            foreach ($_POST as $key => $value) {
                $merchant_data .= $key . '=' . $value . '&';
            }
     
            $encrypted_data = $this->encrypt($merchant_data, $working_key); // Method for encrypting the data.

            $html .= '<html><script src="https://code.jquery.com/jquery-1.12.4.js"></script>
                        <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
                        <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
                        <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
                        <!------ Include the above in your HEAD tag ---------->
                        <style>
                            .animationload {
                            background-color: #fff;
                            height: 100%;
                            left: 0;
                            position: fixed;
                            top: 0;
                            width: 100%;
                            z-index: 10000;
                        }
                        .osahanloading {
                            animation: 1.5s linear 0s normal none infinite running osahanloading;
                            background: #fed37f none repeat scroll 0 0;
                            border-radius: 50px;
                            height: 50px;
                            left: 50%;
                            margin-left: -25px;
                            margin-top: -25px;
                            position: absolute;
                            top: 50%;
                            width: 50px;
                        }

                        .osahanloading::after {
                            animation: 1.5s linear 0s normal none infinite running osahanloading_after;
                            border-color: #85d6de transparent;
                            border-radius: 80px;
                            border-style: solid;
                            border-width: 10px;
                            content: "";
                            height: 80px;
                            left: -15px;
                            position: absolute;
                            top: -15px;
                            width: 80px;
                        }

                        @keyframes osahanloading {
                        0% {
                            transform: rotate(0deg);
                        }
                        50% {
                            background: #85d6de none repeat scroll 0 0;
                            transform: rotate(180deg);
                        }
                        100% {
                            transform: rotate(360deg);
                        }
                        }
                        </style>

                    <div class="container">
                            <div class="row">
                                    <div class="text-center">
                                <h2>Creative Animated Loading icon in HTML5 CSS3</h2>
                            </div>
                            <div class="animationload">
                                <div class="osahanloading"></div>
                            </div>
                            </div>
                    </div><form method="post" name="redirect" action="' . $url . '">';
            $html .= "<input type='text' name=encRequest value=$encrypted_data>";
            $html .= "<input type='text' name=access_code value=$access_code>";
            $html .= '</form>
                            </center>
                            <script language="javascript">document.redirect.submit();</script>
                            </body>
                            </html>';
            echo $html;
        }
    }
    
    
    public function Index($loginid,$formid)
    {
          $ArrayUserInfo=$this->Md_login->FormDataOfStudent($loginid,$formid);
          $paymentGateConfig=$this->Md_login->PaymentGatewayConfig('Ccavenues');
    
          $ArrayPrice=$this->Md_login->HostelFeesmst();

         if (!empty($ArrayPrice)) {
            $hPrice = $ArrayPrice->amount;
         }

         if(empty($ArrayUserInfo))
         {
            return redirect()->to('https://www.mvpm.org/hostel/ccavenue-feedback/5/'.$loginid);
         }
      
        $selected_hostel =$ArrayUserInfo->selected_hostel;
        $ArrrayHotels = explode(',', $selected_hostel);
        $HostelCounts = count($ArrrayHotels);
        $totalPrice = ($hPrice * $HostelCounts);
       
        $data['order_id']= random_string('basic', 20);
       
    //   echo '<pre>';
    //       print_r($paymentGateConfig);
    //       die;
        // $ArrayUserInfo="";
        
        
        if (!empty($paymentGateConfig)) {
            if ($paymentGateConfig->livenow == "1") {
                $liveaccesskey=$paymentGateConfig->livemerchantkey;
            } else if ($paymentGateConfig->livenow == "2") {
                $liveaccesskey = $paymentGateConfig->testmerchantkey;
            }
        }
           
        $livemerchandkey = $paymentGateConfig->testmerchantkey;
       
        $data['totalPrice']=$totalPrice;
        $data['liveaccesskey']=$livemerchandkey;
        $data['loginid']=$loginid;
        $data['formid']=$formid;
        $data['ArrayUserInfo']=$ArrayUserInfo;
        $data['paymentGateConfig']=$paymentGateConfig;
        return view('ccavenue',$data);
    }
    
    
    public function CcavenueResponse()
    {
       
        
       $request = \Config\Services::request();
       $encResp=  $request->getPost('encResp');
       $orderNo=$request->getPost('orderNo');
       $crossSellUrl=$request->getPost('crossSellUrl');
       $accessCode=$request->getPost('accessCode');

       $ArrayFinal=$this->Md_login->PaymentGatewayConfig('CCAvenues');

        $url = "";
        $html = "";
        $Finalurl = "";
        $merchantkey = "";
        $workingkey = "";
        $accesskey = "";
        //get hostel list ::-

        if (!empty($ArrayFinal)) {
            $Finalurl = "";
            $merchantkey = "";
            $workingkey = "";
            $accesskey = "";
            if ($ArrayFinal->livenow == "1") {
                $Finalurl =$ArrayFinal->liveurl;
                $merchantkey =$ArrayFinal->livemerchantkey;
                $workingkey = $ArrayFinal->liveworkingkey;
                $accesskey = $ArrayFinal->liveaccesskey;
            } else if ($ArrayFinal->livenow == "2") {
                $Finalurl = $ArrayFinal->testurl;
                $merchantkey = $ArrayFinal->testmerchantkey;
                $workingkey = $ArrayFinal->testworkingkey;
                $accesskey = $ArrayFinal->testaccesskey;
            }
        }

         $Finalurl = $ArrayFinal->testurl;
         $merchantkey =$ArrayFinal->testmerchantkey;
         $workingkey = $ArrayFinal->testworkingkey;
         $accesskey =$ArrayFinal->testaccesskey;
         
        $workingKey = $workingkey;
        $encResponse = $encResp;   //This is the response sent by the CCAvenue Server
        $rcvdString = $this->decrypt($encResponse, $workingKey);   //Crypto Decryption used as per the specified working key.
        
   
        $order_status = "";
        $decryptValues = explode('&', $rcvdString);
        $dataSize = sizeof($decryptValues);
        $information = explode('=', $decryptValues[15]);
        $uids = explode('-', $information[1]);
        
        $tempLoginid= explode('=', $decryptValues[29]);
        $loginid=$tempLoginid[1];
       
        $tempFormid= explode('=', $decryptValues[28]);
        $formid=$tempFormid[1];
        
        $tempPaymentStatus= explode('=', $decryptValues[3]);
        $status=$tempPaymentStatus[1];
     
        $tempTracking= explode('=', $decryptValues[1]);
        $refid=$tempTracking[1];
        
        $tempOrder= explode('=', $decryptValues[0]);
        $orderid=$tempOrder[1];
        
        $table = "ccavenue_logs";
        $insertData = array(
                'loginid' => $loginid,
                'formid' => $formid,
                'payment_status'=>$status,
                'reuqstlog' => json_encode($request->getPost()),
                'created_date' => date('Y-m-d H:i:s'),
                'ip_address' => $_SERVER['REMOTE_ADDR']
            );

        $this->Md_login->InsertLoginAction($table, $insertData);
        
        $table = "hostel_student";
        $updareData = array('payment_status' =>1,'payment_date'=> date('Y-m-d H:i:s'),'cron_recheck'=>1,'fromStatus'=>2,'order_id'=>$orderid,'order_status'=>'TXN_SUCCESS');
        $condition = array('fk_login_id'=>$loginid,'pk_id'=>$formid);
        $this->Md_login->UpdateData($table, $condition, $updareData);
        
        return redirect()->to('https://www.mvpm.org/hostel/ccavenue-feedback/1/'.$loginid.'/'.$formid); 
    }
    
     public function CcavenueCancelled()
    {
       $request = \Config\Services::request();
       $encResp=  $request->getPost('encResp');
       $orderNo=$request->getPost('orderNo');
       $settingIntegrationType=$request->getPost('settingIntegrationType');
       $accessCode=$request->getPost('accessCode');

       $ArrayFinal=$this->Md_login->PaymentGatewayConfig('CCAvenues');

        $url = "";
        $html = "";
        $Finalurl = "";
        $merchantkey = "";
        $workingkey = "";
        $accesskey = "";
        //get hostel list ::-

        if (!empty($ArrayFinal)) {
            $Finalurl = "";
            $merchantkey = "";
            $workingkey = "";
            $accesskey = "";
            if ($ArrayFinal->livenow == "1") {
                $Finalurl =$ArrayFinal->liveurl;
                $merchantkey =$ArrayFinal->livemerchantkey;
                $workingkey = $ArrayFinal->liveworkingkey;
                $accesskey = $ArrayFinal->liveaccesskey;
            } else if ($ArrayFinal->livenow == "2") {
                $Finalurl = $ArrayFinal->testurl;
                $merchantkey = $ArrayFinal->testmerchantkey;
                $workingkey = $ArrayFinal->testworkingkey;
                $accesskey = $ArrayFinal->testaccesskey;
            }
        }

         $Finalurl = $ArrayFinal->testurl;
         $merchantkey =$ArrayFinal->testmerchantkey;
         $workingkey = $ArrayFinal->testworkingkey;
         $accesskey =$ArrayFinal->testaccesskey;

        $workingKey = $workingkey;
        $encResponse = $encResp;   //This is the response sent by the CCAvenue Server
        $rcvdString = $this->decrypt($encResponse, $workingKey);   //Crypto Decryption used as per the specified working key.
        
   
        $order_status = "";
        $decryptValues = explode('&', $rcvdString);
        $dataSize = sizeof($decryptValues);
        $information = explode('=', $decryptValues[15]);
        $uids = explode('-', $information[1]);
        
        $tempLoginid= explode('=', $decryptValues[29]);
        $loginid=$tempLoginid[1];
       
        $tempFormid= explode('=', $decryptValues[28]);
        $formid=$tempFormid[1];
        
     
        
        $tempPaymentStatus= explode('=', $decryptValues[3]);
        $status=$tempPaymentStatus[1];
        
           
        $table = "ccavenue_logs";
        $insertData = array(
                'loginid' => $loginid,
                'formid' => $formid,
                'payment_status'=>$status,
                'reuqstlog' => json_encode($request->getPost()),
                'created_date' => date('Y-m-d H:i:s'),
                'ip_address' => $_SERVER['REMOTE_ADDR']
            );


        $this->Md_login->InsertLoginAction($table, $insertData);
        
        $tempTracking= explode('=', $decryptValues[1]);
        $refid=$tempTracking[1];
        
        $tempOrder= explode('=', $decryptValues[0]);
        $orderid=$tempOrder[1];
   
   
         $html = '<!DOCTYPE html>
                    <html lang="en">
                    <head>
                      <meta charset="UTF-8">
                      <meta name="viewport" content="width=device-width, initial-scale=1.0">
                      <link rel="stylesheet" href="style.css">
                      <title>Paytm Loading</title>
                      <style>
                     .wrap,body{display:flex}body{margin:0;padding:0;height:100vh;width:100%;justify-content:center;align-items:center}.wrap{height:150px;width:150px;justify-content:center;align-items:center}.five,.four,.one,.three,.two{border-radius:100%;margin:1vw;animation:1s infinite alternate animate}.one,.three,.two{border:10px solid #00f}@keyframes animate{0%{transform:scale(1)}100%{transform:scale(1.2)}}.one{animation-delay:.2s}.two{animation-delay:.4s}.three{animation-delay:.6s}.five,.four{border:10px solid #0ff}.four{animation-delay:.8s}.five{animation-delay:1s}
                    </style>
                    </head>
                    <body>
                      <div class="wrap">
                        <div class="one"></div>
                        <div class="two"></div>
                        <div class="three"></div>
                        <div class="four"></div>
                        <div class="five"></div>
                      </div>
                    </body>
                    </html>';
            echo $html;
            
        flush(); //this sends the output to the client. You may also need ob_flush();
        sleep(20); //wait 20 seconds 
      
        $resultRecheck= $this->paymentCheckingAgains($orderid,$refid,$workingkey,$accesskey);
          
        if($resultRecheck==1)
        {
            
            
            $table = "hostel_student";
            $updareData = array('payment_status' =>1,'payment_date'=> date('Y-m-d H:i:s'),'cron_recheck'=>1,'fromStatus'=>2,'order_id'=>$orderid,'order_status'=>'TXN_SUCCESS');
            $condition = array('fk_login_id'=>$loginid,'pk_id'=>$formid);
            $this->Md_login->UpdateData($table, $condition, $updareData);
        
            return redirect()->to('https://www.mvpm.org/hostel/ccavenue-feedback/1/'.$loginid.'/'.$formid); 
        }else {

            return redirect()->to('https://www.mvpm.org/hostel/ccavenue-feedback/5/'.$loginid.'/'.$formid); 
        }
    }
    
    
    
      public function paymentCheckingAgains($orderid = null, $refid = null,$working_key=null,$access_code=null) {
        error_reporting(-1);
        error_reporting(E_ALL);
        ini_set("display_errors", 1);
        //$URL = "https://api.ccavenue.com/apis/servlet/DoWebTrans";
         $URL='https://apitest.ccavenue.com/apis/servlet/DoWebTrans';

        $merchant_json_data = array(
            'reference_no' => $refid,
            'order_no' => $orderid
        );

        $merchant_data = json_encode($merchant_json_data);
        $encrypted_data = $this->encrypt($merchant_data, $working_key);
        $final_data = "request_type=JSON&access_code=" . $access_code . "&command=orderStatusTracker&version=1.2&response_type=JSON&enc_request=" . $encrypted_data;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $URL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $final_data);

        $result = curl_exec($ch);
        curl_close($ch);
        $information = explode('&', $result);
        $dataSize = sizeof($information);
        $status1 = explode('=', $information[0]);
        $status2 = explode('=', $information[1]);

        if ($status1[1] == '1') {
            $recorddata = $status2[1];
            return 2;
        } else {
            $status = $this->decrypt(trim($status2[1]), $working_key);
            $finalcheck = json_decode(strstr($status, '}', true) . '}');
            $orderStatus = (!empty($finalcheck->order_status) ? $finalcheck->order_status : 'Fail');
            if ($orderStatus == "Shipped" || $orderStatus == "Success") {
                return 1;
            } else {
                return 2;
            }
        }
    }
    
    public function encrypt($plainText, $key) {

        $key = $this->hextobin(md5($key));
        $initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
        $openMode = openssl_encrypt($plainText, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $initVector);
        $encryptedText = bin2hex($openMode);
        return $encryptedText;
    }

   function decrypt($encryptedText, $key) {
      
        $key = $this->hextobin(md5($key));
        $initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
        $encryptedText = $this->hextobin($encryptedText);
        $decryptedText = openssl_decrypt($encryptedText, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $initVector);
        return $decryptedText;
    }

   
    public function hextobin($hexString) {
        $length = strlen($hexString);
        $binString = "";
        $count = 0;
        while ($count < $length) {
            $subString = substr($hexString, $count, 2);
            $packedString = pack("H*", $subString);
            if ($count == 0) {
                $binString = $packedString;
            } else {
                $binString .= $packedString;
            }
            $count += 2;
        }
        return $binString;
    }
}
