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

//------------------------ Get Products Categories from vTiger ------------------------

    //vtiger Object name which need be described or whose information is requested.
    $moduleName = 'Products';

    //use sessionId created at the time of login.
    $params = "sessionName=$sessionId&operation=describe&elementType=$moduleName";

    //describe request 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('describe object failed:'.$jsonResponse['error']['errorMsg']);

    //get describe result object.
    $description = array();
    $description = $jsonResponse['result'];

    $catArray = array();
    $catArray = $description['fields'][5]['type']['picklistValues'];
    $totalCat = count($catArray);


//------------------------ Insert Categories into WooCommerce ------------------------

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

        $cat_name = $description['fields'][5]['type']['picklistValues'][$i]['value'];
        $cat_slug = strtolower($cat_name);

        // array is returned if taxonomy is exist
        $term = term_exists( $cat_name, 'product_cat' );
        $term_id = $term['term_id'];

        if(empty($term)) {

            // if category not exist, a new category is inserted
            $insert_term = wp_insert_term( $cat_name, 'product_cat',
                                            array(
                                                'description' => '',
                                                'slug'        => $cat_slug,
                                                'parent'      => '',
                                            )
                                        );

            // get inserted term id and insert term meta
            $term = term_exists( $cat_name, 'product_cat' );
            add_woocommerce_term_meta($term['term_id'], 'display_type', '');
            add_woocommerce_term_meta($term['term_id'], 'thumbnail_id', '');
            add_woocommerce_term_meta($term['term_id'], 'product_count_product_cat', '');
        }
        else {

            // if category exist, category is updated
            wp_update_term( $term_id, 'product_cat',
                array(
                  'name' => $cat_name,
                  'slug' => $cat_slug,
                )
            );
        }

        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, 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'];

    $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, true);

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

