<?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 products';
$last_sync_date = get_last_sync_date($module_type);

//--------------------- Get Products Categories from WooCommerce ----------------------

    // fetch woocommerce categories
    $args = array(
        'number'     => $number,
        'orderby'    => $orderby,
        'order'      => $order,
        'hide_empty' => $hide_empty,
        'include'    => $ids
    );
    $product_categories = get_terms( 'product_cat', $args );

//--------------------- Insert Products Categories into Vtiger crm ----------------------
    
    foreach( $product_categories as $cat ) 
    {
        ob_start();
        $catName = $cat->name;

        // Fetch last "picklistvalue" from "vtiger_picklistvalues_seq" table
        $sql = "SELECT * FROM vtiger_picklistvalues_seq";
        $res = mysqli_query($db_connect,$sql);
        $row = mysqli_fetch_array($res);
        $last_picklistvalue = $row['id'];

        // Fetch last "productcategoryid" from "vtiger_productcategory_seq" table
        $sql = "SELECT * FROM vtiger_productcategory_seq";
        $res = mysqli_query($db_connect, $sql);
        $row = mysqli_fetch_array($res);
        $last_productcategory_seqid = $row['id'];

        // Fetch products categories from "vtiger_productcategory" table
        $sql = "SELECT * FROM vtiger_productcategory";
        $res = mysqli_query($db_connect, $sql);
        $total_rows = mysqli_num_rows($res);


        // Fetch last "sortorderid" from "vtiger_productcategory" table
        $last_sortorderid = $total_rows;

        $vtigerCatArray = array();
        while ($row = mysqli_fetch_array($res)) {
            // array of products categories
            array_push($vtigerCatArray, $row['productcategory']);   
        }

        // check current "category" out of array of "categories"
        $result = in_array($catName, $vtigerCatArray);

        // increment last values
        $new_picklistvalue = $last_picklistvalue + 1;
        $new_productcategory_seqid = $last_productcategory_seqid + 1;
        $new_sortorderid = $last_sortorderid + 1;

        if(empty($result))
        {
            // insert categories into vtiger crm
            $sql = "INSERT INTO vtiger_productcategory (productcategoryid, productcategory, picklist_valueid, sortorderid) VALUES ('".$new_productcategory_seqid."', '".$catName."', '".$new_picklistvalue."', '".$new_sortorderid."')";
            mysqli_query($db_connect, $sql);

            // insert picklist role for category into vtiger crm
            $sql = "INSERT INTO vtiger_role2picklist (roleid, picklistvalueid, picklistid, sortid) VALUES ('H2', '".$new_picklistvalue."', '18', '')";
            mysqli_query($db_connect, $sql);

            // update tables
            $sql = "UPDATE vtiger_picklistvalues_seq SET id='".$new_picklistvalue."' WHERE id='".$last_picklistvalue."' ";
            mysqli_query($db_connect, $sql);

            $sql = "UPDATE vtiger_productcategory_seq SET id='".$new_productcategory_seqid."' WHERE id='".$last_productcategory_seqid."' ";
            mysqli_query($db_connect, $sql);
        }
        echo ob_get_contents();
        ob_end_flush();
    }

//--------------------------- Get data from vTiger Products Module -----------------------

    //query to select data from the server.
    $query = "SELECT count(*) from Products;";

    //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);

    //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'];
    $retrievedObjects = $jsonResponse->result;

    $total_products = $retrievedObjects[0]->count;
    $recievedProducts = Array();

    for($i = 0; $i <= $total_products;)
    {
        ob_start();
        $query = "SELECT * FROM Products limit ".$i.", ".($i+100).";";

        $queryParam = urlencode($query);
        $params = "sessionName=$sessionId&operation=query&query=$queryParam";

        $curl->get("$endpointUrl?$params");
        $response = $curl->response;
        $jsonResponse = json_decode($response);

        //if($jsonResponse['success']==false)
            //die('query failed:'.$jsonResponse['errorMsg']);

        $retrievedObjects = array();
        $retrievedObjects = $jsonResponse->result;

        foreach ($retrievedObjects as $pro) {
            $recievedProducts[] = $pro;
        }

        $i += 100;
        echo ob_get_contents();
        ob_end_flush();
    }


    $count_products = count($recievedProducts);
    
    $retrievedObjectsArray = array();

    foreach ($recievedProducts as $recProd) 
    {
        array_push($retrievedObjectsArray, $recProd->product_no);
    }

