<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\GateConfiguration;
use App\Models\Settings;
use App\Models\Transaction;
use App\Models\FastagEntry;
use App\Models\FastagErrorList;
use DB;
use App\Traits\FastagEngineCallAPI;

class FastagReqChkTxn extends Command
{
    use FastagEngineCallAPI;

    public $Gate;
    public $Settings;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'FastagReqChkTxn';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fastag Txn Status Check';

    /**
     * Execute the console command.
     *
     * @return mixed
     */

    public function handle()
    {
        DB::beginTransaction();
        $logPath = storage_path() . '/logs/fastag_req_pay/';
        $fastagEntries =  DB::select("SELECT *  from `sps_transactions` LEFT join sps_cps on sps_cps.transaction_id = sps_transactions.id  where sps_transactions.fastag_pay NOT IN ('ACCEPTED','DECLINED','pending') AND sps_transactions.fastag_messageId is not null AND sps_transactions.deleted_at is null LIMIT 5");
        //print_r($fastagEntries);
        $vehicleDetails = [];
        $this->Gate = new GateConfiguration();
        $this->Settings = new Settings();
        $holeTime = 0; //1 min
        try {
            $now = strtotime(date('Y-m-d H:i:s'));
            if (!empty($fastagEntries)) {

                //dd($fastagEntries);
                //die("here");

                foreach ($fastagEntries as $entry) {

                        $entry = (array)$entry;
                        $fastagReqpayRequestCount = $entry['fastag_reqpay_req_count'];
                        $fastagPayStatus = $entry['fastag_pay'];

                        $isReqCheckCalled = false;

                        
                        if($fastagReqpayRequestCount == 0 AND $fastagPayStatus == "pending"){
                            return null;
                        }

                        
                        $fastagReqcheckRequestCount = $entry['fastag_reqcheck_req_count'];
                        $fastagReqcheckRequestDate = $entry['fastag_reqcheck_req_datetime'];
                        $delayMinutes = $fastagReqcheckRequestCount * 2;
                        $callTime =strtotime("+" . $delayMinutes . " minutes", strtotime($fastagReqcheckRequestDate));
                        
                        if ($fastagReqcheckRequestCount == 0) {
                            // Call immediately if fastag_reqpay_req_time is 0
                            $isReqCheckCalled = true;
                            $this->fastagReqCheckApi($entry,$fastagReqcheckRequestCount);
                            
                            //$this->testFastagReqCheckApi($entry,$fastagReqcheckRequestCount);
                        } elseif ($now >= $callTime) {
                            // Call after the calculated delay time
                            
                            $isReqCheckCalled = true;
                            $this->fastagReqCheckApi($entry,$fastagReqcheckRequestCount);
                            //$this->testFastagReqCheckApi($entry,$fastagReqcheckRequestCount);

                        }else{
                            $isReqCheckCalled = false;
                            //print_r("next call will be in min "+$callTime);
                        }


                        if($isReqCheckCalled){
                            $data0["fastag_reqcheck_req_count"] = $fastagReqcheckRequestCount+1;
                            $data0["fastag_reqcheck_req_datetime"] = date("Y-m-d H:i:s");
                            $updateTransactionForReqCheckCount = Transaction::where('id',$entry['id'])->update($data0);
                        }

                        //sleep(5);
                    //}
                }
                DB::commit();
            } else {
                throw new \Exception("FASTag Req Tag Details API -- Data not found");
            }

        } catch (\Exception $exception) {
            DB::rollback();
		dd($exception->getMessage());
            $this->createLog(false, $logPath, "FASTag Request Pay", json_encode($fastagEntries), $exception->getMessage());
        }
    }


