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

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

    $count_contacts = count($recievedCustomers);

    $count_created_contacts = 0;
    $count_modified_contacts = 0;
    $count_deleted_contacts = 0;

    $retrievedContactNoArray = array();
    
    $args = array(
        'role' => 'customer',
        'orderby' => 'user_nicename',
        'order' => 'ASC'
    );
    $customers = get_users($args);
    $membersArray = 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];

        array_push($retrievedContactNoArray, $contact_no);

        echo ob_get_contents();
        ob_end_flush();
    }

    foreach ($recievedCustomers as $recCust) 
    {
        ob_start();

        // check current "contact_no" out of array of "product_no" values
        $result = in_array($recCust['contact_no'], $retrievedContactNoArray);
        
        $countryCode = myCodes($recCust['mailingcountry'], 'short');

        if( $recCust['createdtime'] > $last_sync_date && $result == false )
        {
            //------------------ Insert new users into woocommerce database ---------------

            //allows WP to display an error on failure
            $wp_show_error = true;
            
            // username should be lowercase letters
            $username = strtolower($recCust['firstname']);

            // check username is exist or not.
            if ( username_exists( $username ) )
	           $newUserName = $username.rand(1 , 999);
	        else
	           $newUserName = $username;

            //insert the new user and get the user id
            $userdata = array(
					    'user_login'  =>  $newUserName,
					    'user_nicename' => $recCust['firstname'],
					    'user_email'    =>  $recCust['email'],
					    'user_url'    =>  '',
					    'user_status'   =>  '0',
					    'role' => 'customer',
					    'user_registered'   =>  $recCust['createdtime'],
					    'user_pass'   =>  NULL
					);

			$user_id = wp_insert_user( $userdata ) ;

            //update the default product meta info

            update_user_meta( $user_id, 'first_name', $recCust['firstname']);
            update_user_meta( $user_id, 'last_name', $recCust['lastname']);
            update_user_meta( $user_id, 'description', $recCust['description']);
            add_user_meta( $user_id, 'session_tokens', '');
            add_user_meta( $user_id, '_woocommerce_persistent_cart', '');
            add_user_meta( $user_id, 'billing_first_name', $recCust['firstname']);
            add_user_meta( $user_id, 'billing_last_name', $recCust['lastname']);
            add_user_meta( $user_id, 'billing_company', '');
            add_user_meta( $user_id, 'billing_email', $recCust['email']);
            add_user_meta( $user_id, 'billing_phone', $recCust['mobile']);
            add_user_meta( $user_id, 'billing_country', $countryCode);
            add_user_meta( $user_id, 'billing_address_1', $recCust['mailingstreet']);
            add_user_meta( $user_id, 'billing_address_2', $recCust['otherstreet']);
            add_user_meta( $user_id, 'billing_city', $recCust['mailingcity']);
            add_user_meta( $user_id, 'billing_state', $recCust['mailingstate']);
            add_user_meta( $user_id, 'billing_postcode', $recCust['mailingzip']);
            add_user_meta( $user_id, 'contact_no', $recCust['contact_no']);
            add_user_meta( $user_id, 'contact_crm_id', $recCust['id']);

            // count total new created users
            $count_created_contacts = $count_created_contacts + 1;
        }
        else if( $recCust['modifiedtime'] > $last_sync_date )
        {
            //--------------- Update modified contacts into woocommerce database ---------------

            global $wpdb;
            $usermeta_row = $wpdb->get_results( "SELECT * FROM wp_usermeta WHERE meta_key = 'contact_no' AND meta_value='".$recCust['contact_no']."' " );
            foreach($usermeta_row as $usermeta) {
                $user_id = $usermeta->user_id;
            }

            $userdata = array(
                        'ID' => $user_id,
                        'user_email' => $recCust['email'],
                    );
            wp_update_user( $userdata );

            $u = new WP_User($user_id);
            $u->add_role( 'customer' );

            //update the default user meta info

            update_user_meta( $user_id, 'first_name', $recCust['firstname']);
            update_user_meta( $user_id, 'last_name', $recCust['lastname']);
            update_user_meta( $user_id, 'description', $recCust['description']);
            update_user_meta( $user_id, 'rich_editing', 'true');
            update_user_meta( $user_id, 'comment_shortcuts', 'false');
            update_user_meta( $user_id, 'admin_color', 'fresh');
            update_user_meta( $user_id, 'use_ssl', '0');
            update_user_meta( $user_id, 'show_admin_bar_front', 'true');
            update_user_meta( $user_id, 'wp_user_level', '');
            update_user_meta( $user_id, 'session_tokens', '');
            update_user_meta( $user_id, '_woocommerce_persistent_cart', '');
            update_user_meta( $user_id, 'billing_first_name', $recCust['firstname']);
            update_user_meta( $user_id, 'billing_last_name', $recCust['lastname']);
            update_user_meta( $user_id, 'billing_company', '');
            update_user_meta( $user_id, 'billing_email', $recCust['email']);
            update_user_meta( $user_id, 'billing_phone', $recCust['mobile']);
            update_user_meta( $user_id, 'billing_country', $countryCode);
            update_user_meta( $user_id, 'billing_address_1', $recCust['mailingstreet']);
            update_user_meta( $user_id, 'billing_address_2', $recCust['otherstreet']);
            update_user_meta( $user_id, 'billing_city', $recCust['mailingcity']);
            update_user_meta( $user_id, 'billing_state', $recCust['mailingstate']);
            update_user_meta( $user_id, 'billing_postcode', $recCust['mailingzip']);
            update_user_meta( $user_id, 'contact_no', $recCust['contact_no']);
            update_user_meta( $user_id, 'contact_crm_id', $recCust['id']);

            // count total modified contacts
            $count_modified_contacts = $count_modified_contacts + 1;
        }

        echo ob_get_contents();
        ob_end_flush();
    }


//-------------------------- Delete contacts in WooCommerce -----------------------------

    // Fetch deleted contacts from vtiger crm
    $sql1 = "SELECT * FROM vtiger_crmentity WHERE setype = 'Contacts' 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_contactdetails WHERE contactid = ".$row1['crmid'];
            $res2 = mysqli_query($db_connect, $sql2);
            $row2 = mysqli_fetch_array($res2);
            $contactNo = $row2['contact_no'];

            // get user info that have to delete
            global $wpdb;
            $meta = $wpdb->get_results("SELECT * FROM wp_usermeta WHERE meta_key='contact_no' AND meta_value='".$contactNo."' ");   
            foreach($meta as $usermeta)
            {
                // count deleted contacts
                $count_deleted_contacts = $count_deleted_contacts + 1;
                // product id of delete contact
                $userId = $usermeta->user_id;
                // delete user
                wp_delete_user($userId);
                // delete usermeta
                delete_user_meta($userId, '', '');
            }
        }
    }

    // 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 = 3 ");

?>