<?php

// include woo-vtiger login access file
include_once(WOO_VTIGER_INCLUDES_DIR . 'woo-vtiger-login-access.php');

// Get last synchronize date from database
$module_type = 'export orders';
$last_sync_date = get_last_sync_date($module_type);


$count_created_orders = 0;
$count_modified_orders = 0;
$count_deleted_orders = 0;

//--------------------------- Get data from vTiger SalesOrder Module -----------------------

    //query to select data from the server.
    $query = "SELECT * from SalesOrder;";

    //urlencode to as its sent over http.
    $queryParam = urlencode($query);

    //sessionId is obtained from login result.
    $params = "sessionName=$sessionId&operation=query&query=$queryParam";

    //query must be GET Request.
    $curl->get("$endpointUrl?$params");
    $response = $curl->response;

    //decode the json encode response from the server.
    $jsonResponse = json_decode($response, true);

    //operation was successful get the token from the reponse.
    //if($jsonResponse['success']==false)
        //handle the failure case.
        //die('query failed:'.$jsonResponse['errorMsg']);

    //Array of vtigerObjects
    $retrievedObjects = array();
    $retrievedObjects = $jsonResponse['result'];

    $count_orders = count($retrievedObjects);
    $retrievedObjectsArray = array();

    for($i=0; $i<$count_orders; $i++)
    {
        ob_start();

        // array of "salesorder_no" values       
        array_push($retrievedObjectsArray, $retrievedObjects[$i]['salesorder_no']);

        echo ob_get_contents();
        ob_end_flush();
    }

