<?php
error_reporting(0);
function myCodes($in, $type)
{
    $out = "";
    $long = array('Afghanistan' , 'Åland Island' , 'Albania' , 'Algeria' , 'American Samoa' , 'Andorra' , 'Angola' , 'Anguilla' , 'Antarctica' , 'Antigua and Barbuda' , 'Argentina' , 'Armenia' , 'Aruba' , 'Australia' , 'Austria' , 'Azerbaijan' , 'Bahamas' , 'Bahrain' , 'Bangladesh' , 'Barbados' , 'Belarus' , 'Belgium' , 'Belize' , 'Benin' , 'Bermuda' , 'Bhutan' , 'Bolivia – Plurinational State of' , 'Bonaire – Sint Eustatius and Saba' , 'Bosnia and Herzegovina' , 'Botswana' , 'Bouvet Island' , 'Brazil' , 'British Indian Ocean Territory' , 'Brunei Darussalam' , 'Bulgaria' , 'Burkina Faso' , 'Burundi' , 'Cambodia' , 'Cameroon' , 'Canada' , 'Cape Verde' , 'Cayman Islands' , 'Central African Republic' , 'Chad' , 'Chile' , 'China' , 'Christmas Island' , 'Cocos (Keeling) Islands' , 'Colombia' , 'Comoros' , 'Congo' , 'Congo – the Democratic Republic of the' , 'Cook Islands' , 'Costa Rica' , 'Côte d Ivoire' , 'Croatia' , 'Cuba' , 'Curaçao' , 'Cyprus' , 'Czech Republic' , 'Denmark' , 'Djibouti' , 'Dominica' , 'Dominican Republic' , 'Ecuador' , 'Egypt' , 'El Salvador' , 'Equatorial Guinea' , 'Eritrea' , 'Estonia' , 'Ethiopia' , 'Falkland Islands (Malvinas)' , 'Faroe Islands' , 'Fiji' , 'Finland' , 'France' , 'French Guiana' , 'French Polynesia' , 'French Southern Territories' , 'Gabon' , 'Gambia' , 'Georgia' , 'Germany' , 'Ghana' , 'Gibraltar' , 'Greece' , 'Greenland' , 'Grenada' , 'Guadeloupe' , 'Guam' , 'Guatemala' , 'Guernsey' , 'Guinea' , 'Guinea-Bissau' , 'Guyana' , 'Haiti' , 'Heard Island and McDonald Islands' , 'Holy See (Vatican City State)' , 'Honduras' , 'Hong Kong' , 'Hungary' , 'Iceland' , 'India' , 'Indonesia' , 'Iran – Islamic Republic of' , 'Iraq' , 'Ireland' , 'Isle of Man' , 'Israel' , 'Italy' , 'Jamaica' , 'Japan' , 'Jersey' , 'Jordan' , 'Kazakhstan' , 'Kenya' , 'Kiribati' , "Korea – Democratic People's Republic of" , 'Korea – Republic of' , 'Kuwait' , 'Kyrgyzstan' , "Lao People's Democratic Republic" , 'Latvia' , 'Lebanon' , 'Lesotho' , 'Liberia' , 'Libya' , 'Liechtenstein' , 'Lithuania' , 'Luxembourg' , 'Macao' , 'Macedonia – the former Yugoslav Republic of' , 'Madagascar' , 'Malawi' , 'Malaysia' , 'Maldives' , 'Mali' , 'Malta' , 'Marshall Islands' , 'Martinique' , 'Mauritania' , 'Mauritius' , 'Mayotte' , 'Mexico' , 'Micronesia – Federated States of' , 'Moldova – Republic of' , 'Monaco' , 'Mongolia' , 'Montenegro' , 'Montserrat' , 'Morocco' , 'Mozambique' , 'Myanmar' , 'Namibia' , 'Nauru' , 'Nepal' , 'Netherlands' , 'New Caledonia' , 'New Zealand' , 'Nicaragua' , 'Niger' , 'Nigeria' , 'Niue' , 'Norfolk Island' , 'Northern Mariana Islands' , 'Norway' , 'Oman' , 'Pakistan' , 'Palau' , 'Palestinian Territory – Occupied' , 'Panama' , 'Papua New Guinea' , 'Paraguay' , 'Peru' , 'Philippines' , 'Pitcairn' , 'Poland' , 'Portugal' , 'Puerto Rico' , 'Qatar' , 'Réunion' , 'Romania' , 'Russian Federation' , 'Rwanda' , 'Saint Barthélemy' , 'Saint Helena – Ascension and Tristan da Cunha' , 'Saint Kitts and Nevis' , 'Saint Lucia' , 'Saint Martin (French part)' , 'Saint Pierre and Miquelon' , 'Saint Vincent and the Grenadines' , 'Samoa' , 'San Marino' , 'Sao Tome and Principe' , 'Saudi Arabia' , 'Senegal' , 'Serbia' , 'Seychelles' , 'Sierra Leone' , 'Singapore' , 'Sint Maarten (Dutch part)' , 'Slovakia' , 'Slovenia' , 'Solomon Islands' , 'Somalia' , 'South Africa' , 'South Georgia and the South Sandwich Islands' , 'South Sudan' , 'Spain' , 'Sri Lanka' , 'Sudan' , 'Suriname' , 'Svalbard and Jan Mayen' , 'Swaziland' , 'Sweden' , 'Switzerland' , 'Syrian Arab Republic' , 'Taiwan – Province of China' , 'Tajikistan' , 'Tanzania – United Republic of' , 'Thailand' , 'Timor-Leste' , 'Togo' , 'Tokelau' , 'Tonga' , 'Trinidad and Tobago' , 'Tunisia' , 'Turkey' , 'Turkmenistan' , 'Turks and Caicos Islands' , 'Tuvalu' , 'Uganda' , 'Ukraine' , 'United Arab Emirates' , 'United Kingdom' , 'United States' , 'United States Minor Outlying Islands' , 'Uruguay' , 'Uzbekistan' , 'Vanuatu' , 'Venezuela – Bolivarian Republic of' , 'Viet Nam' , 'Virgin Islands – British' , 'Virgin Islands – U.S.' , 'Wallis and Futuna' , 'Western Sahara' , 'Yemen' , 'Zambia' , 'Zimbabwe');
    $short = array('AF','AX','AL','DZ','AS','AD','AO','AI','AQ','AG','AR','AM','AW','AU','AT','AZ','BS','BH','BD','BB','BY','BE','BZ','BJ','BM','BT','BO','BQ','BA','BW','BV','BR','IO','BN','BG','BF','BI','KH','CM','CA','CV','KY','CF','TD','CL','CN','CX','CC','CO','KM','CG','CD','CK','CR','CI','HR','CU','CW','CY','CZ','DK','DJ','DM','DO','EC','EG','SV','GQ','ER','EE','ET','FK','FO','FJ','FI','FR','GF','PF','TF','GA','GM','GE','DE','GH','GI','GR','GL','GD','GP','GU','GT','GG','GN','GW','GY','HT','HM','VA','HN','HK','HU','IS','IN','ID','IR','IQ','IE','IM','IL','IT','JM','JP','JE','JO','KZ','KE','KI','KP','KR','KW','KG','LA','LV','LB','LS','LR','LY','LI','LT','LU','MO','MK','MG','MW','MY','MV','ML','MT','MH','MQ','MR','MU','YT','MX','FM','MD','MC','MN','ME','MS','MA','MZ','MM','NA','NR','NP','NL','NC','NZ','NI','NE','NG','NU','NF','MP','NO','OM','PK','PW','PS','PA','PG','PY','PE','PH','PN','PL','PT','PR','QA','RE','RO','RU','RW','BL','SH','KN','LC','MF','PM','VC','WS','SM','ST','SA','SN','RS','SC','SL','SG','SX','SK','SI','SB','SO','ZA','GS','SS','ES','LK','SD','SR','SJ','SZ','SE','CH','SY','TW','TJ','TZ','TH','TL','TG','TK','TO','TT','TN','TR','TM','TC','TV','UG','UA','AE','GB','US','UM','UY','UZ','VU','VE','VN','VG','VI','WF','EH','YE','ZM','ZW');
    //$in = strtolower(trim($in));
    switch($type){
        case 'long':$out = str_replace($short, $long, $in);break;
        case 'short':$out = str_replace($long, $short, $in);break;
    }
    return $out;
}


