<?php 
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include_once('config.php');
require('vendor/autoload.php');
use Shopify\PuplicApp;
use rdx\graphqlquery\Query;


$client = new Shopify\PublicApp($SHOPIFY_SHOP_DOMAIN, $SHOPIFY_API_KEY, $SHOPIFY_API_SECRET, $api_params);
  $client->setAccessToken($SHOPIFY_TOKEN);
  

// Retrieve the request's body
$input = @file_get_contents("php://input");

// Decode the JSON payload
$data = json_decode($input, true);

// Extract the order ID
$order_id = $data['id'];

// Log the order ID (optional, for debugging purposes)
file_put_contents('order_log.txt', 'Order ID: ' . $order_id . PHP_EOL, FILE_APPEND);

// You can now process the order ID as needed
// For example, you can save it to a database, send an email, etc.

  global $ci_connection;
  
  
function getOrder($orderid) {
    global $client;
    $query = 'query {
  order(id: "'.$orderid.'") {        
        
        id
            name
      createdAt
      processedAt
       displayFulfillmentStatus
       fulfillments {  
    
            id
            displayStatus
         
      }
        displayFinancialStatus
        totalPriceSet {
            shopMoney {
              amount
            }
          }  
      tags
      note
      shippingAddress {
        country
      }
       shippingLine {
            source
            originalPriceSet {
              shopMoney
              {
                amount
              }
            }
          }
        discountCodes
      
      totalDiscountsSet {
        
        shopMoney {
          amount
        }
      }
      currencyCode
       subtotalPriceSet {
              shopMoney {
              amount
            }
          }
       totalTaxSet {
            shopMoney {
              amount
            }
          }
      discountApplications(first: 5) {
        edges {
          node {
        targetType
            value {
              
              ... on PricingPercentageValue {
                percentage
                
                
              }
              ... on MoneyV2 {
                amount
                currencyCode
              
              }
            }
          }
        }
      }
        risks {
                display
                level
                message
              }
    paymentGatewayNames
      customer {
      id
        firstName
        lastName
        email
        phone
      
         defaultAddress {
               address1
        address2
        city
        province
        country
        zip
        phone
            }
      }
        billingAddress {
        firstName
        lastName
        address1
        address2
        city
        province
        country
        zip
        phone
      }
             shippingAddress {
        firstName
        lastName
        address1
        address2
        city
        province
        country
        zip
        phone
      }
      lineItems(first: 50) {
        edges {
          node {
            
             sku
             id
            quantity
            totalDiscountSet {shopMoney {amount}}
                
            variant {
              title
              price
               sku
               id
                selectedOptions {
                    name
                    value
                  }
            }
          }
        }
      }
      
	}
}
';

 $order = $client->callGraphql($query);
    $rorders = $order['data']['order'];
    $fOrder= array('cursor'=>'','node'=>$rorders);
    return array($fOrder);
}


 $orders =  getOrder("gid://shopify/Order/".$order_id);
 
 
  if (count($orders) > 0) {
    $orderupdateshopify = 'mutation {';

    foreach ($orders as $order) {
        
       
     

        $cursor = $order['cursor'];
        $order = $order['node'];

     echo $order['name'] .' processing<br>';
$original_date =  $order['createdAt'];

// Create a DateTime object from the original date string
$datec = new DateTime($original_date);

// Convert the DateTime object to the desired format
$formatted_cdate = $datec->format('Y-m-d H:i:s');


$original_pdate =  $order['processedAt'];

// Create a DateTime object from the original date string
$datep = new DateTime($original_pdate);

// Convert the DateTime object to the desired format
$formatted_pdate = $datep->format('Y-m-d H:i:s');




      $discountcode = array();
      $totaldiscount = array();

      foreach ($order['discountCodes'] as $dc) {
        $discountcode[] = $dc;
      }

$disamount =  $order['totalDiscountsSet']['shopMoney']['amount'];
     
      $coupon = implode(",", $discountcode);

 echo $order['customer']['email'] .' processing<br>';
      if (check_customer_field('newSystemMemberID', $order['customer']['id'])) {
        updateCustomer($order['customer']);
      } else {
        createCustomer($order['customer']);
      }
    

      $paymentTitle = end($order['paymentGatewayNames']);

      $paymentInternalName = '';

      $paymentInternalName = getPaymentTitle($paymentTitle);
      $shippingMethods='';
      $totalShipping=0 ;
      if(isset($order['shippingLine'])) {
          
    
$shippingMethods = $order['shippingLine']['source'];
$totalShipping=$order['shippingLine']['originalPriceSet']['shopMoney']['amount'];
  }
  $note='';
//print_r($order);die;
    if(isset($order['note'])) {
 $note= addslashes($order['note']);
  
    }
  
      if (check_mag_order($order['id']) > 0) {



        echo $order['id'] . 'Already Exists<br>';

        /*exists start */

        $condiitonUpdate = array('newSystemOrderID' => $order['id'], 'newSystemCustomerID' => $order['customer']['id'], 'newSystemOrderNumber' => $order['name'], 'store'=>$store);







        $orderUpdateData = array(
'order_created' => date('Y-m-d H:i:s', strtotime($order['createdAt'])),          'newSystemCustomerEmail' => $order['customer']['email'],
'order_completed' => date('Y-m-d H:i:s', strtotime($order['processedAt'])),
          'shopify_recommendation'=>$order['risks'][0]['level'],
          'currency' => $order['currencyCode'],
          'order_total' =>$order['totalPriceSet']['shopMoney']['amount'],
          'order_subtotal' => $order['subtotalPriceSet']['shopMoney']['amount'],
          'total_items' => count($order['lineItems']['edges']),
          'shipping_methods' => addslashes($shippingMethods),
          'total_shipping' => $totalShipping,
          'payment_detail_title' => addslashes($paymentInternalName),
          'payment_detail_status' => $order['displayFinancialStatus'],
          'note' => $note,
   'taxAmount'=>$order['totalTaxSet']['shopMoney']['amount'],
          'coupon_code' => addslashes($coupon),
          'coupon_amount' => $disamount,
          'internalPaymentType' => $paymentInternalName,
          'fullfillment_status'=>$order['displayFulfillmentStatus'],
          'shipping_country'=>$order['shippingAddress']['country'],
           'store'=>$store,
        'pendingProcess'=>'0',
          // 'salesforceID'=>'emptynull'
         // 'shopifyCursor'=>$cursor


        );
        updateDatas(TB_ORDERS, $orderUpdateData, $condiitonUpdate, false);







         $olid =  $order['id'];


        if ($olid > 0) {

          foreach ($order['lineItems']['edges'] as $oprod) {
              $oprod = $oprod['node'];

        
              $discountproducttotalamount = $oprod['totalDiscountSet'];
  
            $finalcistockcode = $oprod['sku'];
            
            

            $pUpData = array('newSystemOrderID' => $order['id'], 'newSystemProductId' => $oprod['id'],'stockCode' => $finalcistockcode, 'actualCIStockCode' => $oprod['variant']['sku'], 'quantity' => $oprod['quantity'], 'unitPrice' => $oprod['variant']['price'], 'discountAmount' => $discountproducttotalamount['shopMoney']['amount']);


            $productCondition = array('newSystemOrderID' => $order['id'], 'newSystemProductId' => $oprod['id'], 'store'=>$store);
            $currentPData = getDatas(TB_ORDERS_PRODUCT, $productCondition,  '', 1, false);
            if (count($currentPData) >= 1) {
              updateDatas(TB_ORDERS_PRODUCT, $pUpData, $productCondition, false);
            }else {
                
           createDatas(TB_ORDERS_PRODUCT, $pUpData,false);

            }
          }



          if (isset($order['billingAddress']) && $order['billingAddress'] != '') {

            $c_address = $order['billingAddress'];
          }

          if (isset($order['shippingAddress']) && $order['shippingAddress'] != '') {

            $c_address = $order['shippingAddress'];
          }
      
          $deliveryUpData = array('newSystemOrderID' => $order['id'], 'newSystemMemberID' => $order['customer']['id'],'deliveryTradingName' => '', 
          'deliveryFirstName' => addslashes($c_address['firstName']), 'deliveryLastName' => addslashes($c_address['lastName']), 'deliveryPhone' => addslashes(remove_invisible_characters($c_address['phone'])), 'deliveryStreet' => addslashes($c_address['address1']), 'deliverySuburb' =>($c_address['address2']!='')?addslashes($c_address['address2']):'', 'deliveryPostCode' => ($c_address['zip']!='')?addslashes($c_address['zip']):'', 
          'deliveryCountry' => addslashes($c_address['country']), 
          'deliveryCity' => addslashes($c_address['city']), 
          'deliveryState' => addslashes($c_address['province']));
          $deliveryCondition = array('newSystemOrderID' => $order['id'], 'newSystemMemberID' => $order['customer']['id'], 'store'=>$store);
        
          $currentdeliveryData = getDatas(TB_ORDERS_DELIVERY, $deliveryCondition,  '', 1, false);
          if (count($currentdeliveryData) >= 1) {
            updateDatas(TB_ORDERS_DELIVERY, $deliveryUpData, $deliveryCondition, false);
          }else {
                          createDatas(TB_ORDERS_DELIVERY, $deliveryUpData, false);

          }
        }

        /*exists end */
      } else {

        echo "<pre>";

        echo $order['id'] . 'Exported<br>';

       

   $orderUpdateData = array(
       'newSystemOrderID'=> $order['id'],
       'newSystemOrderNumber'=>$order['name'],
       'newSystemCustomerID'=>$order['customer']['id'],
       'shopify_recommendation'=>$order['risks'][0]['level'],
          'order_created' => date('Y-m-d H:i:s', strtotime($order['createdAt'])),
          'newSystemCustomerEmail' => $order['customer']['email'],
          'order_completed' => date('Y-m-d H:i:s', strtotime($order['processedAt'])),
          'currency' => $order['currencyCode'],
          'order_total' =>$order['totalPriceSet']['shopMoney']['amount'],
          'order_subtotal' =>$order['subtotalPriceSet']['shopMoney']['amount'],
          'total_items' => count($order['lineItems']['edges']),
          'shipping_methods' =>addslashes( $shippingMethods),
          'total_shipping' => $totalShipping,
          'payment_detail_title' => $paymentInternalName,
          'payment_detail_status' => $order['displayFinancialStatus'],
          'note' => $note,
         'taxAmount'=>$order['totalTaxSet']['shopMoney']['amount'],
          'coupon_code' => addslashes($coupon),
          'coupon_amount' => $disamount,
          'internalPaymentType' => $paymentInternalName,
          'fullfillment_status'=>$order['displayFulfillmentStatus'],
          'shipping_country'=>$order['shippingAddress']['country'],
          //'shopifyCursor'=>$cursor,
          'store'=>$store,
        'pendingProcess'=>'0'

        );
        
       // echo '<br>New Cursor --'.$cursor;
       $olid= createDatas(TB_ORDERS, $orderUpdateData, false);


        //$olid = 1;


        if ($olid > 0) {
         //   print_r($order['lineItems']);die;
       
                 foreach ($order['lineItems']['edges'] as $oprod) {
              $oprod = $oprod['node'];

        
              $discountproducttotalamount = $oprod['totalDiscountSet'];
  
            $finalcistockcode = $oprod['sku'];
            
            

            $pUpData = array('newSystemOrderID' => $order['id'], 'newSystemProductId' => $oprod['id'],
            'stockCode' => $finalcistockcode, 'actualCIStockCode' => $oprod['variant']['sku'], 'quantity' => $oprod['quantity'], 'unitPrice' => $oprod['variant']['price'], 'discountAmount' => $discountproducttotalamount['shopMoney']['amount'],
        'store'=>$store);


            $productCondition = array('newSystemOrderID' => $order['id'], 'newSystemProductId' => $oprod['id']);
            $currentPData = getDatas(TB_ORDERS_PRODUCT, $productCondition,  '', 1, false);
            if (count($currentPData) >= 1) {
              updateDatas(TB_ORDERS_PRODUCT, $pUpData, $productCondition, false);
            }else {
                
           createDatas(TB_ORDERS_PRODUCT, $pUpData,false);

            }
          }

          $c_address = $order['shippingAddress'];
          if (isset($order['billingAddress']) && $order['billingAddress'] != '') {

            $c_address = $order['billingAddress'];
          }

          if ( isset($order['shippingAddress']) && $order['shippingAddress'] != '') {

            $c_address = $order['shippingAddress'];
          }
          
          $deliveryData= array(
              'newSystemMemberID'=> $order['customer']['id'],
              'newSystemOrderID'=> $order['id'] ,
              'deliveryFirstName'=>addslashes($c_address['firstName']),
              'deliveryLastName'=>addslashes($c_address['lastName']),
              'deliveryPhone'=>addslashes(remove_invisible_characters($c_address['phone'])),
              'deliveryStreet'=>addslashes($c_address['address1'].' '.$c_address['address2']),
       'deliverySuburb'=>$c_address['address2']==''?'':addslashes($c_address['address2']),
         'deliveryPostCode'=>$c_address['zip']==''?'':addslashes($c_address['zip']),
           'deliveryCountry'=>addslashes($c_address['country']),
               'deliveryCity'=>addslashes($c_address['city']),
               'deliveryState'=>addslashes($c_address['province']),
               'store'=>$store
              
              );
          
                   createDatas(TB_ORDERS_DELIVERY, $deliveryData, false);


        }
      }
    }

    $orderupdateshopify .= ' 

}';



    $newgsql = str_replace('{', '', $orderupdateshopify);
    $newgsql = str_replace('}', '', $newgsql);
    $newgsql = str_replace('mutation', '', $newgsql);
    if (trim($newgsql) != '') {



    //  $response = $client->callGraphql($orderupdateshopify);
    }
    //print_r($response);



  } 
  
  
// Respond with a 200 status code to acknowledge receipt of the webhook
http_response_code(200);
?>
