<?php
include 'dbFunctions.php';
//include 'generate_refid.php';

//////////======= BELOW INCLUDE IS TO CHECK THE LOGIN Authentication ======= ////////
include 'mob_check_api_login.php';

//RECEIVE DATA ////////
$headers2 = getRequestLoginHeaders();
$devId = $headers2['Developerid'];
$devPass = $headers2['Developerpassword'];
$login = $headers2['X-Method-Override'];
//echo "<br>Header:" .json_decode($headers2,true);
//echo "<br>DevId:" . $devId;
//echo "<br>DeveloperPassword:" . $devPass;
//echo "<br>login:" . $login;

//CHECK THE LOGIN Authentication from database  ////////
$auth_result = checklogin($devId,$devPass, $content);

/////////// ======== LOGIN Authentication = END ======== /////////////////////////////

//$auth_result ="SUCCESS";

if ($auth_result =="FAIL") {
///// LOGIN FAIL

}
else
{
///// LOGIN SUCESS & PROCEED


//Make sure that the content type of the POST request has been set to application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';

//if(strcasecmp($contentType, 'application/json') != 0){
//   throw new Exception('Content type must be: application/json');
//}

////////////////////////////////////////// 
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));

//echo "<br>Content:" . $content;
//Attempt to decode the incoming RAW post data from JSON.
$decoded_resp = json_decode($content, true);

$sourceTxnId = $externalReferenceId;



$api_name ='ue_chk_ac.php';


//$merchant_account = $decoded_resp['merchant_account']; 
$merchant_pp = $decoded_resp['merchant_pp']; 
$merchant_ibma_ac = $decoded_resp['merchant_ac']; 


          
//////////////////// MOBILENO - EMPTY
//  if ($idnum ==="" or is_null($idnum)) {
//if ($merchant_account ==="" or is_null($merchant_account)) {
if ($merchant_account ==="") {

              $response_result = array(   
              "errorDetails" =>  array(
              "errorCode" => "3001",
              "errorDescription" => "Merchant Account - cannot be empty."
              ),
              "merchant_ac" => "$merchant_ibma_ac"
              );
        
         $endcode_error= json_encode($response_result);
               
       
        
        $sql_insert = "INSERT INTO mob_api_received (develop_id, develop_pass, merchant_ibma_ac, api_name,data_received, sqlerror,data_response_mob) VALUES ('$devId','$devPass', '$merchant_ibma_ac','$api_name','$content', '$sqlError2','$endcode_error')";
        //echo "<br>memberid:" . $sql_insert;
         
       
       $insert_data = mysql_query($sql_insert);
       
       //echo "<br>SQL:" . $sql_insert . "<br>" ;
       echo $endcode_error;
       
       exit();

}

/////////////CHECK ACCOUNT ID WITH PASSPHRASE //////////////////////


//B_URL + "?requestType=getAccountId&secretPhrase="


//{"errorDescription":"At least one of [secretPhrase, publicKey] must be specified","errorCode":3}

$dataAC = array(
              'requestType' => 'getAccountId',   
              'secretPhrase' => $merchant_pp
               
          );
          
          $postdata = json_encode($dataAC);
          # Create a connection
           
           ///echo "<br>postdata:" . $postdata;
           ///echo "<br>data:" . $data;
           
         // $url = 'http://13.251.39.123:8789/wmp';
          //$url = 'http://18.136.11.63:26876/nxt'; //coal testnet - comment 20250915
         $url = 'https://testcoal.coalculus.com/nxt';
          
          //$url = 'http://52.220.110.100:8286/wic';
          //$url = 'http://18.136.232.117:8384/qtn';
          
          $ch3 = curl_init($url);
          # Form data string
          $postString3 = http_build_query($dataAC, '', '&');
          # Setting our options
          curl_setopt($ch3, CURLOPT_POST, 1);
          curl_setopt($ch3, CURLOPT_POSTFIELDS, $postString3);
          curl_setopt($ch3, CURLOPT_RETURNTRANSFER, true);
          # Get the response
          $response3 = curl_exec($ch3);
          $result3 = json_decode($response3,true);
          
          curl_close($ch3);
          
          //{"accountRS":"WMP-PBGL-B979-7KPR-3TZQQ","publicKey":"5e63b38a0e30a264badd259a796cd631ae486414144c7f8f89bc193e5c27a020","requestProcessingTime":0,"account":"1971443357229688274"}
          
          //$bc_transactionid = $result['transactionJSON']['transaction'];
          $accountRS = $result3['accountRS'];
        // $errCode = $result['errorCode'];
          
          //echo "<br>response:" . $response3;
          
          //echo "<br>accountRS:" . $accountRS . "<bf>";
         
          
          if ($accountRS <> $merchant_ibma_ac){
          
                      $response_result = array(   
                      "errorDetails" =>  array(
                      "errorCode" => "2003",
                      "errorDescription" => "Merchant IBMA account and Password not match!"
                      ),
                      
                       'merchant_ac' => $merchant_ibma_ac
                      );
                
                 $en_response_result= json_encode($response_result);
                       
                 $sql_insert = "INSERT INTO mob_api_received (develop_id, develop_pass, merchant_ibma_ac,data_response_mob, api_name,data_received,data_response_server) VALUES ('$devId','$devPass', '$merchant_ibma_ac','$en_response_result','$api_name','$content','$response3')";
                  
                   //echo "<br>SQL:" . $sql_insert;        
                 
               $insert_data = mysql_query($sql_insert);
             
               echo $en_response_result;
              
               exit();
       
          
          
          }
        
          