/**
 * Add menu options and menu page.
 */

function add_custom_menu_option() {
    add_menu_page('Woo-Vtiger Sync', 'Woo-Vtiger Sync', 'read', 'woo-vtiger-syncing', 'include_vtiger_connectivity_ui', 'dashicons-share-alt', 58);
    add_submenu_page( 'woo-vtiger-syncing', 'Vtiger connectivity', 'Vtiger connectivity', 'read', 'woo-vtiger-syncing');
    add_submenu_page( 'woo-vtiger-syncing', 'Auto Syncing', 'Auto Syncing', 'read', 'woo-vtiger-auto-syncing', 'include_auto_syncing_ui');
    add_submenu_page( 'woo-vtiger-syncing', 'Manual Syncing', 'Manual Syncing', 'read', 'woo-vtiger-manual-syncing', 'include_manual_syncing_ui');
}

/**
 * Include plugin's front end files
 */
function include_vtiger_connectivity_ui()
{
    /* Load front end file for plugin. */
    require_once( WOO_VTIGER_UI_DIR . 'vtiger-connectivity-ui.php' );
}

function include_manual_syncing_ui()
{
    /* Load front end file for plugin. */
    require_once( WOO_VTIGER_UI_DIR . 'manual-syncing-ui.php' );
}

function include_auto_syncing_ui()
{
    /* Load front end file for plugin. */
    require_once( WOO_VTIGER_UI_DIR . 'auto-syncing-ui.php' );
}