//------------------------- Get data from woocommerce Orders ---------------------------

	$args = array(
	  'post_type' => 'shop_order',
	  'post_status' => array('wc-pending','wc-processing','wc-on-hold','wc-completed','wc-cancelled','wc-refunded','wc-failed'),
	  'meta_key' => '_customer_user',
	  'posts_per_page' => '-1'
	);

	$my_query = new WP_Query($args);

	// get sales orders by posttype "shop_order"
	$customer_orders = $my_query->posts;

	// Array Match status order
    $arrMatchStatus = array(
        'pending' => 'Pending payment',
        'processing' => 'Processing',
        'on-hold' => 'On hold',
        'completed' => 'Approved',
        'cancelled' => 'Cancelled',
        'refunded' => 'Refunded',
        'failed' => 'Failed'
    );

	foreach ($customer_orders as $customer_order) 
	{
        ob_start();

		$order = new WC_Order();
		$order->populate($customer_order);
//        WooCommerce since 3.0.0.
        $orderdata = $order->get_data();
        

		// get order data from "wp_post" table

//        WooCommerce since 3.0.0.
        $order_id = $orderdata['id'];
        $order_status = (isset($arrMatchStatus[$orderdata['status']])) ? $arrMatchStatus[$orderdata['status']] : 'Created';
        $order_created = $order->order_date;
        $order_modified = $order->modified_date;

		// get order meta data from "wp_postmeta" table
		$order_meta = get_post_meta($order_id);

		$salesorder_no = $order_meta['salesorder_no'][0];
        $id = $order_meta['salesorder_crm_id'][0];
        $cart_discount = $order_meta['_cart_discount'][0];

        $cart_discount_tax = $order_meta['_cart_discount_tax'][0];
        $order_total = $order_meta['_order_total'][0];
        $order_tax = $order_meta['_order_tax'][0];
        $order_shipping_tax = $order_meta['_order_shipping_tax'][0];
        $order_shipping = $order_meta['_order_shipping'][0];
        $order_currency = $order_meta['_order_currency'][0];
        $order_key = $order_meta['_order_key'][0];
        $customer_user_id = $order_meta['_customer_user'][0];
        
        $billing_first_name = $order_meta['_billing_first_name'][0];
        $billing_last_name = $order_meta['_billing_last_name'][0];
        $billing_address_1 = $order_meta['_billing_address_1'][0];
        $billing_address_2 = $order_meta['_billing_address_2'][0];
        $billing_address = $billing_address_1 . " , " . $billing_address_2;
        $billing_city = $order_meta['_billing_city'][0];
        $billing_postcode = $order_meta['_billing_postcode'][0];
        $billing_country = $order_meta['_billing_country'][0];
        $billing_state = $order_meta['_billing_state'][0];
        $billing_email = $order_meta['_billing_email'][0];
        $billing_phone = $order_meta['_billing_phone'][0];

        $shipping_first_name = $order_meta['_shipping_first_name'][0];
        $shipping_last_name = $order_meta['_shipping_last_name'][0];
        $shipping_address_1 = $order_meta['_shipping_address_1'][0];
        $shipping_address_2 = $order_meta['_shipping_address_2'][0];
        $shipping_address = $shipping_address_1." , ".$shipping_address_2;
        $shipping_city = $order_meta['_shipping_city'][0];
        $shipping_postcode = $order_meta['_shipping_postcode'][0];
        $shipping_country = $order_meta['_shipping_country'][0];
        $shipping_state = $order_meta['_shipping_state'][0];
        $transaction_id = $order_meta['_transaction_id'][0];

        // get order user meta data
        $user_meta = get_user_meta($customer_user_id);
        $contact_no = $user_meta['contact_no'][0];
        $contact_id = $user_meta['contact_crm_id'][0];

        if($cart_discount != '' && $cart_discount !='0'){
            $cart_dis_pre = ($cart_discount *100)/$order_total;
        }else{
            $cart_dis_pre = 0; 
        }
       
		//get sales order item data
		$items = $order->get_items();

        $items_array = array();
        $so_item = array();
        $product_id_array = array();

        $so_item['sequence_no'] = 0;

		foreach ( $items as $item )
		{
            // get product item meta
//          WooCommerce since 3.0.0.
            $item_meta = get_post_meta($item->get_product_id());
            $product_no = $item_meta['product_no'][0];

//          WooCommerce since 3.0.0.
            $so_item['productid']   = $item_meta['product_crm_id'][0];
            $so_item['quantity']    = $item->get_quantity();
            $so_item['sequence_no'] = $so_item['sequence_no'] + 1;
            $so_item['listprice'] = $item->get_total() / $item->get_quantity();

            array_push($items_array, $so_item);
	    }

		// check current "salesorder_no" out of array of "salesorder_no" values
        $result = in_array($salesorder_no, $retrievedObjectsArray);

        if($result == false && $order_created > $last_sync_date) {
            //------------------ Insert salesorder into vtiger database -------------------
            $salesOrderData  = array("subject"=>"Order : ".$order_id,
									"sostatus"=>$order_status,
									"contact_id"=>$contact_id,
									"customerno"=>"",
									"account_id"=>"11x82",
									"bill_street"=>$billing_address,
									"bill_city"=>$billing_city,
									"bill_state"=>$billing_state,
									"bill_code"=>$billing_postcode,
									"bill_country"=>$billing_country,
									"ship_street"=>$shipping_address,
									"ship_city"=>$shipping_city,
									"ship_state"=>$shipping_state,
									"ship_code"=>$shipping_postcode,
									"ship_country"=>$shipping_country,
									"invoicestatus"=>"Created",
									"productid"=>$so_item['productid'],
									"LineItems"=>$items_array,
									"comment"=>"",
									"tax1"=>"",
									"tax2"=>"",
									"tax3"=>"",
									"pre_tax_total"=>"",
									"currency_id"=>"21x1",
									"conversion_rate"=>"",
									"tax4"=>"",
									"start_period"=>"",
									"end_period"=>"",
									"createdtime"=>"",
									"modifiedtime"=>"",
									"duedate"=>"",
									"carrier"=>"",
									"pending"=>"",
									"txtAdjustment"=>"",
									"salescommission"=>"",
									"exciseduty"=>"0.000",
									"hdnGrandTotal"=>$order_total,
									"hdnSubTotal"=>"",
									"hdnTaxType"=>"individual",
									"hdnDiscountAmount"=>"",
									"hdnDiscountPercent"=>$cart_dis_pre,
									"hdnS_H_Percent"=>"0",
									"hdnS_H_Amount"=>$order_shipping,
									"discount_percent"=>"",
									"discount_amount"=>"",
									"terms_conditions"=>"- Unless ",
									"enable_recurring"=>"0",
									"recurring_frequency"=>"0",
									"payment_duration"=>"",
									"assigned_user_id"=>$userId
								);
            
            //encode the object in JSON format to communicate with the server.
            $objectJson = json_encode($salesOrderData);

            //name of the module for which the entry has to be created.
            $moduleName = 'SalesOrder';

            //sessionId is obtained from loginResult.
            $params = array("sessionName"=>$sessionId, "operation"=>'create', 
                "element"=>$objectJson, "elementType"=>$moduleName);
             
            //Create must be POST Request.
            $curl->post("$endpointUrl", $params);
            $response = $curl->response;

            //decode the json encode response from the server.
            $jsonResponse = json_decode($response, true);

            //operation was successful get the token from the reponse.
            //if($jsonResponse['success']==false)
                //handle the failure case.
                //die('create failed:'.$jsonResponse['error']['errorMsg']);
            
            $savedObject = array();
            $savedObject = $jsonResponse['result'];

            // get salesorder_no and salesorder_crm_id of new created order
            $salesorder_no = $savedObject['salesorder_no'];
            $salesorder_crm_id = $savedObject['id'];

            // update post meta of current post
            update_post_meta($order_id, 'salesorder_no', $salesorder_no);
            update_post_meta($order_id, 'salesorder_crm_id', $salesorder_crm_id);

            // count total created products
            $count_created_orders = $count_created_orders + 1;
        }
        else if($order_modified > $last_sync_date) {

            //------------------ retrieve orders that have to modify ---------------------

            //sessionId is obtained from loginResult.
            $params = "sessionName=$sessionId&operation=retrieve&id=$id";

            //Retrieve must be GET Request.
            $curl->get("$endpointUrl?$params");
            $response = $curl->response;
            
            //decode the json encode response from the server.
            $jsonResponse = json_decode($response, true);

            //operation was successful get the token from the reponse.

            //if($jsonResponse['success']==false)
                //handle the failure case.
                //die('retrieve failed:'.$jsonResponse['error']['errorMsg']);

            $retrievedObject = array();
            $retrievedObject = $jsonResponse['result'];

            //---------------------- Update retrived orders --------------------------


            $retrievedObject['sostatus'] = $order_status;
            $retrievedObject['hdnGrandTotal'] = $order_total;
            $retrievedObject['invoicestatus'] = 'Created';
            $retrievedObject['productid'] = $so_item['productid'];

            $retrievedObject['bill_street'] = $billing_address;
            $retrievedObject['bill_city'] = $billing_city;
            $retrievedObject['bill_state'] = $billing_state;
            $retrievedObject['bill_code'] = $billing_code;
            $retrievedObject['bill_country'] = $billing_country;

            $retrievedObject['ship_street'] = $shipping_address;
            $retrievedObject['ship_city'] = $shipping_city;
            $retrievedObject['ship_state'] = $shipping_state;
            $retrievedObject['ship_code'] = $shipping_code;
            $retrievedObject['ship_country'] = $shipping_country;

            $retrievedObject['hdnDiscountPercent'] = $cart_dis_pre;
            $retrievedObject['hdnS_H_Amount'] = $order_shipping;

            $retrievedObject['LineItems'] = $items_array;

            $retrievedObject['potential_id'] = '13x1';
            $retrievedObject['contact_id'] = '12x1';
            $retrievedObject['quote_id'] = '4x1';

            //encode the object in JSON format to communicate with the server.
            $objectJson = json_encode($retrievedObject);

            //sessionId is obtained from the login operation result.
            $params = array("sessionName" => $sessionId, "operation" => 'update',
                "element" => $objectJson);
            
            //update must be a POST request.
            $curl->post("$endpointUrl", $params);
            $response = $curl->response;
            
            //decode the json encode response from the server.
            $jsonResponse = json_decode($response, true);

            //operation was successful get the token from the reponse.
            //if($jsonResponse['success']==false)
                //handle the failure case.
                //die('update failed:'.$jsonResponse['error']['errorMsg']);

            //update result object.
            $updatedObject = array();
            $updatedObject = $jsonResponse['result'];

            // count total modified orders
            $count_modified_orders = $count_modified_orders + 1;
        }
        echo ob_get_contents();
        ob_end_flush();
	}