//--------------------- Insert vtiger data into wooCommerce database -------------------

    $count_products = count($recievedProducts);

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

    $retrievedProductNoArray = array();

    $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;
        // get post meta
        $product_meta = get_post_meta($products->ID);             
        $product_no = $product_meta['product_no'][0];

        array_push($retrievedProductNoArray, $product_no);

        echo ob_get_contents();
        ob_end_flush();
    }

    foreach($recievedProducts as $recProd)
    {
        ob_start();

        // conversion according to required format in woocommerce
        $start_date = strtotime($recProd['sales_start_date']);
        $end_date = strtotime($recProd['sales_end_date']);
        $sales_price = round($recProd['unit_price']);
        $stock_qty = $recProd['qtyinstock'];
        $v_prod_id = $recProd['id'];
        $v_id = explode('x',$v_prod_id);
        $v_product_id = $v_id[1];
        //---------- get product image with url -------------
        $sql_img = "SELECT * FROM vtiger_seattachmentsrel WHERE crmid = '$v_product_id' ";
        $res_img = mysqli_query($db_connect, $sql_img);
        $row_img = mysqli_fetch_array($res_img);
        

        $attachment_id = $row_img['attachmentsid'];
        $sql_img1 = "SELECT * FROM vtiger_attachments WHERE attachmentsid = '$attachment_id' ";
        $res_img1 = mysqli_query($db_connect, $sql_img1);
        $row_img1 = mysqli_fetch_array($res_img1);
        $img_name =  $row_img1['name'];
        $img_path =  $row_img1['path'];
        $data = get_vtiger_crm_data_info();
        $source_folder = $data['crm_endpointurl'];
        $site_url  = str_replace("webservice.php","", $source_folder);
        $imageurl = $site_url.$img_path.$attachment_id."_".$img_name;

        $upload_dir = wp_upload_dir(); // Set upload folder
                
                if($imageurl != '')
                {
                $image_data = file_get_contents($imageurl); // Get image data
                }
                $filename   = basename($imageurl); // Create image file name
               
                // Check folder permission and define file location
                if( wp_mkdir_p( $upload_dir['path'] ) ) {
                    $file = $upload_dir['path'] . '/' . $filename;
                } else {
                    $file = $upload_dir['basedir'] . '/' . $filename;
                }
               
     
        if($stock_qty != 0 && $stock_qty == ''){
            $manage_stock = "yes";
        }else{
            $manage_stock = "no";
        }
        unset($prod_id);
        
        $product_category = $recProd['productcategory'];
        $term = get_term_by('name', $product_category, 'product_cat');
        $prod_term_id = $term->term_id;
        $prod_id[] = $prod_term_id;

        // check current "product_no" out of array of "product_no" values
        $result = in_array($recProd['product_no'], $retrievedProductNoArray);
 
        if( $recProd['createdtime'] > $last_sync_date && $result == false )
        {   
            //------------------ Insert new products into woocommerce database ---------------
            
            //allows WP to display an error on failure
            $wp_show_error = true;
            
            //insert the new product and get the product id
            $product_id = wp_insert_post(array(
            'post_title' => $recProd['productname'],
            'post_content' => $recProd['description'],
            'post_status' => 'publish',
            'post_type' => 'product',
            'post_author' => 1   //the id of the author
            ), $wp_show_error);

            wp_set_post_terms( $product_id, $prod_id, 'product_cat' );

            //update the default product meta info
            update_post_meta($product_id, 'product_crm_id', $recProd['id']);
            update_post_meta($product_id, 'product_no', $recProd['product_no']);
            update_post_meta($product_id, 'product_category', $product_category );
            update_post_meta($product_id, '_visibility', 'visible');
            update_post_meta($product_id, '_stock_status', 'instock');
            update_post_meta($product_id, 'total_sales', 0);
            update_post_meta($product_id, '_downloadable', 'no');
            update_post_meta($product_id, '_virtual', 'no');
            update_post_meta($product_id, '_regular_price', '');
            update_post_meta($product_id, '_sale_price', $sales_price);
            update_post_meta($product_id, '_purchase_note', '');
            update_post_meta($product_id, '_featured', 'no');
            update_post_meta($product_id, '_weight', '');
            update_post_meta($product_id, '_length', '');
            update_post_meta($product_id, '_width', '');
            update_post_meta($product_id, '_height', '');
            update_post_meta($product_id, '_sku', '');
            update_post_meta($product_id, '_product_attributes', array());
            update_post_meta($product_id, '_sale_price_dates_from', $start_date);
            update_post_meta($product_id, '_sale_price_dates_to', $end_date);
            update_post_meta($product_id, '_price', '');
            update_post_meta($product_id, '_sold_individually', '');
            update_post_meta($product_id, '_manage_stock', 'no');
            update_post_meta($product_id, '_backorders', $manage_stock);
            update_post_meta($product_id, '_stock', $stock_qty);
            update_post_meta($product_id, '_product_image_gallery', ''); //the comma separated attachment id's of the product images
                
                // Create the image  file on the server
                file_put_contents($file, $image_data);
               
                // Check image file type
                $wp_filetype = wp_check_filetype( $filename, null );
               
                // Set attachment data
                $attachment = array(
                    'post_mime_type' => $wp_filetype['type'],
                    'post_title'     => sanitize_file_name( $filename ),
                    'post_content'   => '',
                    'post_status'    => 'inherit'
                );
               
                // Create the attachment
                $attach_id = wp_insert_attachment( $attachment, $file, $product_id );
                add_post_meta($attach_id, '_wp_attachment_image_alt', $imagealttag);
                // Include image.php
                require_once(ABSPATH . 'wp-admin/includes/image.php');
               
                // Define attachment metadata
                $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
               
                // Assign metadata to attachment
                wp_update_attachment_metadata( $attach_id, $attach_data );
               
                // And finally assign featured image to post
                set_post_thumbnail($product_id, $attach_id ); 
        
                // count total new created products
                $count_created_products = $count_created_products + 1;
        }
        else if( $recProd['modifiedtime'] > $last_sync_date )
        {
            //--------------- Update modified products into woocommerce database ---------------
           
            global $wpdb;
            $postmeta_row = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."postmeta WHERE meta_key = 'product_no' AND meta_value='".$recProd['product_no']."' " );
            
            foreach($postmeta_row as $postmeta) 
            {
                $post_id = $postmeta->post_id;

                $meta_row = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."postmeta WHERE post_id = '".$post_id."' " );

                foreach($meta_row as $m_row) 
                {
                    switch ($m_row->meta_key) {
                        case '_regular_price':
                            $current_regular_price = $m_row->meta_value;
                            break;
                        case '_sale_price':
                            $current_sale_price = $m_row->meta_value;
                            break;
                        default:
                            # code...
                            break;
                    }
                }

            }

            $my_post = array(
                        'ID'           => $post_id,
                        'post_title'   => $recProd['productname'],
                        'post_content' => $recProd['description'],
                        'post_status' => 'publish',
                        'post_type' => 'product',
                        'post_author' => 1   //the id of the author
                    );

            wp_update_post( $my_post );
             

            //update the default product meta info
            wp_set_post_terms( $post_id, $prod_id, 'product_cat' );
            
            update_post_meta($post_id, 'product_crm_id', $recProd['id']);
            update_post_meta($post_id, 'product_no', $recProd['product_no']);
            update_post_meta($post_id, 'product_category', $recProd['productcategory']);
            update_post_meta($post_id, '_visibility', 'visible');
            update_post_meta($post_id, '_stock_status', 'instock');
            update_post_meta($post_id, 'total_sales', 0);
            update_post_meta($post_id, '_downloadable', 'no');
            update_post_meta($post_id, '_virtual', 'no');

            if($current_sale_price != '')
            {
                update_post_meta($post_id, '_sale_price', $sales_price);
            } else {
                update_post_meta($post_id, '_regular_price', $sales_price);
            }
            
            update_post_meta($post_id, '_purchase_note', '');
            update_post_meta($post_id, '_featured', 'no');
            update_post_meta($post_id, '_weight', '');
            update_post_meta($post_id, '_length', '');
            update_post_meta($post_id, '_width', '');
            update_post_meta($post_id, '_height', '');
            update_post_meta($post_id, '_sku', '');
            update_post_meta($post_id, '_product_attributes', array());
            update_post_meta($post_id, '_sale_price_dates_from', $start_date);
            update_post_meta($post_id, '_sale_price_dates_to', $end_date);
            update_post_meta($post_id, '_price', '');
            update_post_meta($post_id, '_sold_individually', '');
            update_post_meta($post_id, '_manage_stock', $manage_stock);
            update_post_meta($post_id, '_backorders', 'no');
            update_post_meta($post_id, '_stock', $stock_qty);
            update_post_meta($post_id, '_product_image_gallery', ''); //the comma separated attachment id's of the product images
            
                $upload_dir = wp_upload_dir(); // Set upload folder
                if($imageurl != '')
                {
                $image_data = file_get_contents($imageurl); // Get image data
                }
                $filename   = basename($imageurl); // Create image file name
               
                // Check folder permission and define file location
                if( wp_mkdir_p( $upload_dir['path'] ) ) {
                    $file = $upload_dir['path'] . '/' . $filename;
                } else {
                    $file = $upload_dir['basedir'] . '/' . $filename;
                }
                 
                // Create the image  file on the server
                file_put_contents($file, $image_data);
               
                // Check image file type
                $wp_filetype = wp_check_filetype( $filename, null );
               
                // Set attachment data
                $attachment = array(
                    'post_mime_type' => $wp_filetype['type'],
                    'post_title'     => sanitize_file_name( $filename ),
                    'post_content'   => '',
                    'post_status'    => 'inherit'
                );
               
                // Create the attachment
                $attach_id = wp_insert_attachment( $attachment, $file, $post_id );
                add_post_meta($attach_id, '_wp_attachment_image_alt', $imagealttag);
                
                // Include image.php
                require_once(ABSPATH . 'wp-admin/includes/image.php');
               
                // Define attachment metadata
                $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
               
                // Assign metadata to attachment
                wp_update_attachment_metadata( $attach_id, $attach_data );
               
                // And finally assign featured image to post
                set_post_thumbnail( $post_id, $attach_id ); 
        
            // count total modified products
            $count_modified_products = $count_modified_products + 1;
        }
        
        echo ob_get_contents();
        ob_end_flush();
    }