/**
 * Insert vtiger data into table
 */
function insert_vtiger_data_into_table()
{
    $endpointUrl        =   $_POST['crm_endpointurl'];
    $userName           =   $_POST['crm_username'];
    $userAccessKey      =   $_POST['crm_access_key'];
    $crm_db_hostname    =   $_POST['crm_db_hostname'];
    $crm_db_username    =   $_POST['crm_db_username'];
    $crm_db_password    =   $_POST['crm_db_password'];
    $crm_db_name        =   $_POST['crm_db_name'];
    $crm_root_path      =   $_POST['crm_root_path'];

    global $wpdb;
    $table_name = $wpdb->prefix.'WVS_vtigercrm_login_info';

    // Check data is already inserted or not
    $result = $wpdb->get_results( "SELECT * FROM ".$table_name." WHERE id = 1" );    
    
    if(empty($result))
    {
        $wpdb->insert($table_name, array('id' => 1, 
                                        'crm_endpointurl' => $endpointUrl, 
                                        'crm_username' => $userName,
                                        'crm_access_key' => $userAccessKey,
                                        'crm_db_hostname' => $crm_db_hostname,
                                        'crm_db_username' => $crm_db_username,
                                        'crm_db_password' => $crm_db_password, 
                                        'crm_db_name' => $crm_db_name,
                                        'crm_root_path' => $crm_root_path)
                        );
    }
    else
    {
        $wpdb->update($table_name, 
                        array('id' => 1, 
                            'crm_endpointurl' => $endpointUrl, 
                            'crm_username' => $userName,
                            'crm_access_key' => $userAccessKey,
                            'crm_db_hostname' => $crm_db_hostname,
                            'crm_db_username' => $crm_db_username,
                            'crm_db_password' => $crm_db_password, 
                            'crm_db_name' => $crm_db_name,
                            'crm_root_path' => $crm_root_path), 
                        array( 'id' => 1 ), 
                        array('%d','%s','%s','%s','%s','%s','%s', '%s', '%s'), 
                        array( '%d' ) 
                    );
    }
}


/**
 * Get vtiger data from table
 */
function get_vtiger_crm_data_info()
{
    // Get Vtiger data info store in woocommerce database
    global $wpdb;
    $vtigerData = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."WVS_vtigercrm_login_info WHERE id = 1" );    
    foreach ($vtigerData as $data) {
    $vtigerArray  =  array('id' => $data->id, 
                        'crm_endpointurl' => $data->crm_endpointurl, 
                        'crm_username' => $data->crm_username,
                        'crm_access_key' => $data->crm_access_key,
                        'crm_db_hostname' => $data->crm_db_hostname,
                        'crm_db_username' => $data->crm_db_username,
                        'crm_db_password' => $data->crm_db_password, 
                        'crm_db_name' => $data->crm_db_name,
                        'crm_root_path' => $data->crm_root_path); 
    }
    return $vtigerArray;
}

