<?php

    class Electricity extends ApiAccess{
        

         // ------------------------------------------------------------------------------
        // Electricity Bills Payment
        // ------------------------------------------------------------------------------

        //Verify Meter Number
public function validateMeterNummber($body, $electricityid, $provider) {
    $response = array();
    $details = $this->model->getApiDetails();

    //Get API Details
    $host = "https://app.yuniqtelecoms.com.ng/api/electricity/verify/";
            $apiKey = "CoxAC36nvJBlIhi93bzG8BCDc6Crxf2ABxaAx2pd1q084CCAmHCyCbA52EAB1709814144";

    //Set Authentication Type And Parameters
    $aunType = "Basic";

    if (strpos($host, 'n3tdata.com') !== false ||
        strpos($host, 'n3tdata247') !== false ||
        strpos($host, 'legitdataway') !== false ||
        strpos($host, 'bilalsadasub') !== false
    ) {
        $aunType = "Basic";
        $host = $host . "?meter_type=" . $body->metertype . "&disco=" . $electricityid . "&meter_number=" . $body->meternumber;
    } else {
        $aunType = "Token";
        $disconame = str_replace(" ", "-", strtolower($provider));
        $host = $host . "?mtype=" . $body->metertype . "&disconame=" . $disconame . "&disco=" . $electricityid . "&meternumber=" . $body->meternumber;
    }

    // Function to change network ID
    function changeNetworkID($electricityid) {
        switch ($electricityid) {
            case 1:
                return 'ikeja-electric';
            case 2:
                return 'eko-electric';
            case 3:
                return 'kano-electric';
            case 4:
                return 'portharcourt-electric';
            case 5:
                return 'jos-electric';
            case 6:
                return 'ibadan-electric';
            case 7:
                return 'kaduna-electric';
            case 8:
                return 'abuja-electric';
            case 9:
                return 'enugu-electric';
            case 10:
                return 'benin-electric';
            default:
                return $electricityid;
        }
    }

    // Modify $electricityid with the corrected network ID
    $electricityid = changeNetworkID($electricityid);

    $accessToken = $apiKey;
    $endpoint = "https://api-service.vtpass.com/api/merchant-verify";

    // ------------------------------------------
    // Verify Meter No
    // ------------------------------------------

    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $endpoint,
        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 => json_encode(array(
            "billersCode" => $body->meternumber,
            "type" => $body->metertype,
            "serviceID" => $electricityid,
        )),
        CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json',
            "Authorization: Basic $accessToken"
        ),
    ));

    $exereq = curl_exec($curl);
    $err = curl_error($curl);

    if ($err) {
        $response["status"] = "fail";
        $response["msg"] = "Server Connection Error";
        file_put_contents("meter_ver_error_log.txt", json_encode($response) . $err);
        curl_close($curl);
        return $response;
    }

    $result = json_decode($exereq, true);
    curl_close($curl);

    if (isset($result["content"]["Customer_Name"])) {
        $response["status"] = "success";
        $response["msg"] = $result["content"]["Customer_Name"];
        $response["others"] = $result;
    } else {
        $response["status"] = "fail";
        file_put_contents("meter_ver_error_log.txt", json_encode($result) . $host);
    }

    return $response;
}



        //Verify Meter Number
		public function validateMeterNumber($body,$electricityid,$provider){

			$response = array();
            $details=$this->model->getApiDetails();
            
            //Get Ap Details
            $host = "https://n3tdata.com/api/bill/bill-validation";
            $apiKey = "281a8948d4c9a45f34d23c7d769af3c5be9ca96d6f913ecc3c76b52e37fc";

            //Set Authentication Type And Parameters
            $aunType = "Basic";

            if(strpos($host, 'n3tdata') !== false){
                $aunType = "Basic";
                $host = $host . "?meter_type=".$body->metertype."&disco=".$electricityid."&meter_number=".$body->meternumber;
            }
            elseif (strpos($host, 'bilalsadasub') !== false){
                $aunType = "Basic";
                $host = $host . "?meter_type=".$body->metertype."&disco=".$electricityid."&meter_number=".$body->meternumber;
            }
            else{
                $aunType = "Token";
                $disconame = str_replace(" ","-",strtolower($provider));
                $host = $host . "?mtype=".$body->metertype."&disconame=".$disconame."&disco=".$electricityid."&meternumber=".$body->meternumber;
            }
            
           
             
            // ------------------------------------------
            //  Verify Meter No
            // ------------------------------------------
        
            $curl = curl_init();
            curl_setopt_array($curl, array(
            CURLOPT_URL => $host,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                "Authorization: $aunType $apiKey"
            ),
            ));

            $exereq = curl_exec($curl);
            $err = curl_error($curl);
            
            if($err){
                $response["status"] = "fail";
                $response["msg"] = "Server Connection Error";
                file_put_contents("meter_ver_error_log.txt",json_encode($response).$err);
                curl_close($curl);
                return $response;
            }

 
            $result=json_decode($exereq);
            curl_close($curl);
            
           
            if(isset($result->Customer_Name)){
                $response["status"] = "success";
                $response["msg"] = $result->Customer_Name;
                $response["others"] = $result;
            }
            elseif(isset($result->name)){
                $response["status"] = "success";
                $response["msg"] = $result->name;
                $response["others"] = $result;
            }
            else{
                $response["status"] = "fail";
                file_put_contents("meter_ver_error_log.txt",json_encode($result).$host);
            }

            return $response;
		}
		
		

        //Purchase Electricity Unit
		public function purchaseElectricityToken($body,$electricityid,$provider){

			
            $response = array();
            $details=$this->model->getApiDetails();
            
            //Get Ap Details
            $host = "https://app.yuniqtelecoms.com.ng/api/electricity/";
            $apiKey = "CoxAC36nvJBlIhi93bzG8BCDc6Crxf2ABxaAx2pd1q084CCAmHCyCbA52EAB1709814144";

            // ------------------------------------------
            //  Purchase Electricity
            // ------------------------------------------
            $curl = curl_init();
            curl_setopt_array($curl, array(
            CURLOPT_URL => $host,
            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 =>'{
                "disco_name": "'.$electricityid.'",
                "meter_number": "'.$body->meternumber.'",
                "MeterType": "'.ucfirst($body->metertype).'",
                 "metertype": "'.ucfirst($body->metertype).'",
                "amount": "'.$body->amount.'",
                "phone" :  "'.$body->meternumber.'"
            }',
            
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                "Authorization: Token $apiKey"
            ),
            ));

            $exereq = curl_exec($curl);

            $err = curl_error($curl);
            
            if($err){
                $response["status"] = "fail";
                $response["msg"] = "Server Connection Error: ".$err;
                file_put_contents("meter_purchase_error_log.txt",json_encode($response));
                curl_close($curl);
                return $response;
            }

            $result=json_decode($exereq);
            curl_close($curl);

            if($result->Status=='successful' || $result->status=='success'){
                $response["status"] = "success";
                $response["msg"] = $result->token;
            }
            else{
                 
                $response["status"] = "fail";
                $response["msg"] = $result->msg;
                file_put_contents("meter_purchase_error_log.txt",json_encode($body));
            }

            return $response;
		}

        //Purchase Electricity Unit
		public function purchaseMeterWithBasicAuthentication($body,$host,$hostuserurl,$apiKey,$electricityid,$provider){

            // ------------------------------------------
            //  Get User Access Token
            // ------------------------------------------
             
            $curlA = curl_init();
            curl_setopt_array($curlA, array(
                CURLOPT_URL => $hostuserurl,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'GET',
                CURLOPT_HTTPHEADER => array(
                    "Authorization: Basic  $apiKey",
                    'Content-Type: application/json'
                ),
            ));
        
            $exereqA = curl_exec($curlA);
            $err = curl_error($curlA);
            
            if($err){
                $response["status"] = "fail";
                $response["msg"] = "Server Connection Error: ".$err;
                file_put_contents("meter_purchase_error_log.txt",json_encode($response));
                curl_close($curlA);
                return $response;
            }
            $resultA=json_decode($exereqA);
            $apiKey=$resultA->AccessToken;
            curl_close($curlA);
        
           
            // ------------------------------------------
            //  Purchase Electricity
            // ------------------------------------------
        
            $curl = curl_init();
            curl_setopt_array($curl, array(
            CURLOPT_URL => $host,
            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 =>'{
                "disco": "'.$electricityid.'",
                "meter_type": "'.$body->metertype.'",
                "meter_number": "'.$body->meternumber.'",
                "bypass":true,
                "request-id" : "'.$body->ref.'",
                "amount": "'.$body->amount.'",
                "phone": "'.$body->phone.'"
            }',
            
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                "Authorization: Token $apiKey"
            ),
            ));

            $exereq = curl_exec($curl);

            $err = curl_error($curl);
            
            if($err){
                $response["status"] = "fail";
                $response["msg"] = "Server Connection Error: ".$err;
                file_put_contents("meter_purchase_error_log.txt",json_encode($response));
                curl_close($curl);
                return $response;
            }

            $result=json_decode($exereq);
            curl_close($curl);

           

            if($result->status=='successful' || $result->status=='success'){
                $response["status"] = "success";
                $response["msg"] = $result->token;
            }
            else{
                $response["status"] = "fail";
                $response["msg"] = "Server/Network Error: ".$result->msg;
                file_put_contents("meter_purchase_error_log.txt",json_encode($result));
            }

            return $response;
		}





