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

//-------------------------- Get data from vTiger Contacts Module --------------------

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

    //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_customers = $retrievedObjects[0]['count'];
    $recievedCustomers = array();

    for($i = 0; $i <= $total_customers;)
    {
        ob_start();
        $query = "SELECT * from Contacts 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 $cust) {
            $recievedCustomers[] = $cust;
        }

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


    $count_contacts = count($recievedCustomers);
    $retrievedObjectsArray = array();

    foreach($recievedCustomers as $recCust)
    {   
        // array of "contact_no" values       
        array_push($retrievedObjectsArray, $recCust['contact_no']);
    }


//--------------------------- Get data from WooCommerce Users -----------------------

    $count_created_contacts = 0;
    $count_modified_contacts = 0;
    $count_deleted_contacts = 0;
    
    $args = array(
    'role' => 'customer',
    'orderby' => 'user_nicename',
    'order' => 'ASC'
    );
    $customers = get_users($args);
    //$customers = get_users( 'role=customer' );
  
    foreach ($customers as $users) 
    {
        ob_start();
        $userId         =   $users->ID;
        $userName       =   $users->user_login;
        $userEmail      =   $users->user_email;
        $userRegistered =   $users->user_registered;

        // get user meta
        $user_meta = get_user_meta($userId);

        $contact_no = $user_meta['contact_no'][0];
        $id = $user_meta['contact_crm_id'][0];
        $nickname = $user_meta['nickname'][0];
        $first_name = $user_meta['first_name'][0];
        $last_name = $user_meta['last_name'][0];
        $description = $user_meta['description'][0];
        
        $billing_phone = $user_meta['billing_phone'][0];
        $billing_company = $user_meta['billing_company'][0];
        $billing_country = myCodes($user_meta['billing_country'][0], 'long');
        $billing_address_1 = $user_meta['billing_address_1'][0];
        $billing_address_2 = $user_meta['billing_address_2'][0];
        // final address
        $billing_address = $billing_address_1." , ".$billing_address_2;
        $billing_city = $user_meta['billing_city'][0];
        $billing_state = $user_meta['billing_state'][0];
        $billing_postcode = $user_meta['billing_postcode'][0];

        $shipping_phone = $user_meta['shipping_phone'][0];
        $shipping_company = $user_meta['shipping_company'][0];
        $shipping_country = myCodes($user_meta['shipping_country'][0], 'long');
        $shipping_address_1 = $user_meta['shipping_address_1'][0];
        $shipping_address_2 = $user_meta['shipping_address_2'][0];
        // final address
        $shipping_address = $billing_address_1." , ".$billing_address_2;
        $shipping_city = $user_meta['shipping_city'][0];
        $shipping_state = $user_meta['shipping_state'][0];
        $shipping_postcode = $user_meta['shipping_postcode'][0];

        // check current "contact_no" out of array of "contact_no" values
        $result = in_array($contact_no, $retrievedObjectsArray);
       
        if($result == false && $userRegistered > $last_sync_date)
        {
            //-------------------- Insert contacts into vtiger database ---------------------

            //fill in the details of the products.userId is obtained from loginResult.
            $productData  = array( 'firstname'=>$first_name, 
                                   'lastname'=>$nickname, 
                                   'assigned_user_id'=>$userId, 
                                   'email'=>$userEmail,
                                   'phone'=>$billing_phone,
                                   'description'=>$description,
                                   'mailingstreet'=>$billing_address,
                                   'mailingcity'=>$billing_city,
                                   'mailingstate'=>$billing_state,
                                   'mailingcountry'=>$billing_country,
                                   'mailingzip'=>$billing_postcode
                                );
            
            //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 = 'Contacts';

            //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 contact_no of new created objects
            $contact_no = $savedObject['contact_no'];
            $contact_crm_id = $savedObject['id'];

            // update post meta of current post
            add_user_meta($userId, 'contact_no', $contact_no);
            add_user_meta($userId, 'contact_crm_id', $contact_crm_id);

            // count total created contacts
            $count_created_contacts = $count_created_contacts + 1;
        }
        else if($result == true)
        {
            //------------------ retrieve contact 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['firstname'] = $first_name;
            $retrievedObject['lastname'] = $last_name;
            $retrievedObject['phone'] = $billing_phone;
            $retrievedObject['description'] = $description;
            $retrievedObject['email'] = $userEmail;

            $retrievedObject['mailingstreet'] = $billing_address;
            $retrievedObject['mailingcity'] = $billing_city;
            $retrievedObject['mailingstate'] = $billing_state;
            $retrievedObject['mailingcountry'] = $billing_country;
            $retrievedObject['mailingzip'] = $billing_postcode;
            
            //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_contacts = $count_modified_contacts + 1;
        }
        echo ob_get_contents();
        ob_end_flush();
    }


    // Get deleted contacts data from database
    global $wpdb;
    $row = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."WVS_deleted_contact_info" );    
    
    if(!empty($row))
    {
        foreach($row as $deleted_contacts)
        {
            ob_start(); 
            $contact_crm_id = $deleted_contacts->contact_crm_id;

        //---------------------- Delete contacts from vTiger --------------------------

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

            // count total deleted contacts
            $count_deleted_contacts = $count_deleted_contacts + 1;
            echo ob_get_contents();
            ob_end_flush();
        }

        // after deletion of contacts, table become empty
        global $wpdb;
        $table_name = $wpdb->prefix."WVS_deleted_contact_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 = 4 ");

?>