/**
 * Get last synchronize date from database
 */
function get_last_sync_date($module_type)
{
    global $wpdb;
    $sync_data_row = $wpdb->get_results( "SELECT id, last_sync_date FROM ".$wpdb->prefix."WVS_sync_date_info WHERE module_type = '".$module_type."' " );    
    foreach($sync_data_row as $sync_data) {
        return $sync_data->last_sync_date;
    }
}

/**
 * Get last syncing time for both "auto and manual syncing"
 */
function get_last_sync_time()
{
    global $wpdb;
    $sync_time_row = $wpdb->get_results( "SELECT id, sync_type, set_time, last_sync_time, description FROM ".$wpdb->prefix."WVS_last_sync_time_details" );    
    return $sync_time_row;
}


/**
 * Get deleted products from woocommerce
 */

add_action( 'before_delete_post', 'get_deleted_product' );

function get_deleted_product( $postid )
{
    // We check if the global post type isn't ours and just return
    global $post_type;   
    if ( $post_type != 'product' ) return;

    // My custom stuff for deleting my custom post type here
    $product_meta = get_post_meta($postid);
    $product_no = $product_meta['product_no'][0];             
    $product_crm_id = $product_meta['product_crm_id'][0];

    global $wpdb;
    $table_name = $wpdb->prefix.'WVS_deleted_product_info';
    $wpdb->insert($table_name, array('post_id' => $postid, 'post_type' => 'product', 'product_no' => $product_no, 'product_crm_id' => $product_crm_id));    
}


/**
 * Get deleted contacts from woocommerce
 */

add_action( 'delete_user', 'get_deleted_contact' );

function get_deleted_contact( $user_id )
{
    // My custom stuff for deleting my custom post type here
    $user_meta = get_user_meta($user_id);
    $contact_no = $user_meta['contact_no'][0];             
    $contact_crm_id = $user_meta['contact_crm_id'][0];

    global $wpdb;
    $table_name = $wpdb->prefix.'WVS_deleted_contact_info';
    $wpdb->insert($table_name, array('user_id' => $user_id, 'contact_no' => $contact_no, 'contact_crm_id' => $contact_crm_id));    
}

/**
 * Get deleted orders from woocommerce
 */

add_action( 'before_delete_post', 'get_deleted_order' );

function get_deleted_order( $postid )
{
    // We check if the global post type isn't ours and just return
    global $post_type;   
    if ( $post_type != 'shop_order' ) return;

    // My custom stuff for deleting my custom post type here
    $order_meta = get_post_meta($postid);
    $salesorder_no = $order_meta['salesorder_no'][0];             
    $salesorder_crm_id = $order_meta['salesorder_crm_id'][0];

    global $wpdb;
    $table_name = $wpdb->prefix.'WVS_deleted_order_info';
    $wpdb->insert($table_name, array('post_id' => $postid, 'post_type' => 'shop_order', 'salesorder_no' => $salesorder_no, 'salesorder_crm_id' => $salesorder_crm_id));    
}

/**
 * Add custom schedual to worpress
 */

add_filter('cron_schedules', 'cron_interval');

function cron_interval($interval) {
    $interval['1minutes'] = array('interval' => 60, 'display' => 'Every 1 minute');
    $interval['5minutes'] = array('interval' => 5*60, 'display' => 'Every 5 minute');
    $interval['10minutes'] = array('interval' => 10*60, 'display' => 'Every 10 minute');
    $interval['15minutes'] = array('interval' => 15*60, 'display' => 'Every 15 minute');
    $interval['30minutes'] = array('interval' => 30*60, 'display' => 'Every 30 minute');
	
	$interval['2hours'] = array('interval' => 2*60*60, 'display' => 'Every 2 Hours');
	$interval['3hours'] = array('interval' => 3*60*60, 'display' => 'Every 3 Hours');
	$interval['6hours'] = array('interval' => 6*60*60, 'display' => 'Every 6 Hours');
	$interval['9hours'] = array('interval' => 9*60*60, 'display' => 'Every 9 Hours');
    return $interval;
}