//--------------------------- Get data from WooCommerce Products -----------------------

    $count_created_products = 0;
    $count_modified_products = 0;
    $count_deleted_products = 0;

    $product_posts = get_posts(array(
            'post_type'   => 'product',
            'post_status' => 'publish',
            'posts_per_page' => -1
            )
        );

    foreach($product_posts as $products)
    {
        ob_start();
        $productname = $products->post_title;
        $description = $products->post_content;
        $post_date = $products->post_date_gmt;
        $post_modified = $products->post_modified_gmt;
       
        $cat_terms = wp_get_post_terms( $products->ID, 'product_cat' );
        $prod_cat = $cat_terms[0]->name;

        // get post meta
        $product_meta = get_post_meta($products->ID);
        
        $product_no = $product_meta['product_no'][0];
        $id = $product_meta['product_crm_id'][0];
        $sale_price_dates_from = date('Y-m-d', $product_meta['_sale_price_dates_from'][0]);;
        $sale_price_dates_to = date('Y-m-d', $product_meta['_sale_price_dates_to'][0]);

        $sale_price = 0;
        if(!empty($product_meta['_sale_price'][0])) {
            $sale_price = $product_meta['_sale_price'][0];
        } else {
            $sale_price = $product_meta['_regular_price'][0];
        }

        $stock_qty = $product_meta['_stock'][0];
        $image_url = wp_get_attachment_url( get_post_thumbnail_id($products->ID) );
        if($image_url != ' '){
            $image_name = str_replace("/","",strrchr($image_url , "/"));
        }
        $data = get_vtiger_crm_data_info();
        $destination = $data['crm_root_path'];
        
        // check current "product_no" out of array of "product_no" values
        $result = in_array($product_no, $retrievedObjectsArray);

        if($result == false && $post_date > $last_sync_date)
        {
            //-------------------- Insert products into vtiger database ---------------------

            //fill in the details of the products.userId is obtained from loginResult.
            $productData  = array(  'productname'=>$productname, 
                                    'assigned_user_id'=>$userId, 
                                    'description'=>$description, 
                                    'discontinued'=>'1', 
                                    'sales_start_date'=>$sale_price_dates_from, 
                                    'sales_end_date'=>$sale_price_dates_to,
                                    'unit_price'=>$sale_price,
                                    'commissionrate'=>'',
                                    'productcategory' => $prod_cat,
                                    'qtyinstock' => $stock_qty,
                                    'imagename' => $image_name
                                );


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

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

            //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 product_no of new created objects
            $product_no = $savedObject['product_no'];
            $product_crm_id = $savedObject['id'];
            $v_id = explode('x',$product_crm_id);
            $v_product_id = $v_id[1];
            
            // update post meta of current post
            update_post_meta($products->ID, 'product_no', $product_no);
            update_post_meta($products->ID, 'product_crm_id', $product_crm_id);
           
            //---------------- images set ----------------
            if($image_name!=' '){
                
                $des_path = $destination."storage/2016/March/week4/";
                if(!file_exists($des_path))
                {
                    mkdir($des_path , 0777, true);
                }

                $date = current_time( 'mysql' );
                $crmid = mysqli_query($db_connect,"SELECT id FROM vtiger_crmentity_seq");
                $crmid = mysqli_fetch_array($crmid);
                $crmid = $crmid['id']+1;
                $update_crmid = "update vtiger_crmentity_seq set id = '$crmid'";
                mysqli_query($db_connect, $update_crmid);
                $insert_img_entity = "insert into vtiger_crmentity(crmid,smcreatorid,smownerid,modifiedby,setype,description,createdtime,modifiedtime,version,presence,deleted)values('$crmid','1','1','0','Products Image',' ', '$date','$date','0','1','0')";
                 mysqli_query($db_connect ,$insert_img_entity);
                 $insert_img = "insert into vtiger_attachments(attachmentsid,name,type,path,subject) values('$crmid','$image_name','image/jpeg','storage/2016/March/week4/','NULL')";
                mysqli_query($db_connect, $insert_img);

                $insert_rel_img = "insert into vtiger_seattachmentsrel(crmid,attachmentsid) values('$v_product_id','$crmid')";
                    mysqli_query($db_connect, $insert_rel_img);
               
                    if($image_name != " " && $image_name != NULL)
                    {
                        $data = file_get_contents($image_url);
                        $des_path_folder = $des_path.$crmid."_".$image_name;
                        $file = fopen($des_path_folder, "w+");
                        fputs($file, $data);
                        fclose($file);
                    }
            }

            // count total created products
            $count_created_products = $count_created_products + 1;
        }
        else if($post_modified > $last_sync_date)
        {
            //------------------ retrieve product 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 products --------------------------
           
            $retrievedObject['productname'] = $productname;
            $retrievedObject['description'] = $description;
            $retrievedObject['sales_start_date'] = $sale_price_dates_from;
            $retrievedObject['sales_end_date'] = $sale_price_dates_to;
            $retrievedObject['unit_price'] = $sale_price;
            $retrievedObject['productcategory'] = $prod_cat;
            $retrievedObject['qtyinstock'] = $stock_qty;

//            echo '<pre>'; print_r($retrievedObject); echo '</pre>'; echo __FILE__; die();
            //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 products
            $count_modified_products = $count_modified_products + 1;
        }
        echo ob_get_contents();
        ob_end_flush();
    }

    // Get deleted products data from database
    global $wpdb;
    $row = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."WVS_deleted_product_info" );    
    
    if(!empty($row))
    {
        foreach($row as $deleted_products)
        {
            ob_start();
            $product_crm_id = $deleted_products->product_crm_id;

        //---------------------- Delete products from vTiger --------------------------

            //delete a record created in above examples, sessionId a obtain from the login result.
            $params = array("sessionName"=>$sessionId, "operation"=>'delete', "id"=>$product_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)
            //die('delete failed:'.$jsonResponse['error']['errorMsg']);

            // count total deleted products
            $count_deleted_products = $count_deleted_products + 1;
            echo ob_get_contents();
            ob_end_flush();
        }

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

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


?>