public function purchaseMeterWithVTPASS($body,$host,$hostuserurl,$apiKey,$electricityid,$provider) {
    $response = array();

    // Function to change network ID
    function changeNetworkID($electricityid) {
        switch ($electricityid) {
            case 1:
                return 'ikeja-electric';
            case 2:
                return 'eko-electric';
            case 3:
                return 'kano-electric';
            case 4:
                return 'portharcourt-electric';
            case 5:
                return 'jos-electric';
            case 6:
                return 'ibadan-electric';
            case 7:
                return 'kaduna-electric';
            case 8:
                return 'abuja-electric';
            case 9:
                return 'enugu-electric';
            case 10:
                return 'benin-electric';
            default:
                return $electricityid;
        }
    }

    // Modify $electricityid with the corrected network ID
    $electricityid = changeNetworkID($electricityid);

    $accessToken = $apiKey;
    $endpoint = "https://api-service.vtpass.com/api/pay";

    // Function to generate a unique request ID
function generateRequestID() {
    $timezone = new DateTimeZone("Africa/Lagos");
    $now = new DateTime("now", $timezone);
    $currentDate = $now->format("YmdHis");
    $randomString = substr(md5(uniqid(rand(), true)), 0, 12);
    return $currentDate . $randomString;
}


    // Generate a unique request ID
    $requestId = generateRequestID();

    // Define the request data
    $requestData = array(
        "request_id" => $requestId,
        "serviceID" => $electricityid,
        "billersCode" => $body->meternumber,
        "variation_code" => "prepaid",
        "phone" => $body->phone,
        "amount" => $body->amount
    );

    // Define the request headers
    $headers = array(
        "Authorization: Basic $accessToken",
        "Content-Type: application/json"
    );

    // Purchase Cable Plan
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $endpoint,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($requestData),
        CURLOPT_SSL_VERIFYPEER => false, // Use only for development/testing purposes
    ));

    $exereq = curl_exec($curl);
    $err = curl_error($curl);

    if ($err) {
        $response["status"] = "fail";
        $response["msg"] = "Server Connection Error: " . curl_error($curl);
        file_put_contents("cable_error_log2.txt", json_encode($response));
        curl_close($curl);
        return $response;
    }

    $result = json_decode($exereq);
    curl_close($curl);

    if ($result->code === '000' || $result->status === 'success') {
    $response["status"] = "success";
    // Use the result->token if it exists, otherwise use result->mainToken
    $response["msg"] = isset($result->token) ? $result->token : $result->mainToken;
} else {
    $response["status"] = "fail";
    $response["msg"] = "Server/Network Error: " . $result->msg;
    file_put_contents("cable_error_log.txt", json_encode($result));
}


    return $response;
}


    }

?>