/**
 * Get schedule time report
 */

function get_schedule_report($get_schedule)
{
	switch ($get_schedule) {
		case "1minutes":
			$schedule_time = '1 minute';
			break;
		case "5minutes":
			$schedule_time = '5 minute';
			break;
		case "10minutes":
			$schedule_time = '10 minute';
			break;
		case "15minutes":
			$schedule_time = '15 minute';
			break;
		case "30minutes":
			$schedule_time = '30 minute';
			break;
		case "hourly":
			$schedule_time = '1 hour';
			break;
		case "2hours":
			$schedule_time = '2 hours';
			break;
		case "3hours":
			$schedule_time = '3 hours';
			break;
		case "6hours":
			$schedule_time = '6 hours';
			break;
		case "9hours":
			$schedule_time = '9 hours';
			break;
		case "twicedaily":
			$schedule_time = '12 hours';
			break;
		case "daily":
			$schedule_time = '1 day';
			break;
		default:
			echo "nothing";
	}
	return $schedule_time;
}


/**
 * Unschedual te hook on plugin deactivation
 */

function stop_auto_syncing()
{
    if (wp_next_scheduled ( 'MyCronAction' )) {
        // delete running schedule
        wp_clear_scheduled_hook( 'MyCronAction' );
    }
}


/**
 * Start auto syncing on defined time schedual
 */

function start_auto_syncing($timeInterval)
{
    if (! wp_next_scheduled ( 'MyCronAction' )) {
        // start new schedule
        wp_schedule_event(time(), $timeInterval, 'MyCronAction');
    }
    else {
        // delete previous running schedule
        wp_clear_scheduled_hook( 'MyCronAction' );
        // start new schedule
        wp_schedule_event(time(), $timeInterval, 'MyCronAction');
    }
}

add_action('MyCronAction', 'WVS_CronAction_func');

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

    // include file to import products 
	include_once(WOO_VTIGER_INCLUDES_DIR .'woo-vtiger-import-products.php');

	// include file to export products 
	include_once(WOO_VTIGER_INCLUDES_DIR . 'woo-vtiger-export-products.php');

    // include file to export products 
    include_once(WOO_VTIGER_INCLUDES_DIR . 'woo-vtiger-import-contacts.php');

    // include file to export products 
    include_once(WOO_VTIGER_INCLUDES_DIR . 'woo-vtiger-export-contacts.php');

    // include file to export products 
    include_once(WOO_VTIGER_INCLUDES_DIR . 'woo-vtiger-import-orders.php');

    // include file to export products 
    include_once(WOO_VTIGER_INCLUDES_DIR . 'woo-vtiger-export-orders.php');	
}

//Adding new columns to the Orders Page

add_filter( 'manage_edit-shop_order_columns', 'MY_COLUMNS_FUNCTION' );
function MY_COLUMNS_FUNCTION( $columns ) {
    $new_columns = ( is_array( $columns ) ) ? $columns : array();
    unset( $new_columns[ 'order_actions' ] );

    //edit this for your column(s)
    //all of your columns will be added before the actions column
    $new_columns['crm-order'] = 'Crm Order No';

    //stop editing
    $new_columns[ 'order_actions' ] = $columns[ 'order_actions'];
    return $new_columns;
}

//add_filter( "manage_edit-shop_order_sortable_columns", 'MY_COLUMNS_SORT_FUNCTION' );
function MY_COLUMNS_SORT_FUNCTION( $columns )
{
    $custom = array(
        'crm-order'    => 'Order No Crm'
    );
    return wp_parse_args( $custom, $columns );
}

add_action( 'manage_shop_order_posts_custom_column', 'MY_COLUMNS_VALUES_FUNCTION', 2 );
function MY_COLUMNS_VALUES_FUNCTION( $column ) {
    global $post;
    $data = get_post_meta( $post->ID );

    //start editing, I was saving my fields for the orders as custom post meta
    //if you did the same, follow this code

    if ( $column == 'crm-order' ) {
        echo ( isset( $data[ 'salesorder_no'] ) ? $data[ 'salesorder_no' ][0] : '' );
    }
}

?>