//-------------------------- Delete products in WooCommerce -----------------------------

    // Fetch deleted products from vtiger crm
    $sql1 = "SELECT * FROM vtiger_crmentity WHERE setype = 'Products' AND deleted = '1' ";
    $res1 = mysqli_query($db_connect, $sql1);
    while($row1 = mysqli_fetch_array($res1))
    {
        if ($row1['modifiedtime'] > $last_sync_date)
        {
            $sql2 = "SELECT * FROM vtiger_products WHERE productid = ".$row1['crmid'];
            $res2 = mysqli_query($db_connect, $sql2);
            $row2 = mysqli_fetch_array($res2);
            $productNo = $row2['product_no'];

            // get post info that have to delete
            global $wpdb;
            $meta = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."postmeta WHERE meta_key='product_no' AND meta_value='".$productNo."' ");   
            foreach($meta as $postmeta)
            {
                // count deleted products
                $count_deleted_products = $count_deleted_products + 1;
                // product id of delete product
                $postId = $postmeta->post_id;
                // delete post
                wp_delete_post($postId);
                // delete postmeta
                delete_post_meta($postId, '', '');
            }
        }
    }
        
    // Update last synchronization date
    global $wpdb;
    $date = date("Y-m-d H:i:s");
	//$date = current_time( 'mysql' );
    $wpdb->query("UPDATE ".$wpdb->prefix."WVS_sync_date_info SET last_sync_date = '".$date."' WHERE id = 1 ");

?>