//////////////////////////////////////////////////

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

//requestType=getAccountId&secretPhrase="
//requestType=getAccount&account="
//http://13.251.39.123:8789/wmp?requestType=getAccount&account=WMP-8YR9-FS4L-RP7F-FYXUY

/*
$data = array(
              'requestType' => 'getAccount',   
              'account' => $merchant_ibma_ac
              
          );

*/

$data = array(
              'requestType' => 'getBalance', 
              'chain' => '6',
              'account' => $merchant_ibma_ac
              
          );
          
          $postdata = json_encode($data);
          # Create a connection
           
           ///echo "<br>postdata:" . $postdata;
           ///echo "<br>data:" . $data;
           
          //$url = 'http://13.251.39.123:8789/wmp';
           // $url = 'http://18.136.11.63:26876/nxt'; //coal testnet - 20250915
           
           $url = 'https://testcoal.coalculus.com/nxt';
          //$url = 'http://52.220.110.100:8286/wic';
          //$url = 'http://18.136.232.117:8384/qtn';
          
          $ch = curl_init($url);
          # Form data string
          $postString = http_build_query($data, '', '&');
          # Setting our options
          curl_setopt($ch, CURLOPT_POST, 1);
          curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
          # Get the response
          $response = curl_exec($ch);
          $result = json_decode($response,true);
          
          curl_close($ch);
          
          
          //$bc_transactionid = $result['transactionJSON']['transaction'];
          $errDesc = $result['errorDescription'];
          $errCode = $result['errorCode'];
          
          //echo "<br>response:" . $response;
          
          //echo "<br><br>";
          
          
       /*{
    "unconfirmedBalanceNQT": "1000800000",
    "balanceNQT": "1000800000",
    "requestProcessingTime": 0
}
*/
       $amt_acc_bal = $result['balanceNQT'];
        //$accountRS2 = $result['accountRS'];
       
       //echo "accountRS2:" . $accountRS2 . "<br><br>";
       $amt_acc_bal2 = number_format($amt_acc_bal / 1000000,2, '.', ',');
      
        
      //$amt_acc_bal=number_format($result->{'balanceNQT'} / 100000000,2, '.', ',');
      
      //{"errorDescription":"Incorrect \"account\"","errorCode":4}
      
      //$errCode= $result->{'errorCode'};
      //echo "<br>Erro:" . $erro;
      
     /////----------------------------------


      
      if ($errCode == 4){
   
        $response_result = array(   
              "errorDetails" =>  array(
              "errorCode" => "5002",
              "errorDescription" => "Invalid Merchant IBMA account - BC"
              ),
              
               'merchant_ac' => $merchant_ibma_ac
              );
        
         $en_response_result= json_encode($response_result);
               
         $sql_insert = "INSERT INTO mob_api_received (develop_id, develop_pass, merchant_ibma_ac,data_response_mob, api_name,data_received,data_response_server) VALUES ('$devId','$devPass', '$merchant_ibma_ac','$en_response_result','$api_name','$content','$response')";
          
           //echo "<br>SQL:" . $sql_insert;        
         
       $insert_data = mysql_query($sql_insert);
     
       echo $en_response_result;
      
       exit();
       
       

       }
       
          
      $response_result = array(   
                                  "errorDetails" =>  array(
                                  "errorCode" => "0",
                                  "errorDescription" => "Success"
                                  ),
                                    "merchant_ac" => "$merchant_ibma_ac",
                                    "balance" => "$amt_acc_bal2"
                                    
                                  );
                  
                   
                                  
                  $en_response_result= json_encode($response_result);
                         
                  $sql_insert = "INSERT INTO mob_api_received (develop_id, develop_pass, merchant_ibma_ac, data_response_mob, api_name,data_received,data_response_server,data_request_server) VALUES ('$devId','$devPass', '$merchant_ibma_ac','$en_response_result','$api_name','$content','$response','$postdata')";
                  
                   
                   //echo "<br>sql_insert123:" . $sql_insert;
                   
                   $insert_data = mysql_query($sql_insert);
               
                   echo $en_response_result;     

   

    
}

?>