<?php
// Script Version 5.0.1 

//#################################################################################################
//CS-Cart API configuration 
$api_url = "https://www.your-cs-cart-shop.com/api/orders"; //Cs-Cart Api URL
$admin_username = "USER-NAME"; // User Name that Api is enabled
$api_key = 'API-KEY'; // Api Key

//Company ID and Order Status Filters
$company_id = 1; // Cs-Cart Company ID - For Multi Vendors Installation Company ID is Ignored
$connection_password = "00000000000000000000" ;//Connection Password - Put a strong Arithmetical Password
//#################################################################################################





$posted_password  = $_GET['code'];
if ($connection_password != $posted_password  = $_GET['code']) {
echo "Wrong_Password";
die;
}


if ($_GET['cpm'] != ""){
  $company_id  = $_GET['cpm'];
}

//echo "Company ID ===> ".$company_id;
//die;
$action  = $_GET['action'];




//===================Functions START=======================
function remove_not_need_symbols($orderdata){
	//echo $orderdata;
    $newdata = "";
	$newdata = str_replace("*","", $orderdata);
	$newdata = str_replace("~","", $newdata);
	$newdata = str_replace("%","", $newdata);
	$newdata = str_replace("#","", $newdata);
	$newdata = str_replace("&","", $newdata);
	$newdata = str_replace("$","", $newdata);
	$newdata = str_replace("^","", $newdata);
	$newdata = str_replace("{","", $newdata);
	$newdata = str_replace("}","", $newdata);
   return $newdata; 
}

function get_order_based_on_company_id($api_url,$admin_username,$api_key,$company_id){

	$order_statuses = ['O', 'O'];  // 'O' for Open, 'P' for Processed
    // Initialize cURL session
    $ch = curl_init();
    // Build the query string for filters
    $query_string = http_build_query([
       'company_id' => $company_id,
       'status' => $order_statuses,
       'sort_by' => 'timestamp',
       'sort_order' => 'asc'  // Ascending order, last order will be last in the list
     ]);

   // Set the cURL options
   curl_setopt($ch, CURLOPT_URL, "$api_url?$query_string");
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_HTTPHEADER, array(
     'Authorization: Basic ' . base64_encode($admin_username.':'.$api_key),
     'Content-Type: application/json',
   ));

   // Execute the cURL request
    $response = curl_exec($ch);

   // Check for cURL errors
   if (curl_errno($ch)) {
      echo 'Error:' . curl_error($ch);
      curl_close($ch);
      exit;
   }

   // Close the cURL session
   curl_close($ch);

   // Decode the JSON response
   $orders = json_decode($response, true);

   // Display orders
  if (isset($orders['orders']) && !empty($orders['orders'])) {
      foreach ($orders['orders'] as $order) {
          //echo "Order ID: " . $order['order_id'] . "<br>";
          //echo "Customer Name: " . $order['firstname'] . " " . $order['lastname'] . "<br>";
          //echo "Total: " . $order['total'] . "<br>";
          //echo "Status: " . $order['status'] . "<br>";
          //echo "Company ID: " . $order['company_id'] . "<br>";
          //echo "--------------------------<br>";
          return $order['order_id'];
          //break;
      }
   }else{
   	   //echo "No orders found.";
   	   return -99;
   }
	
}