    public function fastagReqCheckApi($entry,$fastagReqcheckRequestCount){

        //DB::beginTransaction();
        $vehicleDetails = [];
        $this->Gate = new GateConfiguration();
        $this->Settings = new Settings();
        $holeTime = 0; //1 min


        try {



            $response = $this->fastagReqChkTxn($entry);
            if($response != false){
 
             if(count($response['Txn']['Resp']['TxnStatusReqList']['Status']['TxnList']) > 1){

	           $txnStatus = "";
		   $errCode = "" ;
		   $fastagTxnId = "" ;
		   $ReqChkTxnId = "" ;  

	           foreach ($response['Txn']['Resp']['TxnStatusReqList']['Status']['TxnList'] as $txnList){
                            print_r($txnList);
		        $errCode = $txnList['@attributes']['errCode'];
                        $fastagTxnId = $response['Txn']['Resp']['TxnStatusReqList']['Status']['@attributes']['txnId'];
                        $ReqChkTxnId = $response['Txn']['@attributes']['id'];
	
                        $result = $txnList['@attributes']['txnStatus'];

                        $txnStatus = "";

                        if($result == "SUCCESS"){
                            $txnStatus = "ACCEPTED";
                            break;
                        }elseif($result == "FAILURE"){
                            $txnStatus = "DECLINED";
                        }elseif($result == "DECLINED"){
                            $txnStatus = "DECLINED";
                        }
		   

		   }
                   //print_r($txnStatus);

                    //die("www");       //nishant

		             $data["fastag_pay"] = $txnStatus;
                    $responseCode = $errCode;
                    $transactionId = $entry['id'];

                    $errorMsg = FastagErrorList::where('error_code', $responseCode)->get()->first();

                    //if (!empty($errorMsg)) {
                    $data["fastag_comment"] = "ResChkTxn|".$responseCode."|".$errorMsg->description."|".$ReqChkTxnId;
                    //}

                    print_r($data["fastag_comment"]);
                   // die("here");
                    // $data["fastag_messageId"] = $response;
                    // $data["fastag_pay"] = "inprocess";
                    // $data["fastag_comment"] = "ReqPay Api intiated, Waiting for response";
		//print_r($entry);        
             //print_r("-------");
			
		//	print_r($transactionId);
        		//die("here");             
	//DB::enableQueryLog();
                    $updateTransaction = Transaction::where('id', $transactionId)->update($data);
          //          print_r(DB::getQueryLog());
	//		print_r($updateTransaction);

//die("here1");


	     }else{
 
               // die("here11");

		 if(!empty($response['Txn']['Resp']['TxnStatusReqList']['Status']['TxnList']['@attributes']['txnStatus'])){

                    $result = $response['Txn']['Resp']['TxnStatusReqList']['Status']['TxnList']['@attributes']['txnStatus'];

                    //$txnStatus = "";

                    if($result == "SUCCESS"){
                        $txnStatus = "ACCEPTED";
                    }elseif($result == "FAILURE"){
                        $txnStatus = "DECLINED";
                    }elseif($result == "DECLINED"){
                        $txnStatus = "DECLINED";
                    }else{
                        $txnStatus = "inprocess";
                    }


                    $errCode = $response['Txn']['Resp']['TxnStatusReqList']['Status']['TxnList']['@attributes']['errCode'];
                    $fastagTxnId = $response['Txn']['Resp']['TxnStatusReqList']['Status']['@attributes']['txnId'];
                    $ReqChkTxnId = $response['Txn']['@attributes']['id'];
                    print_r("----###".$fastagTxnId."###----");


                    $data["fastag_pay"] = $txnStatus;
                    $responseCode = $errCode;
                    $transactionId = $entry['id'];

                    $errorMsg = FastagErrorList::where('error_code', $responseCode)->get()->first();

                    //if (!empty($errorMsg)) {
                    $data["fastag_comment"] = "ResChkTxn|".$responseCode."|".$errorMsg->description."|".$ReqChkTxnId;
                    //}

                    print_r($data["fastag_comment"]);

                    // $data["fastag_messageId"] = $response;
                    // $data["fastag_pay"] = "inprocess";
                    // $data["fastag_comment"] = "ReqPay Api intiated, Waiting for response";

                    $updateTransaction = Transaction::where('id', $transactionId)->update($data);
                    

                    // $this->createLog(true, $logPath, "FASTag Request Pay", $entry, json_encode($response));
                }
}
            }

            //DB::commit();

        } catch (\Exception $exception) {
            dd($exception->getMessage());
            //DB::rollback();
            throw new \Exception("FASTag Req Tag Details API ");
        }
    }


    public function testFastagReqCheckApi($entry,$fastagReqcheckRequestCount){

        //DB::beginTransaction();
        $vehicleDetails = [];
        $this->Gate = new GateConfiguration();
        $this->Settings = new Settings();
        $holeTime = 0; //1 min

        try {
            //DB::commit();


            $response = true;

            if($response != false){


                    $result = "pending"; //change here for test txn status

                    $txnStatus = "";

                    if($result == "SUCCESS"){
                        $txnStatus = "ACCEPTED";
                    }elseif($result == "FAILURE"){
                        $txnStatus = "DECLINED";
                    }


                    $errCode = "00"; //00 for success
                    $fastagTxnId = "1234567890"; //dummy txnID
                    $ReqChkTxnId = "1111111111"; //dymmu fastagTxnId
                    print_r("###".$fastagTxnId."###");


                    $data["fastag_pay"] = $txnStatus;
                    $responseCode = $errCode;
                    $transactionId = $entry['id'];

                    $errorMsg = FastagErrorList::where('error_code', $responseCode)->get()->first();

                    //if (!empty($errorMsg)) {
                    $data["fastag_comment"] = "ResChkTxn|".$responseCode."|".$errorMsg->description."|".$ReqChkTxnId;
                    //}

                    print_r($data["fastag_comment"]);

                    // $data["fastag_messageId"] = $response;
                    // $data["fastag_pay"] = "inprocess";
                    // $data["fastag_comment"] = "ReqPay Api intiated, Waiting for response";

                   // $updateTransaction = Transaction::where('id', $transactionId)->update($data);
                    

                    // $this->createLog(true, $logPath, "FASTag Request Pay", $entry, json_encode($response));

            }

            //DB::commit();

        } catch (\Exception $exception) {
            print_r($exception->getMessage());
            //DB::rollback();
            throw new \Exception("FASTag Req Tag Details API ");
        }
    }



}