//---------------------- Delete orders from vTiger --------------------------

    // Get deleted orders data from database
    global $wpdb;
    $row = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."WVS_deleted_order_info" );    
    
    if(!empty($row)) {

        foreach($row as $deleted_orders)
        {
            ob_start();
            $salesorder_crm_id = $deleted_orders->salesorder_crm_id;

            //delete a record created in above examples, sessionId a obtain from the login result.
            $params = array("sessionName"=>$sessionId, "operation"=>'delete', "id"=>$salesorder_crm_id);
            
            //delete operation request must be POST request.
            $curl->post("$endpointUrl", $params);
            $response = $curl->response;
            
            //decode the json encode response from the server.
            $jsonResponse = json_decode($response, true);

            //operation was successful get the token from the reponse.
            //if($jsonResponse['success']==false)
                //handle the failure case.
                //die('delete failed:'.$jsonResponse['error']['errorMsg']);

            // count total deleted orders
            $count_deleted_orders = $count_deleted_orders + 1;
            echo ob_get_contents();
            ob_end_flush();
        }

        // after deletion of orders, table become empty
        global $wpdb;
        $table_name = $wpdb->prefix."WVS_deleted_order_info";
        $delete = $wpdb->query("TRUNCATE TABLE ".$table_name);
    }

    // Update last synchronization date 
    $date = current_time( 'mysql' );
    //$date = date("Y-m-d H:i:s");
    global $wpdb;
    $wpdb->query("UPDATE ".$wpdb->prefix."WVS_sync_date_info SET last_sync_date = '".$date."' WHERE id = 6 ");
?>