function get_order_details_by_id($api_url,$admin_username,$api_key,$order_number_to_be_printed){

	$string_to_send ="";
	
   // Initialize cURL session
   $ch = curl_init();


   // Set the cURL options
   curl_setopt($ch, CURLOPT_URL, "$api_url/$order_number_to_be_printed");
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Authorization: Basic ' . base64_encode($admin_username.':'.$api_key),
      'Content-Type: application/json',
    ));

    // Execute the cURL request
    $response = curl_exec($ch);

    // Check for cURL errors
    if (curl_errno($ch)) {
       echo 'Error:' . curl_error($ch);
       curl_close($ch);
       exit;
    }

    // Close the cURL session
    curl_close($ch);

    // Decode the JSON response
    $order = json_decode($response, true);


    ///echo "************Order Details*******************";
    $amount_product = count($order['products']); 
    ///echo "<br>Number of Products in order ==>>",$amount_product;
    ///echo "<br>Order ID ==================>>",$order_number_to_be_printed;

    $string_to_send =$amount_product."#".$order_number_to_be_printed;


    // Iterate over the products and echo the product names
    foreach ($order['products'] as $product_id => $product_details) {
       ///echo "<br>Product Name ===============>>" . $product_details['product'] . "<br>";
       ///echo "shipment_amount ============>>". $product_details['shipment_amount'] . "<br>";
      
       $number_of_options = count($product_details['extra']['product_options']);
       
       ///echo "Number of Product options ==>>".$number_of_options."<br>";
       ///echo "Display_subtotal ===========>>". $product_details['display_subtotal'] . "<br>";
       
       $product_name =  $product_details['product'];
       $product_in_order_amount = $product_details['shipment_amount'];
       $product_in_order_cost = $product_details['display_subtotal'];
       
       $product_name = remove_not_need_symbols($product_name);
       
       $string_to_send = $string_to_send."*".$product_name."~".$product_in_order_amount."~".$number_of_options."~".$product_in_order_cost."~";
            
       
       if ($number_of_options > 0){
          ///echo "---------- Options----------<br>";
          foreach($product_details['extra']['product_options_value'] as $row){
     	    $option_name = $row['option_name'];
    	    $option_value = $row['variant_name'];
    	    if ($option_value == "") {
              $option_value = "No-Value";
            }
    	    
            $option_name = remove_not_need_symbols($option_name);
            $option_value = remove_not_need_symbols($option_value);
            
            $string_to_send = $string_to_send.$option_name."~".$option_value."~";
            ///echo $option_name."<--->".$option_value."<br>";
           }
           ///echo "--------------------------------<br>";
         }
        
    }   

    ///echo "-Destination Details-<br>";
      
    $main_phone_number = $order['phone'];
    if ($main_phone_number == "") {
       $main_phone_number = "No-Value";
    }
   
    $main_phone_number = remove_not_need_symbols($main_phone_number);
    ///echo "main_phone_number ==>>>".$main_phone_number."<br>";
    $string_to_send = $string_to_send."%".$main_phone_number."&"; 
   
    
    $location_data = $order['product_groups'][0]['package_info_full']['location'];
    $number_of_address_field = count($location_data = $order['product_groups'][0]['package_info_full']['location']);
    //echo "<br> Number of Adresss fields ====>>>".$number_of_address_field;
    $k = 1;
    foreach ($location_data as $key => $value) {
      //echo ucfirst($key) . ": " . $value . "<br>";
      $address_field = $value;
      if ($address_field == "") {
          $address_field = "No-Value";
      }
     ///echo $address_field."<br>";
      if ($k <  $number_of_address_field){
      	 $address_field =  remove_not_need_symbols($address_field);
         $string_to_send = $string_to_send.$address_field."&";
      }else{
      	 $address_field =  remove_not_need_symbols($address_field);
      	 $string_to_send = $string_to_send.$address_field;
      }
     $k = $k +1; 
    }
    $string_to_send = $string_to_send."%";
     
     ///echo "<br>-Payment Details-<br>";
     $payment_name =  $order['payment_method']['payment'];   
     $payment_descrition =  $order['payment_method']['description']; 

     if ($payment_name == "") {
        //$payment_name = "No-Value";
        $payment_name = "Con";
     }
     if ($payment_descrition == "") {
        //$payment_descrition = "No-Value";
        $payment_descrition = "1-Click";
      }
    
     //echo $payment_name."<br>";
     //echo $payment_descrition."<br>";
     $payment_name = remove_not_need_symbols($payment_name);
     $payment_descrition = remove_not_need_symbols($payment_descrition);
     $string_to_send = $string_to_send."$".$payment_name."~".$payment_descrition."$";
     
     
     //--- Extra Values  
     // First is Always Order Fees in Case there
     $extra_value_info = "Order-Fee-Info";
     //$extra_value_data = "0.0";
     $extra_value_data = $order['shipping_cost'];
     $extra_value_info = remove_not_need_symbols($extra_value_info);
     $extra_value_data = remove_not_need_symbols($extra_value_data);
     $string_to_send = $string_to_send."^".$extra_value_info."^".$extra_value_data."^" ;
     //Order Fees End
     
     
     // ORDER DISCOUNT
     $extra_value_info = "Order-Discount-Info";
     //$extra_value_data = "0.0";
     $extra_value_data = $order['subtotal_discount'];
     $extra_value_info = remove_not_need_symbols($extra_value_info);
     $extra_value_data = remove_not_need_symbols($extra_value_data);
     $string_to_send = $string_to_send.$extra_value_info."^".$extra_value_data."^" ;
     //Order Fees End
     
     $string_to_send = $string_to_send."Description 1"."^"."Value 1"."^" ;
     
          
     ///echo "<br>-Order Note-<br>";
     $order_note =  $order['notes'];
     if ($order_note == "") {
        $order_note = "No-Value";
     }
     ///echo $order_note."<br>";
     ///echo "************Order Details END*******************";
     
     $order_note = remove_not_need_symbols($order_note);     
     $string_to_send = $string_to_send."~".$order_note."~";
     //echo "<br>";
      echo $string_to_send;
     
     //echo "<br>";
     //echo "<pre>"; print_r($order); echo "</pre>";
    
}

function update_order_based_on_company_id($api_url,$admin_username,$api_key,$order_id){

	$api_url = $api_url."/".$order_id;
	// Data to update the order status
    $data = [
       'status' => 'C'  // 'C' stands for Complete
    ];
    
    // Initialize cURL session
    $ch = curl_init();
   
    // Set the cURL options
     curl_setopt($ch, CURLOPT_URL, $api_url);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
     curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
     curl_setopt($ch, CURLOPT_HTTPHEADER, array(
     'Authorization: Basic ' . base64_encode($admin_username.':'.$api_key),
    'Content-Type: application/json',
     ));
    
     // Execute the cURL request
     $response = curl_exec($ch);

     // Check for cURL errors
     if (curl_errno($ch)) {
     	 echo 'Error:' . curl_error($ch);
     	 curl_close($ch);
     	 return "";
     }
     
    // Close the cURL session
    curl_close($ch);

    // Output the response
    //echo $response."<br>";
    // Decode the JSON response to an associative array
    $response_data = json_decode($response, true);
    $responsed_order_id = trim($response_data['order_id']);
    //echo "Responed ID: " . $responsed_order_id . "<br>";
	
    if ($order_id == $responsed_order_id){
		return "Order_status_has_been_changed";
	}else{
		return "";
	}
    
}

//===================Functions END=========================

if ($action == "getnew") {
	$order_number_to_be_printed = get_order_based_on_company_id($api_url,$admin_username,$api_key,$company_id);
    //echo "<br>".$order_number_to_be_printed;

	if ($order_number_to_be_printed <> -99){
		get_order_details_by_id($api_url,$admin_username,$api_key,$order_number_to_be_printed);
	}else{
		echo "NO_ORDER";
	}

}elseif ($action =="update_order") {
    $posted_order_id = $_GET['order_id'];
    $response = update_order_based_on_company_id($api_url,$admin_username,$api_key,$posted_order_id);
	echo $response;
	
}else{
echo "NO_ORDER";
die;
}

 




?>