<?php
/*
Plugin Name: Appointment Booking Calendar
Plugin URI: http://wordpress.dwbooster.com/calendars/appointment-booking-calendar
Description: This plugin allows you to easily insert appointments forms into your WP website.
Version: 9.1.39
Author: CodePeople.net
Author URI: http://codepeople.net
License: GPL
*/

/* START: time critical validation link settings */

define('CPABC_ENABLE_VALIDATIONS', false);          // Set to true to enable validation link...
                                                   // ...and tag %VALIDATION% should be included into the email content
define('CPABC_VALIDATE_REDIRECT_TO', '/');         // Return address for a successfull validation link.
define('CPABC_VALIDATE_EXPIRED_REDIRECT_TO', '/'); // Return address for a expired validation link
define('CPABC_VALIDATION_TIMEOUT', 6);             // Validation link will expire X hours before the appoinment date.

/* END: time critical validation link settings */

define('CPABC_ENABLE_DEPOSIT', false);
define('CPABC_DEPOSIT_PERCENT', 50);

/* END: email enable/disable options */
define('CPABC_ENABLE_ADMIN_EMAILS', true);
define('CPABC_ENABLE_CUSTOMER_EMAILS', true);

/* initialization / install / uninstall functions */

define('CPABC_CHANGE_DATE_SUBJECT', 'Appointment date modified...');
define('CPABC_CHANGE_DATE_CONTENT', 'Your booking for %olddatecustomer% %oldtimecustomer% was changed to %DATE_CUSTOMER% %TIME_CUSTOMER%.');

define('CPABC_CHANGE_DATE_SUBJECT_ADMIN', 'Appointment date modified...');
define('CPABC_CHANGE_DATE_CONTENT_ADMIN', 'The booking scheduled for %olddate% %oldtime% was changed to %DATE% %TIME%.');


// CANCELLATION LINK SETTINGS
define('CPABC_APPOINTMENTS_DEFAULT_ON_CANCEL_REDIRECT_TO', '/'); // Return address for the cancellation link.
define('CPABC_APPOINTMENTS_DEFAULT_ON_CANCEL_EXPIRED_REDIRECT_TO', '/'); // Return address for the cancellation link if it has expired.
define('CPABC_APPOINTMENTS_DEFAULT_CANCEL_AVAILABLE_UNTIL', 24); // Cancellation link will expire X hours before the appoinment date.
define('CPABC_APPOINTMENTS_DEFAULT_CANCEL_SKIP_WEEKENDS', false); // Cancellation link will expire until X hours before the appoinment date, excluding weekends.

// OTHER SETTINGS
define('CPABC_APPOINTMENTS_AUTO_FILL_LOGGED_USER_DATA', true); // Auto-fill email field with logged in user's email address. Works only in predefined classic form.

define('CPABC_APPOINTMENTS_IDENTIFY_PRICES', false);  // Undocumented feature: Currently disabled. Still in beta version.

define('CPABC_APPOINTMENTS_ACTIVATECC', false);  // CCF activate, not available yet

define('CPABC_APPOINTMENTS_TZONE', true);  // Undocumented, disabled as default

define('CPABC_DISCOUNT_FIELDS', 0); // Undocumented, disabled, future feature not fully tested yet

define('CPABC_APPOINTMENTS_ICAL_OBSERVE_DAYLIGHT', true);  // Undocumented, disabled as default
define('CPABC_APPOINTMENTS_ICAL_DAYLIGHT_ZONE', 'Europe');  // Undocumented, valid valued: Europe, USA

define('CPABC_APPOINTMENTS_ADV_DUPLICITY_VERIFICATION', true);

define('CPABC_APPOINTMENTS_ENABLE_QUANTITY_FIELD', 0);
define('CPABC_APPOINTMENTS_ENABLE_QUANTITY_FIELD_LABEL', 'Quantity');
define('CPABC_APPOINTMENTS_ENABLE_QUANTITY_FIELD_TWO', 0);
define('CPABC_APPOINTMENTS_ENABLE_QUANTITY_FIELD_TWO_LABEL', 'Juniors');
define('CPABC_APPOINTMENTS_ENABLE_AJAX_PRICE', '0');

define('CPABC_APPOINTMENTS_RELOAD_FORM_STRUCTURE', true);

define('CPABC_APPOINTMENTS_DEFAULT_DEFER_SCRIPTS_LOADING', (get_option('CPABC_APPOINTMENTS_LOAD_SCRIPTS',"1") == "1"?true:false));

define('CPABC_APPOINTMENTS_DEFAULT_CURRENCY_SYMBOL','$');
define('CPABC_APPOINTMENTS_GBP_CURRENCY_SYMBOL',chr(163));
define('CPABC_APPOINTMENTS_EUR_CURRENCY_SYMBOL_A','EUR ');
define('CPABC_APPOINTMENTS_EUR_CURRENCY_SYMBOL_B',chr(128));

define('CPABC_APPOINTMENTS_ENABLE_PG_STRIPE', true);
define('CPABC_APPOINTMENTS_ENABLE_PG_AUTHORIZE', false);
define('CPABC_APPOINTMENTS_ENABLE_PG_MOLLIE', false);
define('CPABC_APPOINTMENTS_DK', 'fegDijrfwengYTwe45gwergrqFDeherh');

define('CPABC_APPOINTMENTS_DEFAULT_form_structure', '[[{"name":"email","index":0,"title":"Email","ftype":"femail","userhelp":"","csslayout":"","required":true,"predefined":"","size":"medium"},{"name":"subject","index":1,"title":"Subject","required":true,"ftype":"ftext","userhelp":"","csslayout":"","predefined":"","size":"medium"},{"name":"message","index":2,"size":"large","required":true,"title":"Message","ftype":"ftextarea","userhelp":"","csslayout":"","predefined":""}],[{"title":"","description":"","formlayout":"top_aligned"}]]');

define('CPABC_APPOINTMENTS_DEFAULT_PAYPAL_OPTION_YES', 'Pay with PayPal.');
define('CPABC_APPOINTMENTS_DEFAULT_PAYPAL_OPTION_NO', 'Pay later.');


define('CPABC_APPOINTMENTS_DEFAULT_CALENDAR_LANGUAGE', 'EN');
define('CPABC_APPOINTMENTS_DEFAULT_CALENDAR_DATEFORMAT', '0');
define('CPABC_APPOINTMENTS_DEFAULT_CALENDAR_MILITARYTIME', '1');
define('CPABC_APPOINTMENTS_DEFAULT_CALENDAR_WEEKDAY', '0');
define('CPABC_APPOINTMENTS_DEFAULT_CALENDAR_MINDATE', 'today');
define('CPABC_APPOINTMENTS_DEFAULT_CALENDAR_MAXDATE', '');
define('CPABC_APPOINTMENTS_DEFAULT_CALENDAR_PAGES', 1);

define('CPABC_APPOINTMENTS_DEFAULT_cu_user_email_field', 'email');
define('CPABC_APPOINTMENTS_DEFAULT_email_format', 'text');
define('CPABC_APPOINTMENTS_DEFAULT_ENABLE_PAYPAL', 1);
define('CPABC_APPOINTMENTS_DEFAULT_PAYPAL_EMAIL','put_your@email_here.com');
define('CPABC_APPOINTMENTS_DEFAULT_PRODUCT_NAME','Consultation');
define('CPABC_APPOINTMENTS_DEFAULT_COST','25');
define('CPABC_APPOINTMENTS_DEFAULT_OK_URL',get_site_url());
define('CPABC_APPOINTMENTS_DEFAULT_CANCEL_URL',get_site_url());
define('CPABC_APPOINTMENTS_DEFAULT_CURRENCY','USD');
define('CPABC_APPOINTMENTS_DEFAULT_PAYPAL_LANGUAGE','EN');

define('CPABC_APPOINTMENTS_DEFAULT_ENABLE_REMINDER', 0);
define('CPABC_APPOINTMENTS_DEFAULT_REMINDER_HOURS', 24);
define('CPABC_APPOINTMENTS_DEFAULT_REMINDER_SUBJECT', 'Appointment reminder...');
define('CPABC_APPOINTMENTS_DEFAULT_REMINDER_CONTENT', "This is a reminder for your appointment with the following information:\n\n%INFORMATION%\n\nThank you.\n\nBest regards.");

define('CPABC_APPOINTMENTS_DEFAULT_SUBJECT_CONFIRMATION_EMAIL', 'Thank you for your request...');
define('CPABC_APPOINTMENTS_DEFAULT_CONFIRMATION_EMAIL', "We have received your request with the following information:\n\n%INFORMATION%\n\nThank you.\n\nBest regards.");
define('CPABC_APPOINTMENTS_DEFAULT_SUBJECT_NOTIFICATION_EMAIL','New appointment requested...');
define('CPABC_APPOINTMENTS_DEFAULT_NOTIFICATION_EMAIL', "New appointment made with the following information:\n\n%INFORMATION%\n\nBest regards.");

define('CPABC_APPOINTMENTS_DEFAULT_SUBJECT_NOTIFICATION_CEMAIL','Appointment cancelled...');
define('CPABC_APPOINTMENTS_DEFAULT_NOTIFICATION_CEMAIL', "The following appointment was cancelled:\n\n%INFORMATION%\n\nBest regards.");


define('CPABC_APPOINTMENTS_DEFAULT_CP_CAL_CHECKBOXES',"");
define('CPABC_APPOINTMENTS_DEFAULT_EXPLAIN_CP_CAL_CHECKBOXES',"1.00 | Service 1 for us$1.00\n5.00 | Service 2 for us$5.00\n10.00 | Service 3 for us$10.00");

// tables

define('CPABC_APPOINTMENTS_TABLE_NAME_NO_PREFIX', "cpabc_appointments");
define('CPABC_APPOINTMENTS_TABLE_NAME', @$wpdb->prefix . CPABC_APPOINTMENTS_TABLE_NAME_NO_PREFIX);

define('CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX', "cpabc_appointment_calendars_data");
define('CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME', @$wpdb->prefix ."cpabc_appointment_calendars_data");

define('CPABC_APPOINTMENTS_CONFIG_TABLE_NAME_NO_PREFIX', "cpabc_appointment_calendars");
define('CPABC_APPOINTMENTS_CONFIG_TABLE_NAME', @$wpdb->prefix ."cpabc_appointment_calendars");

define('CPABC_APPOINTMENTS_DISCOUNT_CODES_TABLE_NAME_NO_PREFIX', "cpabc_appointments_discount_codes");
define('CPABC_APPOINTMENTS_DISCOUNT_CODES_TABLE_NAME', @$wpdb->prefix ."cpabc_appointments_discount_codes");

// calendar constants

define("CPABC_TDEAPP_DEFAULT_CALENDAR_ID","1");
define("CPABC_TDEAPP_DEFAULT_CALENDAR_LANGUAGE","EN");

define("CPABC_TDEAPP_CAL_PREFIX", "cal");
define("CPABC_TDEAPP_CONFIG",CPABC_APPOINTMENTS_CONFIG_TABLE_NAME);
define("CPABC_TDEAPP_CONFIG_ID","id");
define("CPABC_TDEAPP_CONFIG_TITLE","title");
define("CPABC_TDEAPP_CONFIG_USER","uname");
define("CPABC_TDEAPP_CONFIG_PASS","passwd");
define("CPABC_TDEAPP_CONFIG_LANG","lang");
define("CPABC_TDEAPP_CONFIG_CPAGES","cpages");
define("CPABC_TDEAPP_CONFIG_TYPE","ctype");
define("CPABC_TDEAPP_CONFIG_MSG","msg");
define("CPABC_TDEAPP_CONFIG_WORKINGDATES","workingDates");
define("CPABC_TDEAPP_CONFIG_RESTRICTEDDATES","restrictedDates");
define("CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES0","timeWorkingDates0");
define("CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES1","timeWorkingDates1");
define("CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES2","timeWorkingDates2");
define("CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES3","timeWorkingDates3");
define("CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES4","timeWorkingDates4");
define("CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES5","timeWorkingDates5");
define("CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES6","timeWorkingDates6");
define("CPABC_TDEAPP_CALDELETED_FIELD","caldeleted");

define("CPABC_TDEAPP_CALENDAR_DATA_TABLE",CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME);
define("CPABC_TDEAPP_DATA_ID","id");
define("CPABC_TDEAPP_DATA_IDCALENDAR","appointment_calendar_id");
define("CPABC_TDEAPP_DATA_DATETIME","datatime");
define("CPABC_TDEAPP_DATA_TITLE","title");
define("CPABC_TDEAPP_DATA_DESCRIPTION","description");
// end calendar constants

define('CPABC_TDEAPP_DEFAULT_dexcv_enable_captcha', 'true');
define('CPABC_TDEAPP_DEFAULT_dexcv_width', '180');
define('CPABC_TDEAPP_DEFAULT_dexcv_height', '60');
define('CPABC_TDEAPP_DEFAULT_dexcv_chars', '5');
define('CPABC_TDEAPP_DEFAULT_dexcv_font', 'font-1.ttf');
define('CPABC_TDEAPP_DEFAULT_dexcv_min_font_size', '25');
define('CPABC_TDEAPP_DEFAULT_dexcv_max_font_size', '35');
define('CPABC_TDEAPP_DEFAULT_dexcv_noise', '200');
define('CPABC_TDEAPP_DEFAULT_dexcv_noise_length', '4');
define('CPABC_TDEAPP_DEFAULT_dexcv_background', 'ffffff');
define('CPABC_TDEAPP_DEFAULT_dexcv_border', '000000');
define('CPABC_TDEAPP_DEFAULT_dexcv_text_enter_valid_captcha', 'Please enter a valid captcha code.');

define('CPABC_APPOINTMENTS_DEFAULT_vs_text_is_required', 'This field is required.');
define('CPABC_APPOINTMENTS_DEFAULT_vs_text_is_email', 'Please enter a valid email address.');

define('CPABC_APPOINTMENTS_DEFAULT_vs_text_datemmddyyyy', 'Please enter a valid date with this format(mm/dd/yyyy)');
define('CPABC_APPOINTMENTS_DEFAULT_vs_text_dateddmmyyyy', 'Please enter a valid date with this format(dd/mm/yyyy)');
define('CPABC_APPOINTMENTS_DEFAULT_vs_text_number', 'Please enter a valid number.');
define('CPABC_APPOINTMENTS_DEFAULT_vs_text_digits', 'Please enter only digits.');
define('CPABC_APPOINTMENTS_DEFAULT_vs_text_max', 'Please enter a value less than or equal to {0}.');
define('CPABC_APPOINTMENTS_DEFAULT_vs_text_min', 'Please enter a value greater than or equal to {0}.');


require_once 'cpabc_appointments_data_source.inc.php';

// loading add-ons
// -----------------------------------------
global $cpabc_addons_active_list, // List of addon IDs
	   $cpabc_addons_objs_list; // List of addon objects

$cpabc_addons_active_list = array();
$cpabc_addons_objs_list	 = array();

function cpabc_loading_add_ons()
{
	global $cpabc_addons_active_list, // List of addon IDs
		   $cpabc_addons_objs_list; // List of addon objects

    // Get the list of active addons
	$cpabc_addons_active_list = get_option( 'cpabc_addons_active_list', array() );
	if( !empty( $cpabc_addons_active_list ) || ( isset( $_GET["page"] ) && $_GET["page"] == "cpabc_appointments" )  )
	{
		$path = dirname( __FILE__ ).'/addons';
		if( file_exists( $path ) )
		{
			$addons = dir( $path );
			while( false !== ( $entry = $addons->read() ) )
			{
				if( strlen( $entry ) > 3 && strtolower( pathinfo( $entry, PATHINFO_EXTENSION) ) == 'php' )
				{
					require_once $addons->path.'/'.$entry;
				}
			}
		}
	}
}
cpabc_loading_add_ons();


// code initialization, hooks
// -----------------------------------------

register_activation_hook(__FILE__,'cpabc_appointments_install');


add_action( 'user_register', 'cpabc_registration_save', 10, 1 );
function cpabc_registration_save( $user_id ) {
    global $wpdb;
    $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME." where autocreatecals='1' ORDER BY id ASC" , ARRAY_A);
    if (count ($myrows))
    {
        $orgform = $myrows[0][CPABC_TDEAPP_CONFIG_ID];
        unset($myrows[0][CPABC_TDEAPP_CONFIG_ID]);
        $myrows[0]["autocreatecals"] = 0;
        $myrows[0]["conwer"] = $user_id;
        $udata = get_userdata( $user_id );
        $myrows[0]["notification_destination_email"] = $udata->user_email;
        $myrows[0][CPABC_TDEAPP_CONFIG_USER] = 'User Cal: '.$myrows[0][CPABC_TDEAPP_CONFIG_USER];
        $wpdb->insert( CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, $myrows[0]);
        do_action( 'cpabc_cloneitem', $orgform, $wpdb->insert_id );
    }
}

function cpabc_plugin_init() {
  load_plugin_textdomain( 'cpabc', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
  $ao_options = get_option('autoptimize_js_exclude',"seal.js, js/jquery/jquery.js");
  if (!strpos($ao_options,'stringify.js'))
      update_option('autoptimize_js_exclude',"jQuery.stringify.js,jquery.validate.js,".$ao_options);  
}
add_action('plugins_loaded', 'cpabc_plugin_init');

function cpabc_appointments_install($networkwide)  {
	global $wpdb;

	if (function_exists('is_multisite') && is_multisite()) {
		// check if it is a network activation - if so, run the activation function for each blog id
		if ($networkwide) {
	                $old_blog = $wpdb->blogid;
			// Get all blog ids
			$blogids = $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs" );
			foreach ($blogids as $blog_id) {
				switch_to_blog($blog_id);
				_cpabc_appointments_install();
			}
			switch_to_blog($old_blog);
			return;
		}
	}
	_cpabc_appointments_install();
}

function _cpabc_appointments_install() {
    global $wpdb;


    update_option('CP_ABC_JS', ''); // clean this option

    $table_name = $wpdb->prefix . CPABC_APPOINTMENTS_TABLE_NAME_NO_PREFIX;

    $sql = "CREATE TABLE ".$wpdb->prefix.CPABC_APPOINTMENTS_DISCOUNT_CODES_TABLE_NAME_NO_PREFIX." (
         id mediumint(9) NOT NULL AUTO_INCREMENT,
         cal_id mediumint(9) NOT NULL DEFAULT 1,
         code VARCHAR(250) DEFAULT '' NOT NULL,
         discount VARCHAR(250) DEFAULT '' NOT NULL,
         expires datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
         availability int(10) unsigned NOT NULL DEFAULT 0,
         used int(10) unsigned NOT NULL DEFAULT 0,
         UNIQUE KEY id (id)
         );";
    $wpdb->query($sql);

    $sql = "CREATE TABLE $table_name (
         id int(10) NOT NULL AUTO_INCREMENT,
         `calendar` INT NOT NULL,
         time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
         booked_time VARCHAR(250) DEFAULT '' NOT NULL,
         booked_time_customer VARCHAR(250) DEFAULT '' NOT NULL,
         booked_time_unformatted VARCHAR(250) DEFAULT '' NOT NULL,
         name VARCHAR(250) DEFAULT '' NOT NULL,
         email VARCHAR(250) DEFAULT '' NOT NULL,
         phone VARCHAR(250) DEFAULT '' NOT NULL,
         question mediumtext,
         quantity VARCHAR(25) DEFAULT '1' NOT NULL,
         quantity_a VARCHAR(25) DEFAULT '1' NOT NULL,
         quantity_s VARCHAR(25) DEFAULT '1' NOT NULL,
         buffered_date text,
         who_added  VARCHAR(50) DEFAULT '' NOT NULL,
         UNIQUE KEY id (id)
         );";
    $wpdb->query($sql);

    $sql = "CREATE TABLE `".$wpdb->prefix.CPABC_APPOINTMENTS_CONFIG_TABLE_NAME."` (`".CPABC_TDEAPP_CONFIG_ID."` int(10) unsigned NOT NULL auto_increment, ".
           "`conwer` INT NOT NULL,".
           "`form_structure` mediumtext,".
           "`specialDates` mediumtext,".
           "`enable_paypal_option_yes` VARCHAR(250) DEFAULT '' NOT NULL,".
           "`enable_paypal_option_no` VARCHAR(250) DEFAULT '' NOT NULL,".
           "`stripe_key` VARCHAR(250) DEFAULT '' NOT NULL,".
           "`stripe_secretkey` VARCHAR(250) DEFAULT '' NOT NULL,".
           "`authorizenet_api_id` VARCHAR(250) DEFAULT '' NOT NULL,".
           "`authorizenet_tra_key` VARCHAR(250) DEFAULT '' NOT NULL,".
           "`vs_use_validation` VARCHAR(10) DEFAULT '' NOT NULL,".
           "`vs_text_is_required` VARCHAR(250) DEFAULT '' NOT NULL,".
           "`vs_text_is_email` VARCHAR(250) DEFAULT '' NOT NULL,".
           "`vs_text_datemmddyyyy` VARCHAR(250) DEFAULT '' NOT NULL,".
           "`vs_text_dateddmmyyyy` VARCHAR(250) DEFAULT '' NOT NULL,".
           "`vs_text_number` VARCHAR(250) DEFAULT '' NOT NULL,".
           "`vs_text_digits` VARCHAR(250) DEFAULT '' NOT NULL,".
           "`vs_text_max` VARCHAR(250) DEFAULT '' NOT NULL,".
           "`vs_text_min` VARCHAR(250) DEFAULT '' NOT NULL,".
           "`vs_text_submitbtn` VARCHAR(250) DEFAULT '' NOT NULL,".           
           "`".CPABC_TDEAPP_CONFIG_TITLE."` varchar(255) NOT NULL default '',`".CPABC_TDEAPP_CONFIG_USER."` varchar(100) default NULL,`".CPABC_TDEAPP_CONFIG_PASS."` varchar(100) default NULL,`".CPABC_TDEAPP_CONFIG_LANG."` varchar(5) default NULL,`".CPABC_TDEAPP_CONFIG_CPAGES."` tinyint(3) unsigned default NULL,`".CPABC_TDEAPP_CONFIG_TYPE."` tinyint(3) unsigned default NULL,`".CPABC_TDEAPP_CONFIG_MSG."` varchar(255) NOT NULL default '',`".CPABC_TDEAPP_CONFIG_WORKINGDATES."` varchar(255) NOT NULL default '',`".CPABC_TDEAPP_CONFIG_RESTRICTEDDATES."` text,`".CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES0."` text,`".CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES1."` text,`".CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES2."` text,`".CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES3."` text,`".CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES4."` text,`".CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES5."` text,`".CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES6."` text,".
           "`calendar_language` text,".
           "`calendar_dateformat` text,".
           "`calendar_pages` text,".
           "`calendar_militarytime` text,".
           "`calendar_weekday` text,".
           "`calendar_mindate` text,".
           "`calendar_maxdate` text,".
           "`calendar_startmonth` VARCHAR(20) DEFAULT '' NOT NULL,".
           "`calendar_startyear` VARCHAR(20) DEFAULT '' NOT NULL,".
           "`calendar_theme` text,".
           "`gmt_enabled` VARCHAR(20) DEFAULT '' NOT NULL,".
           "`gmt_diff` VARCHAR(20) DEFAULT '' NOT NULL,".
           "`min_slots` VARCHAR(10) DEFAULT '' NOT NULL,".
           "`max_slots` VARCHAR(10) DEFAULT '' NOT NULL,".
           "`close_fpanel` VARCHAR(10) DEFAULT '' NOT NULL,".
           "`quantity_field` VARCHAR(10) DEFAULT '0' NOT NULL,".
           "`quantity_field_two` VARCHAR(10) DEFAULT '0' NOT NULL,".
           "`quantity_field_label` VARCHAR(250) DEFAULT '".CPABC_APPOINTMENTS_ENABLE_QUANTITY_FIELD_LABEL."' NOT NULL,".
           "`quantity_field_two_label` VARCHAR(250) DEFAULT '".CPABC_APPOINTMENTS_ENABLE_QUANTITY_FIELD_TWO_LABEL."' NOT NULL,".
           "`ajax_load_enabled` VARCHAR(10) DEFAULT '".CPABC_APPOINTMENTS_ENABLE_AJAX_PRICE."' NOT NULL,".
           "`paypal_mode` VARCHAR(10) DEFAULT '' NOT NULL,".
           "`master` VARCHAR(10) DEFAULT '0' NOT NULL,".
           "`enable_paypal` text,".
           "`paypal_email` text,".
           "`request_cost` text,".
           "`request_cost_st` text,".
           "`paypal_price_field` VARCHAR(50) DEFAULT '' NOT NULL,".
           "`paypal_product_name` text,".
           "`currency` text,".
           "`url_ok` text,".
           "`url_cancel` text,".
           "`paypal_language` text,".
           "`cu_user_email_field` VARCHAR(250) DEFAULT '' NOT NULL,".
           "`notification_from_email` text,".
           "`notification_destination_email` text,".
           "`email_subject_confirmation_to_user` text,".
           "`email_confirmation_to_user` text,".
           "`email_subject_notification_to_admin` text,".
           "`email_notification_to_admin` text,".
           "`enable_reminder` text,".
           "`reminder_hours` text,".
           "`reminder_subject` text,".
           "`reminder_content` text,".
           "`cancelredirect` text,".
           "`cancelredirectexpired` text,".
           "`canceluntil` text,".
           "`autocreatecals` VARCHAR(10) DEFAULT '' NOT NULL,".
           "`dexcv_enable_captcha` text,".
           "`dexcv_width` text,".
           "`dexcv_height` text,".
           "`dexcv_chars` text,".
           "`dexcv_min_font_size` text,".
           "`dexcv_max_font_size` text,".
           "`dexcv_noise` text,".
           "`dexcv_noise_length` text,".
           "`dexcv_background` text,".
           "`dexcv_border` text,".
           "`dexcv_font` text,".
           "`cv_text_enter_valid_captcha` VARCHAR(250) DEFAULT '' NOT NULL,".
           "`cp_cal_checkboxes` text,".
           "`nuser_emailformat` text,".
           "`nadmin_emailformat` text,".
           "`nremind_emailformat` text,".           
           "`".CPABC_TDEAPP_CALDELETED_FIELD."` tinyint(3) unsigned default NULL,PRIMARY KEY (`".CPABC_TDEAPP_CONFIG_ID."`)); ";
    $wpdb->query($sql);

    $sql = "CREATE TABLE `".$wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME."` (`".CPABC_TDEAPP_DATA_ID."` int(10) unsigned NOT NULL auto_increment,`".CPABC_TDEAPP_DATA_IDCALENDAR."` int(10) unsigned default NULL,`".CPABC_TDEAPP_DATA_DATETIME."`datetime NOT NULL default '0000-00-00 00:00:00',`".CPABC_TDEAPP_DATA_TITLE."` varchar(250) default NULL,`".CPABC_TDEAPP_DATA_DESCRIPTION."` mediumtext,PRIMARY KEY (`".CPABC_TDEAPP_DATA_ID."`)) ;";
    $wpdb->query($sql);

    $sql = "ALTER TABLE  `".$wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX."` ADD `description_customer` text DEFAULT '' NOT NULL;"; $wpdb->query($sql);

    $sql = "ALTER TABLE  `".$wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX."` ADD `reminder` VARCHAR(1) DEFAULT '' NOT NULL;"; $wpdb->query($sql);
    $sql = "ALTER TABLE  `".$wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX."` ADD `reference` VARCHAR(20) DEFAULT '' NOT NULL;"; $wpdb->query($sql);
    $sql = "ALTER TABLE  `".$wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX."` ADD `quantity` VARCHAR(25) DEFAULT '1' NOT NULL;"; $wpdb->query($sql);
    $sql = "ALTER TABLE  `".$wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX."` ADD `quantity_a` VARCHAR(25) DEFAULT '1' NOT NULL;"; $wpdb->query($sql);
    $sql = "ALTER TABLE  `".$wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX."` ADD `quantity_s` VARCHAR(25) DEFAULT '1' NOT NULL;"; $wpdb->query($sql);

    $sql = "ALTER TABLE  `".$wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX."` ADD `who_added` VARCHAR(25) DEFAULT '' NOT NULL;"; $wpdb->query($sql);
    $sql = "ALTER TABLE  `".$wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX."` ADD `who_edited` VARCHAR(25) DEFAULT '' NOT NULL;"; $wpdb->query($sql);
    $sql = "ALTER TABLE  `".$wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX."` ADD `who_cancelled` VARCHAR(25) DEFAULT '' NOT NULL;"; $wpdb->query($sql);
    $sql = "ALTER TABLE  `".$wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX."` ADD `is_cancelled` VARCHAR(25) DEFAULT '0' NOT NULL;"; $wpdb->query($sql);
    $sql = "ALTER TABLE  `".$wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX."` ADD `is_verified` VARCHAR(25) DEFAULT '0' NOT NULL;"; $wpdb->query($sql);
    $sql = "ALTER TABLE  `".$wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX."` ADD `verified_required` VARCHAR(25) DEFAULT '0' NOT NULL;"; $wpdb->query($sql);
    $sql = "ALTER TABLE  `".$wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX."` ADD `cancelled_reason` TEXT;"; $wpdb->query($sql);

    $sql = 'INSERT INTO `'.$wpdb->prefix.CPABC_APPOINTMENTS_CONFIG_TABLE_NAME.'` (conwer,`form_structure`,`'.CPABC_TDEAPP_CONFIG_ID.'`,`'.CPABC_TDEAPP_CONFIG_TITLE.'`,`'.CPABC_TDEAPP_CONFIG_USER.'`,`'.CPABC_TDEAPP_CONFIG_PASS.'`,`'.CPABC_TDEAPP_CONFIG_LANG.'`,`'.CPABC_TDEAPP_CONFIG_CPAGES.'`,`'.CPABC_TDEAPP_CONFIG_TYPE.'`,`'.CPABC_TDEAPP_CONFIG_MSG.'`,`'.CPABC_TDEAPP_CONFIG_WORKINGDATES.'`,`'.CPABC_TDEAPP_CONFIG_RESTRICTEDDATES.'`,`'.CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES0.'`,`'.CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES1.'`,`'.CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES2.'`,`'.CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES3.'`,`'.CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES4.'`,`'.CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES5.'`,`'.CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES6.'`,`'.CPABC_TDEAPP_CALDELETED_FIELD.'`) '.
                                                                                ' VALUES(0,"'.esc_sql(CPABC_APPOINTMENTS_DEFAULT_form_structure).'","1","cal1","Calendar Item 1","","ENG","1","3","Please, select your appointment.","1,2,3,4,5","","","9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0","9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0","9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0","9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0","9:0,10:0,11:0,12:0,13:0,14:0,15:0,16:0","","0");';
    $wpdb->query($sql);

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    //dbDelta($sql);

}



function _cpabc_appointments_get_default_paypal_email() 
{
    return get_the_author_meta('user_email', get_current_user_id());
}


function _cpabc_appointments_get_default_from_email() 
{
    $default_from = strtolower(get_the_author_meta('user_email', get_current_user_id()));
    $domain = str_replace('www.','', strtolower($_SERVER["HTTP_HOST"]));                                  
    while (substr_count($domain,".") > 1)
        $domain = substr($domain, strpos($domain, ".")+1);                 
    $pos = strpos($default_from, $domain);
    if (substr_count($domain,".") == 1 && $pos === false)
        return 'admin@'.$domain;
    else    
        return $default_from;
}


/* Filter for placing the maps into the contents */



function cpabc_appointments_filter_content($atts) {
    global $wpdb;
    extract( shortcode_atts( array(
		'calendar' => '',
		'user' => '',
        'mycalendar' => '',
        'buddypress' => '',
		'readonly' => false
	), $atts ) );

	/**
	 * Filters applied before generate the form,
	 * is passed as parameter an array with the forms attributes, and return the list of attributes
	 */
    if ($calendar == '') $atts["id"] = 1; else $atts["id"] = $calendar;
	$atts = apply_filters( 'cpabc_pre_form',  $atts );

    if ($calendar != '')
        define ('CPABC_CALENDAR_FIXED_ID',$calendar);   
    else if (strtolower($mycalendar) == 'yes')
    {
        $current_user = wp_get_current_user();
        $user = $current_user->user_login;
        $users = $wpdb->get_results( "SELECT user_login,ID FROM ".$wpdb->users." WHERE user_login='".esc_sql($user)."'" );
        if (isset($users[0]))
            define ('CPABC_CALENDAR_USER',$users[0]->ID);
        else
        {
            return __('You must be logged in to see the calendar.','cpabc');      
        }
    }
    else if ($user != '')
    {
        $users = $wpdb->get_results( "SELECT user_login,ID FROM ".$wpdb->users." WHERE user_login='".esc_sql($user)."'" );
        if (isset($users[0]))
            define ('CPABC_CALENDAR_USER',$users[0]->ID);
        else
            define ('CPABC_CALENDAR_USER',0);
    }
    else
        define ('CPABC_CALENDAR_USER',0);
    ob_start();
    cpabc_appointments_get_public_form($readonly, ($buddypress != '' ? true : false));
    $buffered_contents = ob_get_contents();
    ob_end_clean();

	/**
	 * Filters applied after generate the form,
	 * is passed as parameter the HTML code of the form with the corresponding <LINK> and <SCRIPT> tags,
	 * and returns the HTML code to includes in the webpage
	 */
	$buffered_contents = apply_filters( 'cpabc_the_form', $buffered_contents,  CP_CALENDAR_ID );

    return $buffered_contents;
}


function cpabc_appointments_filter_content_read_only($atts) {
    $atts["readonly"] = true;
    return cpabc_appointments_filter_content($atts);
}


function cpabc_appointments_filter_edit($atts) {
    global $wpdb;
    extract( shortcode_atts( array(
		'calendar' => '',
		'user' => '',
		'fullsettings' => false,
	), $atts ) );
	$buffered_contents = '';
	$current_user = wp_get_current_user();
    if (intval($calendar))
        $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME." where id=".intval($calendar) );
    else
	    $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME." where conwer<>'' AND conwer='".esc_sql($current_user->ID )."'" );
    if (count($myrows))
    {
        if (!defined('CP_CALENDAR_ID'))
            define ('CP_CALENDAR_ID',$myrows[0]->id);
        define ('CPABC_CALENDAR_ON_PUBLIC_WEBSITE',true);
        define ('CPABC_CALENDAR_ON_PUBLIC_WEBSITE_ONLYCALAREA',$fullsettings);
        ob_start();
        @include_once dirname( __FILE__ ) . '/cpabc_appointments_admin_int.inc.php';
        $buffered_contents = ob_get_contents();
        ob_end_clean();
    }
    return $buffered_contents;
}


function cpabc_appointments_filter_mylist($atts) {
    global $wpdb;
    extract( shortcode_atts( array(
		'calendar' => '',
		'user' => '',  // user that owns the calendar
		'group' => 'no',
		'fields' => 'DATE,TIME,fieldname1',
		'from' => "today -20 years ",
		'onlyuser' => '',  // user that made the booking
		'to' => "today +20 years",
		'emailfield' => "email",
		'namefield' => "fieldname1"
	), $atts ) );

    ob_start();


    //aca postear a la misma pagina de la lista, update the date and see what to do with the email notification
    if ($_POST["cpabc_appointments_post_update"])
    {
       define ('CP_CALENDAR_ID', $_POST["cpabc_appointments_post_update"]);
       // START:: PROCESS POSTED DATES
       $_POST["dateAndTime"] =   explode(";",str_replace(",","-",$_POST["selDaycal".CP_CALENDAR_ID]));
       array_shift($_POST["dateAndTime"]);
       $_POST["dateAndTime"] = $_POST["dateAndTime"][0];

       if ($_POST["tzonelistcal".CP_CALENDAR_ID] == '')
          $_POST["tzonelistcal".CP_CALENDAR_ID] = $_POST["selDaycal".CP_CALENDAR_ID];

       $_POST["dateAndTime_customer"] =   explode(";",str_replace(",","-",@$_POST["tzonelistcal".CP_CALENDAR_ID]));
       array_shift($_POST["dateAndTime_customer"]);
       $_POST["dateAndTime_customer"] = $_POST["dateAndTime_customer"][0];
       
       $format = cpabc_appointments_getDateFormat();
       $_POST["dateAndTime"] = date("Y-m-d H:i:s",strtotime($_POST["dateAndTime"]));
       $_POST["Date"] = date($format,strtotime($_POST["dateAndTime"]));
       $_POST["dateAndTime_customer"] = date("Y-m-d H:i:s",strtotime(@$_POST["dateAndTime_customer"]));
       $_POST["Date_customer"] = date($format,strtotime($_POST["dateAndTime_customer"]));

       // END:: PROCESS POSTED DATES

       $mycalendarrows = $wpdb->get_results( "SELECT ".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".id as itemnumber,".
                                                      CPABC_TDEAPP_CALENDAR_DATA_TABLE.".*,".
                                                      CPABC_APPOINTMENTS_TABLE_NAME.".*,".
                                                      CPABC_APPOINTMENTS_CONFIG_TABLE_NAME.".*".
                                      " FROM ".CPABC_TDEAPP_CALENDAR_DATA_TABLE .
                                      " INNER JOIN  ".CPABC_APPOINTMENTS_TABLE_NAME." on  ".CPABC_APPOINTMENTS_TABLE_NAME.".id=".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".reference " .
                                      " INNER JOIN  ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME." on  ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME.".id=".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".appointment_calendar_id " .
                                      "WHERE ".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".id=".intval($_POST["cpabc_edit_item"]));

       $wpdb->update(CPABC_TDEAPP_CALENDAR_DATA_TABLE, array("datatime" => $_POST["dateAndTime"]),array ("id" => $mycalendarrows[0]->itemnumber));
       $wpdb->update(CPABC_TDEAPP_CALENDAR_DATA_TABLE, array("description" => 'Rebooked to '.$_POST["Date"].'<br />'.$mycalendarrows[0]->description), array ("id" => $mycalendarrows[0]->itemnumber));
       $wpdb->update(CPABC_TDEAPP_CALENDAR_DATA_TABLE, array("description_customer" => 'Rebooked to '.$_POST["Date_customer"]."<br />".$mycalendarrows[0]->description_customer), array ("id" => $mycalendarrows[0]->itemnumber));


       $params = unserialize($mycalendarrows[0]->buffered_date);
       $saved_params = $params;
       $params["dateAndTime"] = $_POST["dateAndTime"];
       $params["dateAndTime_customer"] = $_POST["dateAndTime_customer"];
       $params["Date_customer"]  = $_POST["Date_customer"];
       $params["DATE"] = date("d/m/Y",strtotime($_POST["dateAndTime"]));
       $params["DATE_CUSTOMER"] = date("d/m/Y",strtotime($_POST["dateAndTime_customer"]));
       $params["TIME"] = date("H:i",strtotime($_POST["dateAndTime"]));
       $params["TIME_CUSTOMER"] = date("H:i",strtotime($_POST["dateAndTime_customer"]));

       $wpdb->update(CPABC_APPOINTMENTS_TABLE_NAME, array("buffered_date" => serialize($params)),array ("id" => $mycalendarrows[0]->reference));
       $wpdb->update(CPABC_APPOINTMENTS_TABLE_NAME, array("booked_time_unformatted" => $_POST["dateAndTime"]),array ("id" => $mycalendarrows[0]->reference));
       $wpdb->update(CPABC_APPOINTMENTS_TABLE_NAME, array("booked_time" => $_POST["Date"]),array ("id" => $mycalendarrows[0]->reference));
       $wpdb->update(CPABC_APPOINTMENTS_TABLE_NAME, array("booked_time_customer" => $_POST["Date_customer"]),array ("id" => $mycalendarrows[0]->reference));

       $params["olddatecustomer"] = $saved_params["DATE_CUSTOMER"];
       $params["oldtimecustomer"] = $saved_params["TIME_CUSTOMER"];
       $params["olddate"] = $saved_params["DATE"];
       $params["oldtime"] = $saved_params["TIME"];

       // SEND EMAIL TO CUSTOMER
       $email_content = CPABC_CHANGE_DATE_CONTENT;
       foreach ($params as $item => $value)
           $email_content = str_replace('%'.$item.'%',(is_array($value)?(implode(", ",$value)):($value)),$email_content);
       if (CPABC_ENABLE_CUSTOMER_EMAILS)    
           wp_mail(strtolower($params[$emailfield]), CPABC_CHANGE_DATE_SUBJECT_ADMIN, $email_content,
                "From: $SYSTEM_EMAIL\r\n".
                $content_type.
                "X-Mailer: PHP/" . phpversion(), $attachments_customer);

       // SEND EMAIL TO ADMIN
       $SYSTEM_EMAIL = trim(cpabc_get_option('notification_from_email', _cpabc_appointments_get_default_from_email()));
       $SYSTEM_RCPT_EMAIL = cpabc_get_option('notification_destination_email', _cpabc_appointments_get_default_paypal_email());
       $toem = explode(",",$SYSTEM_RCPT_EMAIL);
       $email_content = CPABC_CHANGE_DATE_CONTENT_ADMIN;
       foreach ($params as $item => $value)
           $email_content = str_replace('%'.$item.'%',(is_array($value)?(implode(", ",$value)):($value)),$email_content);
       foreach ($toem as $item)
            if (trim($item) != '' && CPABC_ENABLE_ADMIN_EMAILS)
            {
                wp_mail(strtolower(trim($item)), CPABC_CHANGE_DATE_SUBJECT_ADMIN, $email_content,
                    "From: $SYSTEM_EMAIL\r\n".
                    ($replyto!=''?"Reply-To: ".$replyto."\r\n":'').
                    $content_type.
                    "X-Mailer: PHP/" . phpversion(), $attachments);
            }

       $_POST["cpabc_display_list"] = 1;
       $_POST["cpabc_edit_item"] = '';
       $_POST["emailfield"] = $params[$emailfield];
       $_POST["namefield"] = $params[$namefield];
    }

    echo '<form action="#abclist" name="abceditform" method="post"><input type="hidden" id="cpabc_edit_item" name="cpabc_edit_item" value="1" /><input type="hidden" id="cpabc_calid" name="cpabc_calid" value="1" />';
    echo '</form>';
    if ($_POST["cpabc_edit_item"])
    {
        $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME." WHERE id=".intval($_POST["cpabc_calid"]));
        define ('CPABC_AUTH_INCLUDE', true);
        define ('CP_CALENDAR_ID',$myrows[0]->id);
        @include dirname( __FILE__ ) . '/cpabc_rebook.inc.php';
    }
    else
    {
        echo '<a name="abclist"></a><form action="#abclist" method="post"><input type="hidden" name="cpabc_display_list" value="1" />';
        echo '<input type="text" name="emailfield" value="'.esc_attr(@$_POST["emailfield"]).'" placeholder="'.__('Email address','cpabc').'">';
        echo '<input type="text" name="namefield" value="'.esc_attr(@$_POST["namefield"]).'" placeholder="'.__('Name','cpabc').'">';
        echo '<input type="submit" name="subbtn" value="'.__('Search','cpabc').'">';
        echo '</form><br />';
    }

    ?>
    <script type="text/javascript">
        function cpabc_cancelitem(id) {
            if (confirm('<?php echo __('Are you sure you want to cancel this booking?','cpabc'); ?>'))
                document.location = '<?php echo cpabc_appointment_get_site_url(); ?>/?cpabc_c=1&i='+id+'&a=1';
        }
        function cpabc_edititem(id,calid) {
            document.getElementById("cpabc_edit_item").value = id;
            document.getElementById("cpabc_calid").value = calid;
            document.abceditform.submit();
        }
    </script>
    <?php

    if ($_POST["cpabc_display_list"])
    {
	    $from = date("Y-m-d 00:00:00", strtotime($from));
	    $to = date("Y-m-d 23:59:59", strtotime($to));
	    $group = strtolower($group);

	    $CPABC_CALENDAR_FIXED_ID = '';
	    $CPABC_CALENDAR_USER = '';

        if ($calendar != '')
            $CPABC_CALENDAR_FIXED_ID = $calendar;
        else if ($user != '')
        {
            $users = $wpdb->get_results( "SELECT user_login,ID FROM ".$wpdb->users." WHERE user_login='".esc_sql($user)."'" );
            if (isset($users[0]))
                $CPABC_CALENDAR_USER = $users[0]->ID;
            else
                $CPABC_CALENDAR_USER = 0;
        }
        else
            $CPABC_CALENDAR_USER = 0;

        if ($CPABC_CALENDAR_USER != '' && $CPABC_CALENDAR_USER != 0)
            $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME." WHERE conwer=".$CPABC_CALENDAR_USER );
        else if ($CPABC_CALENDAR_FIXED_ID != '')
            $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME." WHERE id=".$CPABC_CALENDAR_FIXED_ID );
        else
            $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME );

        $CP_CALENDAR_ID = '';
        foreach($myrows as $item)
            $CP_CALENDAR_ID .= ($CP_CALENDAR_ID==''?'':',').$item->id;


        echo '<link rel="stylesheet" type="text/css" href="'.plugins_url('TDE_AppCalendar/'.cpabc_get_option('calendar_theme','modern/').'all-css.css', __FILE__).'" />';
        $fields = explode(",",$fields);
        $last_date = '';
        if ($onlyuser != '')
            $user_filter = CPABC_TDEAPP_CALENDAR_DATA_TABLE.".who_added='".$onlyuser."' AND ";
        else
            $user_filter = '';
        $mycalendarrows = $wpdb->get_results( "SELECT ".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".id as itemnumber,".
                                                      CPABC_TDEAPP_CALENDAR_DATA_TABLE.".*,".
                                                      CPABC_APPOINTMENTS_TABLE_NAME.".*,".
                                                      CPABC_APPOINTMENTS_CONFIG_TABLE_NAME.".*".
                                      " FROM ".CPABC_TDEAPP_CALENDAR_DATA_TABLE .
                                      " INNER JOIN  ".CPABC_APPOINTMENTS_TABLE_NAME." on  ".CPABC_APPOINTMENTS_TABLE_NAME.".id=".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".reference " .
                                      " INNER JOIN  ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME." on  ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME.".id=".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".appointment_calendar_id " .
                                      "WHERE ((is_cancelled<>'1') OR is_cancelled is null) AND ".$user_filter." datatime>='".$from."' AND datatime<='".$to."' AND appointment_calendar_id in (".$CP_CALENDAR_ID.") ORDER BY datatime ASC");

        for($f=0; $f<count($mycalendarrows); $f++) {
            $params = unserialize($mycalendarrows[$f]->buffered_date);
            $params["CALENDAR"] = $mycalendarrows[$f]->uname;
            $params["WEEKDAY"] = date("l",strtotime($mycalendarrows[$f]->booked_time_unformatted));
            $newline = ($last_date != $mycalendarrows[$f]->booked_time_unformatted);
            if ($params[$emailfield] == @$_POST["emailfield"] && $params[$namefield] == @$_POST["namefield"])
            {
                if ($group != 'yes' || $newline)
                {
                    echo '<div class="cpabc_field_clear"></div>';
                }
                for ($k=0; $k < count($fields); $k++)
                {
                    $fieldname = trim($fields[$k]);
                    if ($group == 'yes')
                    {
                        if ($newline || ($fieldname != "DATE" && $fieldname != "TIME"))
                        {
                            echo '<div class="cpabc_field_'.$k.'">';
                            echo (@$params[$fieldname]);
                            if ($fieldname != "DATE" && $fieldname != "TIME")
                            {
                                while ($f<count($mycalendarrows) && @$mycalendarrows[$f+1]->booked_time_unformatted == @$mycalendarrows[$f]->booked_time_unformatted)
                                {
                                    $f++;
                                    $params = unserialize($mycalendarrows[$f]->buffered_date);
                                    echo ", ".@$params[$fieldname];
                                }
                                $k = count($fields);
                            }
                            echo '</div>';
                        }
                    }
                    else
                        echo '<div class="cpabc_field_'.$k.'">'.(@$params[$fieldname]).'&nbsp;</div>';
                }

                // check if item can be cancelled
                if(!defined('CP_CALENDAR_ID')) define ('CP_CALENDAR_ID',$CP_CALENDAR_ID);
                $hours = cpabc_get_option('canceluntil', CPABC_APPOINTMENTS_DEFAULT_CANCEL_AVAILABLE_UNTIL);
                if ($hours == '') $hours = "0";
                $expire_date = date("Y-m-d H:i:s", strtotime($mycalendarrows[$f]->datatime." -".$hours." hours"));
                $weekday = date("N",strtotime($expire_date));
                if (CPABC_APPOINTMENTS_DEFAULT_CANCEL_SKIP_WEEKENDS && $weekday >= 6)
                {
                    if ($weekday == 6)
                        $expire_date = date("Y-m-d", strtotime($expire_date." -1 day" ));
                    else
                        $expire_date = date("Y-m-d", strtotime($expire_date." -2 days" ));
                    $expire_date .= ' 23:59:59';
                }
                $cancel_allowed = !($expire_date < date("Y-m-d H:i:s"));
                // end cancellation verification
                echo '<div class="cpabc_field_'.(count($fields)+1).'" style="text-align:right"> &nbsp;';
                if ($cancel_allowed) echo '[<a href="javascript:cpabc_edititem('.($mycalendarrows[$f]->itemnumber.','.$mycalendarrows[$f]->id).')">'.__('edit','cpabc').'</a>]';
                if ($cancel_allowed) echo ' [<a href="javascript:cpabc_cancelitem(\''.base64_encode($mycalendarrows[$f]->itemnumber).'\')">'.__('cancel','cpabc').'</a>]';
                echo '</div>';
                $last_date = $mycalendarrows[$f]->booked_time_unformatted;
            }
        }
        echo '<div class="cpabc_field_clear"></div>';
    }

    $buffered_contents = ob_get_contents();
    ob_end_clean();

    return $buffered_contents;
}


function cpabc_appointments_getDateFormat() {
    $military_time = cpabc_get_option('calendar_militarytime', CPABC_APPOINTMENTS_DEFAULT_CALENDAR_MILITARYTIME);
    if (cpabc_get_option('calendar_militarytime', CPABC_APPOINTMENTS_DEFAULT_CALENDAR_MILITARYTIME) == '0') $format = "g:i A"; else $format = "H:i";
    $dfoption = cpabc_get_option('calendar_dateformat', CPABC_APPOINTMENTS_DEFAULT_CALENDAR_DATEFORMAT);
    if ($dfoption == '4')
       $format = "l jS F Y ".$format; 
    else if ($dfoption == '3')
       $format = "l jS F ".$format; 
    else if ($dfoption == '0')
       $format = "m/d/Y ".$format;
    else if ($dfoption == '2')
       $format = "d.m.Y ".$format;
    else
        $format = "d/m/Y ".$format;
    return $format;    
}


function cpabc_appointments_filter_list_query($atts) {
    global $wpdb;    
    wp_enqueue_script( "jquery-ui-datepicker" );
    wp_enqueue_style('jquery-style', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css');
    ob_start();
    ?>
      <form action="" method="post">
       <input type="hidden" name="cpabc_appointments_filter" value="1" />
       <table>
        <tr>
         <td align="right"><?php _e('Search for','cpabc'); ?>:</td>
         <td><input type="text" name="abcsearch" value="<?php echo esc_attr(@$_POST["abcsearch"]); ?>" /></td>
         <td align="right"><?php _e('From','cpabc'); ?>:</td>
         <td><input type="text" id="abcdfrom" name="abcdfrom" value="<?php echo esc_attr(@$_POST["abcdfrom"]); ?>" /></td> 
         <td align="right"><?php _e('To','cpabc'); ?>:</td>
         <td><input type="text" id="abcdto" name="abcdto" value="<?php echo esc_attr(@$_POST["abcdto"]); ?>" /></td>
        </tr> 
        <tr>
         <td align="right"><?php _e('Order By','cpabc'); ?></td>
         <td colspan="2">     
           <?php $orderby = @$_POST["abcorderby"]; ?>
           <select name="abcorderby">
            <option value="<?php echo CPABC_TDEAPP_CALENDAR_DATA_TABLE; ?>.id DESC" <?php if ($orderby == 'id DESC') echo ' selected'; ?>><?php _e('Submission time - desc','cpabc'); ?></option>
            <option value="<?php echo CPABC_TDEAPP_CALENDAR_DATA_TABLE; ?>.id ASC" <?php if ($orderby == 'id ASC') echo ' selected'; ?>><?php _e('Submission time - asc','cpabc'); ?></option>
            <option value="datatime DESC" <?php if ($orderby == 'datatime DESC') echo ' selected'; ?>><?php _e('Appointment time - desc','cpabc'); ?></option>
            <option value="datatime ASC" <?php if ($orderby == 'datatime ASC') echo ' selected'; ?>><?php _e('Appointment time - asc','cpabc'); ?></option>
           </select>     
           <span class="submit"><input type="submit" name="ds" value="<?php _e('Filter','cpabc'); ?>" /></span> 
         </td>
        </tr>
       </table>  
      </form>    
      <script type="text/javascript">
       var $j = jQuery.noConflict();
       $j(function() {
       	$j("#abcdfrom").datepicker({     	                
                          dateFormat: 'yy-mm-dd'
                       });
       	$j("#abcdto").datepicker({     	                
                          dateFormat: 'yy-mm-dd'
                       });
       });
       
      </script>
    <?php
    $buffered_contents = ob_get_contents();
    if (!is_array($atts)) $atts = array();
    ob_end_clean();
    if (@$_POST["abcdfrom"])
        $atts["from"] = date("Y-m-d", strtotime($_POST["abcdfrom"]));
    if (@$_POST["abcdto"])
        $atts["to"] = date("Y-m-d", strtotime($_POST["abcdto"]));
    if (@$_POST["abcorderby"])
        $atts["orderby"] = $_POST["abcorderby"];
    if (@$_POST["abcsearch"])
        $atts["query"] = $_POST["abcsearch"];
    return $buffered_contents.cpabc_appointments_filter_list($atts);
}

function cpabc_appointments_filter_list($atts) {
    global $wpdb;
    extract( shortcode_atts( array(
		'calendar' => '',
		'user' => '',
		'cancel' => 'false',
		'group' => 'no',
		'fields' => 'DATE,TIME,NAME',
		'from' => "today",
		'onlyuser' => '',
        'orderby' => 'datatime ASC',
        'query' => '',
		'to' => "today +30 days",
        'displaycancel' => 'false',
        'displayslots' => 'no',        
	), $atts ) );

	$from = date("Y-m-d 00:00:00", strtotime($from));
	$to = date("Y-m-d 23:59:59", strtotime($to));
	$group = strtolower($group);

	$CPABC_CALENDAR_FIXED_ID = '';
	$CPABC_CALENDAR_USER = '';

    if ($calendar != '')
        $CPABC_CALENDAR_FIXED_ID = intval($calendar);
    else if ($user != '')
    {  
        $users = $wpdb->get_results( "SELECT user_login,ID FROM ".$wpdb->users." WHERE user_login='".esc_sql($user)."'" );
        if (isset($users[0]))
            $CPABC_CALENDAR_USER = $users[0]->ID;
        else
            $CPABC_CALENDAR_USER = 0;
    }
    else
        $CPABC_CALENDAR_USER = 0;

    if ($CPABC_CALENDAR_USER != '' && $CPABC_CALENDAR_USER != 0)
    {    
        $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME." WHERE conwer=".$CPABC_CALENDAR_USER );
        if (!count($myrows))
            return '';
    }
    else if ($CPABC_CALENDAR_FIXED_ID != '')
        $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME." WHERE id=".$CPABC_CALENDAR_FIXED_ID );
    else
        $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME );

    $CP_CALENDAR_ID = '';
    foreach($myrows as $item)
        $CP_CALENDAR_ID .= ($CP_CALENDAR_ID==''?'':',').$item->id;

    ob_start();
    echo '<link rel="stylesheet" type="text/css" href="'.plugins_url('TDE_AppCalendar/'.cpabc_get_option('calendar_theme','modern/').'all-css.css', __FILE__).'" />';
    $fields = explode(",",$fields);
    $last_date = '';
    if ($onlyuser != '')
        $user_filter = CPABC_TDEAPP_CALENDAR_DATA_TABLE.".who_added='".$onlyuser."' AND ";
    else
        $user_filter = '';
    if ($cancel != 'true')
        $user_filter .= " ((is_cancelled is Null) OR (is_cancelled<>'1')) AND ";
    
    if ($query != '') $user_filter .= " (".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".title like '%".esc_sql($query)."%' OR description LIKE '%".esc_sql($query)."%') AND ";
    
    $mycalendarrows = $wpdb->get_results( "SELECT ".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".id as itemnumber,".
                                                      CPABC_TDEAPP_CALENDAR_DATA_TABLE.".*,".
                                                      CPABC_APPOINTMENTS_TABLE_NAME.".*,".
                                                      CPABC_APPOINTMENTS_CONFIG_TABLE_NAME.".* FROM ".CPABC_TDEAPP_CALENDAR_DATA_TABLE .
                                  " INNER JOIN  ".CPABC_APPOINTMENTS_TABLE_NAME." on  ".CPABC_APPOINTMENTS_TABLE_NAME.".id=".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".reference " .
                                  " INNER JOIN  ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME." on  ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME.".id=".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".appointment_calendar_id " .
                                  "WHERE ".$user_filter." datatime>='".$from."' AND datatime<='".$to."' AND appointment_calendar_id in (".$CP_CALENDAR_ID.") ORDER BY ".$orderby);                            
                                  
    $dfoption = cpabc_get_option('calendar_dateformat', CPABC_APPOINTMENTS_DEFAULT_CALENDAR_DATEFORMAT,$myrows[0]->id);
    if ($dfoption == '0') 
       $format = "m/d/Y"; 
    else if ($dfoption == '2')
       $format = "d.m.Y";
    else
       $format = "d/m/Y";
   
    if (strtolower($displayslots) == 'yes')    
    {
        $used = array();
        foreach($mycalendarrows as $item)
            if (isset($used[$item->booked_time_unformatted]))
                $used[$item->booked_time_unformatted]++;
            else
                $used[$item->booked_time_unformatted] = 1;
        $frommark = date("Y-m-d", strtotime($from));
        while ($frommark < $to)
        {
            $times = cpabc_get_slots_for ($CP_CALENDAR_ID , $frommark);
            foreach($times as $item)
                if (!isset($used[$frommark." ".$item["time"].":00"]) || $used[$frommark." ".$item["time"].":00"] < $item["capacity"])
                {
                    $count_slots = $item["capacity"] - $used[$frommark." ".$item["time"].":00"];
                    for ($k=0;$k<$count_slots; $k++)
                        $mycalendarrows[] = (object) array( 
                                                   'buffered_date' => serialize(array('DATE' => date($format, strtotime($frommark)), 'TIME' => $item["time"])),
                                                   'uname' => '',
                                                   'booked_time_unformatted' => $frommark." ".$item["time"],
                                                 );
                }
            $frommark = date("Y-m-d", strtotime($frommark." +1 day"));
        }
        usort($mycalendarrows, function ($a, $b) { return ($a->booked_time_unformatted < $b->booked_time_unformatted) ? -1 : 1; } );
    }
    
    for($f=0; $f<count($mycalendarrows); $f++) {
        $params = unserialize($mycalendarrows[$f]->buffered_date);
        $params["CALENDAR"] = $mycalendarrows[$f]->uname;
        $params["WEEKDAY"] = date("l",strtotime($mycalendarrows[$f]->booked_time_unformatted));
        $newline = ($last_date != $mycalendarrows[$f]->booked_time_unformatted);
        if ($group != 'yes' || $newline)
        {
            echo '<div class="cpabc_field_clear"></div>';
        }
        for ($k=0; $k < count($fields); $k++)
        {
            $fieldname = trim($fields[$k]);
            if ($group == 'yes')
            {
                if ($newline || ($fieldname != "DATE" && $fieldname != "TIME"))
                {
                    echo '<div class="cpabc_field_'.$k.'">';
                    echo (@$params[$fieldname]);
                    if ($fieldname != "DATE" && $fieldname != "TIME")
                    {
                        while ($f<count($mycalendarrows) && @$mycalendarrows[$f+1]->booked_time_unformatted == @$mycalendarrows[$f]->booked_time_unformatted)
                        {
                            $f++;
                            $params = unserialize($mycalendarrows[$f]->buffered_date);
                            echo ", ".@$params[$fieldname];
                        }
                        $k = count($fields);
                    }
                    echo '</div>';
                }
            }
            else
                echo '<div class="cpabc_field_'.$k.'">'.(@$params[$fieldname]).'&nbsp;</div>';
        }
        if ($displaycancel == "true")
        {
                $expire_date = date("Y-m-d H:i:s", strtotime($mycalendarrows[$f]->datatime." -".$hours." hours"));
                $weekday = date("N",strtotime($expire_date));
                if (CPABC_APPOINTMENTS_DEFAULT_CANCEL_SKIP_WEEKENDS && $weekday >= 6)
                {
                    if ($weekday == 6)
                        $expire_date = date("Y-m-d", strtotime($expire_date." -1 day" ));
                    else
                        $expire_date = date("Y-m-d", strtotime($expire_date." -2 days" ));
                    $expire_date .= ' 23:59:59';
                }            
                $cancel_allowed = !($expire_date < date("Y-m-d H:i:s"));
                echo '<div class="cpabc_field_'.(count($fields)+1).'" style="text-align:right"> &nbsp;';
                echo ' [<a href="javascript:cpabc_cancelitem(\''.base64_encode($mycalendarrows[$f]->itemnumber).'\')">'.__('cancel','cpabc').'</a>]';
                echo '</div>';
        }
        $last_date = $mycalendarrows[$f]->booked_time_unformatted;
    }
    if ($displaycancel == "true")
    {
        ?>
        <script type="text/javascript">
        function cpabc_cancelitem(id) {
            if (confirm('<?php echo __('Are you sure you want to cancel this booking?','cpabc'); ?>'))
                document.location = '<?php echo cpabc_appointment_get_site_url(); ?>/?cpabc_c=1&i='+id+'&a=1';
        }
        </script>
       <?php
    }
    echo '<div class="cpabc_field_clear"></div>';
    $buffered_contents = ob_get_contents();
    ob_end_clean();
    return $buffered_contents;
}


function cpabc_appointments_filter_my_cal_bookings($atts) {
    global $wpdb;
    if (!is_array($atts))
        $atts = array();
    $current_user = wp_get_current_user();
    $user_id = $current_user->user_login;
    $atts["user"] = $user_id;
    return cpabc_appointments_filter_list($atts);
}


function cpabc_appointments_filter_my_bookings($atts) {
    global $wpdb;
    if (!is_array($atts))
        $atts = array();    
    $current_user = wp_get_current_user();
    $user_id = $current_user->id;
    $atts["onlyuser"] = $user_id;
    return cpabc_appointments_filter_list($atts);
}


function cpabc_appointments_get_public_form($readonly, $iswidget = false) {

    global $wpdb;
    
    if ($iswidget && function_exists('bp_displayed_user_id') && bp_displayed_user_id())
        define ('CPABC_CALENDAR_USER',  bp_displayed_user_id()); 
    
    if (defined('CPABC_CALENDAR_USER') && CPABC_CALENDAR_USER != 0)
        $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME." WHERE conwer=".CPABC_CALENDAR_USER." AND caldeleted=0" );
    else if (defined('CPABC_CALENDAR_FIXED_ID'))
        $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME." WHERE id=".CPABC_CALENDAR_FIXED_ID." AND caldeleted=0" );    
    else    
        $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME." WHERE caldeleted=0" );
    
    
    define ('CP_CALENDAR_ID',$myrows[0]->id);

    $button_label = cpabc_get_option('vs_text_submitbtn', 'Continue');
    $button_label = ($button_label==''?'Continue':$button_label);

    $previous_label = __("Previous",'cpabc');
    $next_label = __("Next",'cpabc');


    if (get_option('CPABC_APPOINTMENTS_DEFAULT_USE_EDITOR',"1") != "1")
    {
        if (CPABC_APPOINTMENTS_DEFAULT_DEFER_SCRIPTS_LOADING)
        {
            wp_deregister_script('query-stringify');
            wp_register_script('query-stringify', plugins_url('/js/jQuery.stringify.js', __FILE__));

            wp_deregister_script('cp_abc_validate_script');
            wp_register_script('cp_abc_validate_script', plugins_url('/js/jquery.validate.js', __FILE__));

            wp_enqueue_script( 'cp_contactformpp_buikder_script',
             get_site_url( get_current_blog_id() ).'?cp_abc_resources=public',array("jquery","jquery-ui-core","jquery-ui-button","jquery-ui-datepicker","jquery-ui-widget","jquery-ui-position","jquery-ui-tooltip","query-stringify","cp_abc_validate_script"), false, true );

            wp_localize_script('cp_contactformpp_buikder_script', 'cp_contactformpp_fbuilder_config', array('obj'  	=>
'{"pub":true,"messages": {
"required": "'.str_replace(array('"'),array('\\"'),cpabc_get_option('vs_text_is_required', CPABC_APPOINTMENTS_DEFAULT_vs_text_is_required)).'",
"email": "'.str_replace(array('"'),array('\\"'),cpabc_get_option('vs_text_is_email', CPABC_APPOINTMENTS_DEFAULT_vs_text_is_email)).'",
"datemmddyyyy": "'.str_replace(array('"'),array('\\"'),cpabc_get_option('vs_text_datemmddyyyy', CPABC_APPOINTMENTS_DEFAULT_vs_text_datemmddyyyy)).'",
"dateddmmyyyy": "'.str_replace(array('"'),array('\\"'),cpabc_get_option('vs_text_dateddmmyyyy', CPABC_APPOINTMENTS_DEFAULT_vs_text_dateddmmyyyy)).'",
"number": "'.str_replace(array('"'),array('\\"'),cpabc_get_option('vs_text_number', CPABC_APPOINTMENTS_DEFAULT_vs_text_number)).'",
"digits": "'.str_replace(array('"'),array('\\"'),cpabc_get_option('vs_text_digits', CPABC_APPOINTMENTS_DEFAULT_vs_text_digits)).'",
"max": "'.str_replace(array('"'),array('\\"'),cpabc_get_option('vs_text_max', CPABC_APPOINTMENTS_DEFAULT_vs_text_max)).'",
"min": "'.str_replace(array('"'),array('\\"'),cpabc_get_option('vs_text_min', CPABC_APPOINTMENTS_DEFAULT_vs_text_min)).'",
"previous": "'.str_replace(array('"'),array('\\"'),$previous_label).'",
"next": "'.str_replace(array('"'),array('\\"'),$next_label).'"
}}'
    	    ));
        } else {
            wp_enqueue_script( "jquery" );
            wp_enqueue_script( "jquery-ui-core" );
            wp_enqueue_script( "jquery-ui-datepicker" );
        }
    }
    else
        wp_enqueue_script( 'jquery' );

    $calendar_items = '';
    foreach ($myrows as $item)
      $calendar_items .=  '<option value='.$item->id.'>'.$item->uname.'</option>';

    $cpabc_buffer = "";
    $services = explode("\n",cpabc_get_option('cp_cal_checkboxes', CPABC_APPOINTMENTS_DEFAULT_CP_CAL_CHECKBOXES));
    foreach ($services as $item)
        if (trim($item) != '')
            $cpabc_buffer .= '<option value="'.esc_attr(trim($item)).'">'.trim(substr($item,strpos($item,"|")+1)).'</option>';

    $codes = $wpdb->get_results( 'SELECT * FROM '.CPABC_APPOINTMENTS_DISCOUNT_CODES_TABLE_NAME.' WHERE `cal_id`='.CP_CALENDAR_ID);

    $quant_buffer = '';
    $qant_value = cpabc_get_option('quantity_field','0');
    $quantlabel = cpabc_get_option('quantity_field_label',CPABC_APPOINTMENTS_ENABLE_QUANTITY_FIELD_LABEL);
    $qant_value_two = '0';
    if ($qant_value != '0' && $qant_value != '' && $quantlabel != '')
    {
        $qant_value = intval($qant_value);
        $quant_buffer = '<div class="abc_quantity fields"><label>'.__($quantlabel,'cpabc').':</label><div><select id="abc_capacity_a" name="abc_capacity_a" onchange="apc_clear_date();">';
        for ($i=0; $i<=$qant_value; $i++)
            $quant_buffer .= '<option'.($i==1?' selected="selected"':'').'>'.$i.'</option>';
        $quant_buffer .= '</select></div></div>';

        $qant_value_two = cpabc_get_option('quantity_field_two','0');
        if ($qant_value_two != '0' && $qant_value_two != '')
        {
            $quant_buffer .= __(cpabc_get_option('quantity_field_two_label',CPABC_APPOINTMENTS_ENABLE_QUANTITY_FIELD_TWO_LABEL),'cpabc').':<br /><select id="abc_capacity_s" name="abc_capacity_s" onchange="apc_clear_date();">';
            for ($i=0; $i<=$qant_value_two; $i++)
                $quant_buffer .= '<option'.($i==0?' selected="selected"':'').'>'.$i.'</option>';
            $quant_buffer .= '</select><br />';
        }

        $quant_buffer .= '<input type="hidden" id="abc_capacity" name="abc_capacity" value="1">';
    }

    ?>
</p> <!-- this p tag fixes a IE bug -->
<link rel="stylesheet" type="text/css" href="<?php echo plugins_url('TDE_AppCalendar/'.(is_admin()?'':cpabc_get_option('calendar_theme','modern/')).'all-css.css', __FILE__); ?>" />
<script>
var pathCalendar = "<?php echo cpabc_appointment_get_site_url(); ?>";
var ccminslots = <?php $opt = cpabc_get_option('min_slots', '1'); if ($opt == '') $opt = '1'; echo $opt; ?>;
var ccmaxslots = <?php $opt = cpabc_get_option('max_slots', '1'); if ($opt == '') $opt = '1'; echo $opt; ?>;
var cpabc_global_date_format = '<?php echo cpabc_get_option('calendar_dateformat', CPABC_APPOINTMENTS_DEFAULT_CALENDAR_DATEFORMAT); ?>';
var cpabc_global_military_time = '<?php echo cpabc_get_option('calendar_militarytime', CPABC_APPOINTMENTS_DEFAULT_CALENDAR_MILITARYTIME); ?>';
var cpabc_global_start_weekday = '<?php echo cpabc_get_option('calendar_weekday', CPABC_APPOINTMENTS_DEFAULT_CALENDAR_WEEKDAY); ?>';
var cpabc_global_mindate = '<?php $value = cpabc_get_option('calendar_mindate', CPABC_APPOINTMENTS_DEFAULT_CALENDAR_MINDATE); if ($value != '') echo date("n/j/Y", strtotime($value)); ?>';
var cpabc_global_maxdate = '<?php $value = cpabc_get_option('calendar_maxdate', CPABC_APPOINTMENTS_DEFAULT_CALENDAR_MAXDATE); if ($value != '') echo date("n/j/Y",strtotime($value)); ?>';
var cpabc_global_gmt_enabled = <?php $value = cpabc_get_option('gmt_enabled', 'no'); if ($value == 'yes' && CPABC_APPOINTMENTS_TZONE) echo 'true'; else echo 'false'; ?>;
var cpabc_global_gmt = <?php $value = cpabc_get_option('gmt_diff', '0'); if ($value != '') echo intval($value); else echo '0'; ?>;
var cpabc_global_close_on_select = <?php $value = cpabc_get_option('close_fpanel', 'yes'); if ($value == '' || $value == 'yes') echo 'true'; else echo 'false'; ?>;
var cpabc_global_cancel_text = '<?php _e("Cancel"); ?>';
var cpabc_global_pagedate = '<?php
    $sm = cpabc_get_option('calendar_startmonth', date("n"));
    $sy = cpabc_get_option('calendar_startyear', date("Y"));
    if ($sm=='0' || $sm=='') $sm = date("n");
    if ($sy=='0' || $sy=='') $sy = date("Y");
    echo $sm."/".$sy;
?>';
</script>
<?php if (!isset($_GET["fl_builder"])) { ?>
<!--noptimize--><script type="text/javascript" src="<?php echo plugins_url('TDE_AppCalendar/all-scripts.js', __FILE__); ?>"></script>
<?php } ?>
<script type="text/javascript">
 var cpabc_current_calendar_item;
 var abc_last_date = '';
 var abc_cost = '';
 function apc_clear_date()
 {
    document.getElementById("selDaycal"+cpabc_current_calendar_item ).value = "";
    <?php if ($qant_value != '0' && $qant_value != '') { ?>
        var adults = document.getElementById("abc_capacity_a").options.selectedIndex;
        <?php if ($qant_value_two != '0' && $qant_value_two != '') { ?>
            var students = document.getElementById("abc_capacity_s").options.selectedIndex;
        <?php } else { ?>
            var students = 0;
        <?php } ?>
        document.getElementById("abc_capacity").value = adults + students;
    <?php } ?>
    cpabc_updateItem(false);
 }
 function cpabc_updateItem(isfullreload)
 {
    document.getElementById("calarea_"+cpabc_current_calendar_item).style.display = "none";
    var i = document.getElementById("cpabc_item").options.selectedIndex;
    var selecteditem = document.getElementById("cpabc_item").options[i].value;
    cpabc_do_init(selecteditem,isfullreload);
 }
 var cpabc_first_load = true;
 var cpabc_load_sync = false;
 function cpabc_do_init(id,isfullreload)
 {
    cpabc_current_calendar_item = id;
    document.getElementById("calarea_"+cpabc_current_calendar_item).style.display = "";
    ccminslots = document.getElementById("ccminslots"+id).value;
    ccmaxslots = document.getElementById("ccmaxslots"+id).value;
    cpabc_global_date_format = document.getElementById("ccpabc_global_date_format"+id).value;
    cpabc_global_military_time = document.getElementById("ccpabc_global_military_time"+id).value;
    cpabc_global_start_weekday = document.getElementById("ccpabc_global_start_weekday"+id).value;
    cpabc_global_mindate = document.getElementById("cmintime"+id).value;
    cpabc_global_maxdate = document.getElementById("cmaxtime"+id).value;
    if (document.getElementById("ccpabc_global_gmt_enabled"+id).value == 'true')
        cpabc_global_gmt_enabled = true;
    else
        cpabc_global_gmt_enabled = false;
    cpabc_global_gmt = document.getElementById("ccpabc_global_gmt"+id).value;
    if (document.getElementById("ccpabc_global_close_on_select"+id).value == 'true')
        cpabc_global_close_on_select = true;
    else
        cpabc_global_close_on_select = false;
    cpabc_global_pagedate = document.getElementById("ccpabc_global_pagedate"+id).value;
    <?php if (!isset($_GET["fl_builder"])) { ?>initAppCalendar("cal"+cpabc_current_calendar_item,document.getElementById("ccpages"+id).value,2,document.getElementById("cclanguage"+id).value,{m1:"<?php if (!$readonly) _e('Please select the appointment time.','cpabc'); ?>"});<?php } ?><?php
if (get_option('CPABC_APPOINTMENTS_DEFAULT_USE_EDITOR',"1") != "1" && CPABC_APPOINTMENTS_RELOAD_FORM_STRUCTURE) {
  ?>if (cpabc_first_load) {
        cpabc_first_load = false;
        return;
    }
    if (!isfullreload) return;
    $dexQuery = jQuery.noConflict();
    $dexQuery.ajax({
                      type: "GET",
                      url: "<?php echo cpabc_appointment_get_site_url(); ?>/?dex_abc=getstructure"+String.fromCharCode(38)
                      +"inAdmin=1"+String.fromCharCode(38)
                      +"cpabc_item="+cpabc_current_calendar_item+""+String.fromCharCode(38),
                    }).done(function( html ) {
                        document.getElementById("form_structure").value = html;
                        try { $dexQuery("#cpcaptchalayer").html($dexQuery(".captcha").html()); } catch (e) {}
                        var f = $dexQuery("#fbuilder").fbuilder($dexQuery.parseJSON(document.getElementById("form_structure").value));
                        f.fBuild.loadData("form_structure");
                    });
    $dexQuery.ajax({
                      type: "GET",
                      url: "<?php echo cpabc_appointment_get_site_url(); ?>/?dex_abc=getservices"+String.fromCharCode(38)
                      +"inAdmin=1"+String.fromCharCode(38)
                      +"cpabc_item="+cpabc_current_calendar_item+""+String.fromCharCode(38),
                    }).done(function( html ) {
                        document.getElementById("abcservices").innerHTML = html;
                    });<?php } ?>
 }
 function force_updatedate() {
     abc_last_date = "";
     updatedate();
 }
 function updatedate()
 {<?php
     if (cpabc_get_option('enable_paypal',CPABC_APPOINTMENTS_DEFAULT_ENABLE_PAYPAL) == '3' || cpabc_get_option('enable_paypal',CPABC_APPOINTMENTS_DEFAULT_ENABLE_PAYPAL) == '7' ||  cpabc_get_option('enable_paypal',CPABC_APPOINTMENTS_DEFAULT_ENABLE_PAYPAL) == '4')
         $ajax_enabled_value = '1';
     else
         $ajax_enabled_value = cpabc_get_option('ajax_load_enabled',CPABC_APPOINTMENTS_ENABLE_AJAX_PRICE);
    if ($ajax_enabled_value != '0' && $ajax_enabled_value != '') { ?>
    if (document.getElementById("selDaycal"+cpabc_current_calendar_item ).value == '')
       document.getElementById("abccost").innerHTML = '';
    if (document.getElementById("selDaycal"+cpabc_current_calendar_item ).value != '')
    {
        if (document.getElementById("selDaycal"+cpabc_current_calendar_item ).value != abc_last_date)
        {
            document.getElementById("abccost").innerHTML = '';
            abc_last_date = document.getElementById("selDaycal"+cpabc_current_calendar_item ).value;
            var services = "";
            try { services = document.getElementById("abcservicesfield").options[document.getElementById("abcservicesfield").options.selectedIndex].value; } catch (e) {}
            <?php if ($qant_value != '0' && $qant_value != '') { ?>var adults = document.getElementById("abc_capacity_a").options.selectedIndex;<?php } else { ?>var adults = 1;<?php } ?>
            <?php if ($qant_value_two != '0' && $qant_value_two != '') { ?>var students = document.getElementById("abc_capacity_s").options.selectedIndex;<?php } else { ?>var students = 0;<?php } ?>
            if ((adults + students) == 0)
            {
                 document.getElementById("abc_capacity_a").options.selectedIndex = 1;
                 adults = 1;
            }
            abc_cost = '';
            $dexQuery = jQuery.noConflict();
            var coupon = ''; <?php if (count($codes)) echo 'coupon = $dexQuery("#abccouponcode").val();'; ?>
            var xparams = {
                      type: "GET",
                      url: "<?php echo cpabc_appointment_get_site_url(); ?>/?dex_abc=getcost"+String.fromCharCode(38)
                      +"inAdmin=1"+String.fromCharCode(38)
                      +"cpabc_item="+cpabc_current_calendar_item+""+String.fromCharCode(38)
                      +"selDaycal"+cpabc_current_calendar_item+"="+abc_last_date+""+String.fromCharCode(38)<?php if ($qant_value != '0' && $qant_value != '') { ?>+"abc_capacity="+(adults+students)+String.fromCharCode(38)<?php } ?><?php if ($qant_value != '0' && $qant_value != '') { ?>+"abc_capacity_a="+adults+String.fromCharCode(38)<?php } ?><?php if ($qant_value_two != '0' && $qant_value_two != '') { ?> +"abc_capacity_s="+students+String.fromCharCode(38)<?php } ?><?php if ($cpabc_buffer != '') { ?>+"services="+services+""+String.fromCharCode(38)<?php } ?>+"cp="+coupon,
                    };
            if (cpabc_load_sync)
            {
                xparams.async = false;
                html = $dexQuery.ajax(xparams).responseText;
                document.getElementById("abccost").innerHTML = '';
                abc_cost = html;
                $dexQuery("#abccost").append('<b><?php _e("Cost"); ?>:</b> <?php echo cpabc_get_option('currency', CPABC_APPOINTMENTS_DEFAULT_CURRENCY); ?> '+html);
            }
            else
                $dexQuery.ajax(xparams).done(function( html ) {
                        document.getElementById("abccost").innerHTML = '';
                        abc_cost = html;
                        $dexQuery("#abccost").append('<b><?php _e("Cost"); ?>:</b> <?php echo cpabc_get_option('currency', CPABC_APPOINTMENTS_DEFAULT_CURRENCY); ?> '+html);
                    });
        }
    }
    else abc_last_date = ""; <?php } ?>
 }
 </script><!--/noptimize-->
    <?php
    $current_user = wp_get_current_user();
    define('CPABC_AUTH_INCLUDE', true);
    if (get_option('CPABC_APPOINTMENTS_DEFAULT_USE_EDITOR',"1") != "1")
    {
        @include dirname( __FILE__ ) . '/cpabc_internal.inc.php';
        if (!CPABC_APPOINTMENTS_DEFAULT_DEFER_SCRIPTS_LOADING) {
        ?>
        <?php $plugin_url = plugins_url('', __FILE__); ?>
<script type='text/javascript' src='<?php echo $plugin_url.'/../../../wp-includes/js/jquery/jquery.js'; ?>'></script>
<script type='text/javascript' src='<?php echo $plugin_url.'/../../../wp-includes/js/jquery/ui/core.min.js'; ?>'></script>
<script type='text/javascript' src='<?php echo $plugin_url.'/../../../wp-includes/js/jquery/ui/datepicker.min.js'; ?>'></script>
<script type='text/javascript' src='<?php echo $plugin_url.'/../../../wp-includes/js/jquery/ui/widget.min.js'; ?>'></script>
<script type='text/javascript' src='<?php echo $plugin_url.'/../../../wp-includes/js/jquery/ui/position.min.js'; ?>'></script>
<script type='text/javascript' src='<?php echo $plugin_url.'/../../../wp-includes/js/jquery/ui/tooltip.min.js'; ?>'></script>
<script type='text/javascript' src='<?php echo plugins_url('js/jQuery.stringify.js', __FILE__); ?>'></script>
<script type='text/javascript' src='<?php echo plugins_url('js/jquery.validate.js', __FILE__); ?>'></script>
<script type='text/javascript'>
/* <![CDATA[ */
var cp_contactformpp_fbuilder_config = {"obj":"{\"pub\":true,\"messages\": {\n    \t                \t\"required\": \"This field is required.\",\n    \t                \t\"email\": \"Please enter a valid email address.\",\n    \t                \t\"datemmddyyyy\": \"Please enter a valid date with this format(mm\/dd\/yyyy)\",\n    \t                \t\"dateddmmyyyy\": \"Please enter a valid date with this format(dd\/mm\/yyyy)\",\n    \t                \t\"number\": \"Please enter a valid number.\",\n    \t                \t\"digits\": \"Please enter only digits.\",\n    \t                \t\"max\": \"Please enter a value less than or equal to {0}.\",\n    \t                \t\"min\": \"Please enter a value greater than or equal to {0}.\",\"previous\": \"Previous\",\"next\": \"Next.\"\n    \t                }}"};
/* ]]> */
</script>
<script type='text/javascript' src='<?php echo plugins_url('js/fbuilder-loader-public.php', __FILE__); ?>'></script>
        <?php
        }
    }
    else
        @include dirname( __FILE__ ) . '/cpabc_scheduler.inc.php';
}


function cpabc_appointments_show_booking_form($id = "")
{
    if ($id != '')
        define ('CPABC_CALENDAR_FIXED_ID',$id);
    define('CPABC_AUTH_INCLUDE', true);
    cpabc_appointments_get_public_form(false);
}

/* Code for the admin area */

if ( is_admin() ) {
    add_action('media_buttons', 'set_cpabc_apps_insert_button', 100);
    add_action('admin_enqueue_scripts', 'set_cpabc_apps_insert_adminScripts', 1);
    add_action('admin_menu', 'cpabc_appointments_admin_menu');
    add_action('enqueue_block_editor_assets', 'cpabc_appointments_gutenberg_block' );
    add_action('wp_loaded', 'cpabc_data_management_loaded' );

    $plugin = plugin_basename(__FILE__);
    add_filter("plugin_action_links_".$plugin, 'cpabc_customAdjustmentsLink');
    add_filter("plugin_action_links_".$plugin, 'cpabc_settingsLink');
    add_filter("plugin_action_links_".$plugin, 'cpabc_helpLink');

    function cpabc_appointments_admin_menu() {
        add_options_page('Appointment Booking Calendar Options', 'Appointment Booking Calendar', 'manage_options', 'cpabc_appointments', 'cpabc_appointments_html_post_page' );
        add_menu_page( 'Appointment Booking Calendar Options', 'Appointment Booking Calendar', 'read', 'cpabc_appointments', 'cpabc_appointments_html_post_page' );
    }
}
else
{
    add_shortcode( 'CPABC_APPOINTMENT_CALENDAR', 'cpabc_appointments_filter_content' );
    add_shortcode( 'CPABC_APPOINTMENT_CALENDAR_READ_ONLY', 'cpabc_appointments_filter_content_read_only' );
    add_shortcode( 'CPABC_APPOINTMENT_CALENDAR_CURRENT_USER_BOOKINGS', 'cpabc_appointments_filter_my_bookings' );
    add_shortcode( 'CPABC_APPOINTMENT_CALENDAR_MY_CAL_BOOKINGS', 'cpabc_appointments_filter_my_cal_bookings' );
    add_shortcode( 'CPABC_EDIT_CALENDAR', 'cpabc_appointments_filter_edit' );
    add_shortcode( 'CPABC_APPOINTMENT_LIST', 'cpabc_appointments_filter_list' );
    add_shortcode( 'CPABC_APPOINTMENT_LIST_QUERY', 'cpabc_appointments_filter_list_query' );
    add_shortcode( 'CPABC_APPOINTMENT_MYAPPS', 'cpabc_appointments_filter_mylist' );
}


function cpabc_appointments_gutenberg_block() {
    wp_enqueue_script( 'cpabc_gutenberg_editor', plugins_url('/js/block.js', __FILE__));
}


function cpabc_settingsLink($links) {
    $settings_link = '<a href="options-general.php?page=cpabc_appointments">'.__('Settings','cpabc').'</a>';
	array_unshift($links, $settings_link);
	return $links;
}


function cpabc_helpLink($links) {
    $help_link = '<a href="http://wordpress.dwbooster.com/calendars/appointment-booking-calendar">'.__('Help','cpabc').'</a>';
	array_unshift($links, $help_link);
	return $links;
}

function cpabc_customAdjustmentsLink($links) {
    $customAdjustments_link = '<a href="http://wordpress.dwbooster.com/contact-us">'.__('Request custom changes','cpabc').'</a>';
	array_unshift($links, $customAdjustments_link);
	return $links;
}

function cpabc_appointments_html_post_page() {
    global $wpdb;
    if ((isset($_GET["cal"]) && $_GET["cal"] != '') || ( @$_GET["cal"] == '0' || @$_GET["pwizard"] == '1'))
    {
        if (isset($_GET["editk"]) && $_GET["editk"] == '1')
            @include_once dirname( __FILE__ ) . '/cp_admin_int_edition.inc.php';
        else if (isset($_GET["list"]) && $_GET["list"] == '1')
            @include_once dirname( __FILE__ ) . '/cpabc_appointments_admin_int_bookings_list.inc.php';
        else if (isset($_GET["calschedule"]) && $_GET["calschedule"] == '1')
            @include_once dirname( __FILE__ ) . '/mv/calendar_schedule.inc.php';         
        else if (@$_GET["pwizard"] == '1')
            @include_once dirname( __FILE__ ) . '/cpabc_publish_wizzard.inc.php';
        else if (isset($_GET["addbk"]) && $_GET["addbk"] == '1')
            @include_once dirname( __FILE__ ) . '/cpabc_appointments_admin_addbk.inc.php';
        else if (isset($_GET["edit"]) && $_GET["edit"] != '')
            @include_once dirname( __FILE__ ) . '/cpabc_appointments_admin_int_edit_booking.inc.php';
        else
            @include_once dirname( __FILE__ ) . '/cpabc_appointments_admin_int.inc.php';
    }
    else
        @include_once dirname( __FILE__ ) . '/cpabc_appointments_admin_int_calendar_list.inc.php';
}

function set_cpabc_apps_insert_button() {
    global $wpdb;
    if (@$_GET["page"] == 'uxbuilder') return;
    $options = '';
    $calendars = $wpdb->get_results( 'SELECT * FROM '.$wpdb->prefix.CPABC_APPOINTMENTS_CONFIG_TABLE_NAME_NO_PREFIX);
    foreach($calendars as $item)
        $options .= '<option value="'.$item->id.'">'.$item->uname.'</option>';

    if (!defined('ELEMENTOR_MENUS_VERSION') || @$_GET["action"] != 'elementor')   
        wp_enqueue_style('wp-jquery-ui-dialog');
    wp_enqueue_script('jquery-ui-dialog');
    ?>
    <script type="text/javascript">
      var cpabc_appointments_fpanel = function($){
        var cpabc_counter = 0;
      	function loadWindow(){
      	    cpabc_counter++;
      		$(' <div title="Appointment Booking Calendar"><div style="padding:20px;">'+
      		   'Select Calendar:<br /><select id="cpabc_calendar_sel'+cpabc_counter+'" name="cpabc_calendar_sel'+cpabc_counter+'"><?php echo $options; ?></select>'+
      		   '</div></div>'
      		  ).dialog({
      			dialogClass: 'wp-dialog',
                  modal: true,
                  closeOnEscape: true,
                  buttons: [
                      {text: "Insert", click: function() {
      						if(send_to_editor){
      							var id = $('#cpabc_calendar_sel'+cpabc_counter)[0].options[$('#cpabc_calendar_sel'+cpabc_counter)[0].options.selectedIndex].value;
                                send_to_editor('[CPABC_APPOINTMENT_CALENDAR calendar="'+id+'"]');
      						}
      						$(this).dialog("close");
      				}}
                  ]
              });
      	}
      	var obj = {};
      	obj.open = loadWindow;
      	return obj;
      }(jQuery);
     </script>
    <?php
        if (@$_GET["action"] == 'elementor')
            print '<a href="javascript:send_to_editor(\'[CPABC_APPOINTMENT_CALENDAR calendar=&quot;1&quot;]\');" title="'.__('Insert Appointment Booking Calendar','cpabc').'"><img hspace="5" src="'.plugins_url('/images/cpabc_apps.gif', __FILE__).'" alt="'.__('Insert Appointment Booking Calendar','cpabc').'" /></a>';
        else  
            print '<a href="javascript:cpabc_appointments_fpanel.open()" title="'.__('Insert Appointment Booking Calendar','cpabc').'"><img hspace="5" src="'.plugins_url('/images/cpabc_apps.gif', __FILE__).'" alt="'.__('Insert  Appointment Booking Calendar','cpabc').'" /></a>';
}

function set_cpabc_apps_insert_adminScripts($hook) {
    if (isset($_GET["cal"]) && $_GET["cal"] != '' && !isset($_GET["addbk"]) && isset($_GET["page"]) && $_GET["page"] == 'cpabc_appointments')
    {
        if (get_option('CPABC_APPOINTMENTS_DEFAULT_USE_EDITOR',"1") != "1")
        {
            wp_deregister_script('query-stringify');
            wp_register_script('query-stringify', plugins_url('/js/jQuery.stringify.js', __FILE__));
            if (CPABC_APPOINTMENTS_ACTIVATECC) wp_enqueue_script( 'cp_apc_buikder_script_caret', plugins_url('/js/jquery.caret.js', __FILE__),array("jquery") );
            wp_enqueue_script( 'cp_contactformpp_buikder_script', get_site_url( get_current_blog_id() ).'?cp_abc_resources=admin',array("jquery","jquery-ui-core","jquery-ui-sortable","jquery-ui-tabs","jquery-ui-droppable","jquery-ui-button","jquery-ui-datepicker","query-stringify") );
        }
        else
        {
            wp_enqueue_script( 'jquery' );
            wp_enqueue_script( 'jquery-ui-core' );
            wp_enqueue_script( 'jquery-ui-datepicker' );
        }
        if (isset($_GET["calschedule"]) && $_GET["calschedule"] == '1')
            wp_enqueue_script( 'jquery-ui-dialog' );
        wp_enqueue_script( 'tinymce_js', includes_url( 'js/tinymce/' ) . 'wp-tinymce.php', array( 'jquery' ), false, true );
        wp_enqueue_style('jquery-style', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css');        
    }
    
    if (isset($_GET["addbk"]) && $_GET["addbk"] == '1' && isset($_GET["page"]) && $_GET["page"] == 'cpabc_appointments')
    {
        wp_enqueue_script( 'cpabc_repeat', plugins_url('js/repeat.js', __FILE__), array( 'jquery', 'jquery-ui-core', 'jquery-ui-datepicker' ));
        wp_enqueue_script( 'cpabc_rrule', plugins_url('js/rrule.js', __FILE__), array( 'jquery', 'jquery-ui-core', 'jquery-ui-datepicker' ) );
        wp_enqueue_style('jquery-style', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css');
    }  
    
    if( 'post.php' != $hook  && 'post-new.php' != $hook )
        return;
}

function cpabc_export_iCal() {
    global $wpdb;
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=events".date("Y-M-D_H.i.s").".ics");

    define('CPABC_CAL_TIME_ZONE_MODIFY',get_option('CPABC_CAL_TIME_ZONE_MODIFY_SET'," +2 hours"));
    define('CPABC_CAL_TIME_SLOT_SIZE'," +".get_option('CPABC_CAL_TIME_SLOT_SIZE_SET',"15")." minutes");

/**    echo "BEGIN:VCALENDAR\n";
    echo "PRODID:-//CodePeople//Appointment Booking Calendar for WordPress//EN\n";
    echo "VERSION:2.0\n";
    echo "CALSCALE:GREGORIAN\n";
    echo "METHOD:PUBLISH\n";
    echo "X-WR-CALNAME:Bookings\n";
    echo "X-WR-TIMEZONE:Europe/London\n";
    echo "BEGIN:VTIMEZONE\n";
    echo "TZID:Europe/Stockholm\n";
    echo "X-LIC-LOCATION:Europe/London\n";
    echo "BEGIN:DAYLIGHT\n";
    echo "TZOFFSETFROM:+0000\n";
    echo "TZOFFSETTO:+0100\n";
    echo "TZNAME:CEST\n";
    echo "DTSTART:19700329T020000\n";
    echo "RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU\n";
    echo "END:DAYLIGHT\n";
    echo "BEGIN:STANDARD\n";
    echo "TZOFFSETFROM:+0100\n";
    echo "TZOFFSETTO:+0000\n";
    echo "TZNAME:CET\n";
    echo "DTSTART:19701025T030000\n";
    echo "RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU\n";
    echo "END:STANDARD\n";
    echo "END:VTIMEZONE\n";

*/
    echo "BEGIN:VCALENDAR\n";
    echo "PRODID:-//CodePeople//Appointment Booking Calendar for WordPress//EN\n";
    echo "VERSION:2.0\n";

    // note: exclude who_added == -1 because are events already imported via iCal
    $events = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME." WHERE (who_added<>'-1') AND ((is_cancelled is Null) OR (is_cancelled<>'1')) AND appointment_calendar_id=".intval($_GET["id"])." ORDER BY datatime ASC" );
    foreach ($events as $event)
    {
        if (CPABC_APPOINTMENTS_ICAL_OBSERVE_DAYLIGHT)
        {
            $full_date = gmdate("Ymd",strtotime($event->datatime.CPABC_CAL_TIME_ZONE_MODIFY));
            $year = substr($full_date,0,4);
            if (strtoupper(CPABC_APPOINTMENTS_ICAL_DAYLIGHT_ZONE) == 'EUROPE')
            {
                $dst_start = strtotime('last Sunday GMT', strtotime("1 April $year GMT"));
                $dst_stop = strtotime('last Sunday GMT', strtotime("1 November $year GMT"));
            } else { // USA
                $dst_start = strtotime('first Sunday GMT', strtotime("1 April $year GMT"));
                $dst_stop = strtotime('last Sunday GMT', strtotime("1 November $year GMT"));
            }
            if ($full_date >= gmdate("Ymd",$dst_start) && $full_date < gmdate("Ymd",$dst_stop))
                $event->datatime = date("Y-m-d H:i",strtotime($event->datatime." -1 hour"));
        }

        echo "BEGIN:VEVENT\n";
        echo "DTSTART:".gmdate("Ymd",strtotime($event->datatime.CPABC_CAL_TIME_ZONE_MODIFY))."T".gmdate("His",strtotime($event->datatime.CPABC_CAL_TIME_ZONE_MODIFY))."Z\n";
        echo "DTEND:".gmdate("Ymd",strtotime($event->datatime.CPABC_CAL_TIME_ZONE_MODIFY.CPABC_CAL_TIME_SLOT_SIZE))."T".gmdate("His",strtotime($event->datatime.CPABC_CAL_TIME_ZONE_MODIFY.CPABC_CAL_TIME_SLOT_SIZE))."Z\n";
        //echo "DTSTAMP:".date("Ymd",strtotime($event->datatime.CPABC_CAL_TIME_ZONE_MODIFY))."T".date("His",strtotime($event->datatime.CPABC_CAL_TIME_ZONE_MODIFY))."Z\n";
        echo "DTSTAMP:".gmdate("Ymd")."T".gmdate("His")."Z\n";
        echo "UID:uid".$event->id."@".$_SERVER["SERVER_NAME"]."\n";
        //echo "CREATED:".date("Ymd",strtotime($event->datatime.CPABC_CAL_TIME_ZONE_MODIFY))."T".date("His",strtotime($event->datatime.CPABC_CAL_TIME_ZONE_MODIFY))."Z\n";
        echo "DESCRIPTION:".str_replace("<br>",'\n',str_replace("<br />",'\n',str_replace("\r",'',str_replace("\n",'\n',$event->description)) ))."\n";
        //echo "LAST-MODIFIED:".date("Ymd",strtotime($event->datatime.CPABC_CAL_TIME_ZONE_MODIFY))."T".date("His",strtotime($event->datatime.CPABC_CAL_TIME_ZONE_MODIFY))."Z\n";
        echo "LAST-MODIFIED:".gmdate("Ymd")."T".gmdate("His")."Z\n";
        echo "LOCATION:\n";
        echo "SEQUENCE:0\n";
        echo "STATUS:CONFIRMED\n";
        echo "SUMMARY:Booking from ".str_replace("\n",'\n',$event->title)."\n";
        echo "TRANSP:OPAQUE\n";
        echo "END:VEVENT\n";


    }
    echo 'END:VCALENDAR';
    exit;
}


/* hook for checking posted data for the admin area */


add_action( 'init', 'cpabc_appointments_check_posted_data', 11 );

function cpabc_appointments_check_posted_data()
{
    global $wpdb;

    if (get_option('CPABC_ENABLE_VALIDATIONS',"1") == '2')
      cpabc_update_verifieds();

	if( isset( $_REQUEST[ 'cp_abc_resources' ] ) )
	{
		if( $_REQUEST[ 'cp_abc_resources' ] == 'admin' )
		{
			require_once dirname( __FILE__ ).'/js/fbuilder-loader-admin.php';
		}
		else
		{
			require_once dirname( __FILE__ ).'/js/fbuilder-loader-public.php';
		}
		exit;
	}

    if (isset($_GET["dex_abc"]) && $_GET["dex_abc"] == 'getcost')
        foreach($_GET as $item => $value)
        {
            $_POST[$item] = $value;
        }

    if (isset($_GET["dex_abc"]) && $_GET["dex_abc"] == 'getstructure')
    {
        // replace this to load it encoded as done in the "cpabc_internal" file
        if (!defined('CP_CALENDAR_ID') && isset($_GET["cpabc_item"]))
            define ('CP_CALENDAR_ID', intval($_GET["cpabc_item"]));
        echo cpabc_appointment_cleanJSON(cpabc_get_option('form_structure', CPABC_APPOINTMENTS_DEFAULT_form_structure));
        exit;
    }

    if (isset($_GET["dex_abc"]) && $_GET["dex_abc"] == 'getservices')
    {
        if (!defined('CP_CALENDAR_ID') && isset($_GET["cpabc_item"]))
            define ('CP_CALENDAR_ID', intval($_GET["cpabc_item"]));
        $cpabc_buffer = "";
        $services = explode("\n",cpabc_get_option('cp_cal_checkboxes', CPABC_APPOINTMENTS_DEFAULT_CP_CAL_CHECKBOXES));
        foreach ($services as $item)
            if (trim($item) != '')
                $cpabc_buffer .= '<option value="'.esc_attr(trim($item)).'">'.trim(substr($item,strpos($item,"|")+1)).'</option>';
        if ($cpabc_buffer != '')
        {
            _e('Service','cpabc');
            echo ':<br /><select name="services" id="abcservicesfield" onchange="force_updatedate();">'.$cpabc_buffer.'</select><br /><br />';
        }
        exit;
    }


    cpabc_appointments_check_reminders();

    if(isset($_GET) && array_key_exists('cpabc_app',$_GET)) {
        if ( $_GET["cpabc_app"] == 'calfeed' )
        {
            if ($_GET["id"] != '' && substr(md5($_GET["id"].$_SERVER["DOCUMENT_ROOT"]),0,10) == $_GET["verify"])
                cpabc_export_iCal();
            else
            {
                echo 'Access denied - verify value is not correct.';
                exit;
            }
        }

        if ($_GET["cpabc_app"] == 'captcha')
        {
            @include_once dirname( __FILE__ ) . '/captcha/captcha.php';
            exit;
        }

        if ( $_GET["cpabc_app"] == 'cpabc_loadcoupons')
            cpabc_appointments_load_discount_codes();
    }

    if ((isset( $_GET['cpabc_appointments_csv'] ) || isset( $_GET['cpabc_appointments_csv_unused'] )) && is_admin() )
    {
        cpabc_appointments_export_csv();
        return;
    }

    if (isset($_GET["cpabc_c"]) && $_GET['cpabc_c'] == '1')
        cpabc_process_cancel_go_appointment();

    if (isset($_GET["cpabc_v"]) && $_GET['cpabc_v'] == '1')
        cpabc_process_validation_go_appointment();

    if (!defined('CP_CALENDAR_ID') && isset($_POST["cpabc_item"]))
        define ('CP_CALENDAR_ID', $_POST["cpabc_item"]);

    if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset( $_POST['cpabc_appointments_post_options'] ) && (is_admin() || cpabc_appointments_user_access_to(CP_CALENDAR_ID) ))
    {
        cpabc_appointments_save_options();
        return;
    }
    
    if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset( $_POST['CP_ABC_post_edition'] ) && is_admin() && current_user_can('edit_posts') )
    {
        cpabc_appointments_save_edition();
        return;
    }  
    
    if (isset($_GET["abc_verifydate"]) && $_GET['abc_verifydate'] != '')
    {

        $times =   explode(";",str_replace(",","-",$_GET["abc_verifydate"]));
        array_shift($times);
        foreach ($times as $itemtime) {
            $capacity = cpabc_get_slot_capacity(intval($_GET["cal"]),$itemtime);
            if ($capacity == '') $capacity = 0;
            $result = $wpdb->get_results( "SELECT SUM(quantity) as cantidad FROM ".CPABC_TDEAPP_CALENDAR_DATA_TABLE.
                  " WHERE appointment_calendar_id=".intval($_GET["cal"]).
                  " AND ((is_cancelled is Null) OR (is_cancelled<>'1')) AND datatime='".date("Y-m-d H:i:s", strtotime($itemtime))."'");
            if (intval($result[0]->cantidad)+intval($_GET["tobook"]) > $capacity)
            {
                echo 'failed';
                exit;
            }
        }

        if ($_GET["cp"] != '')
        {
            $codes = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_DISCOUNT_CODES_TABLE_NAME." WHERE ((dc_times>used) OR dc_times='0') AND code='".esc_sql(@$_GET["cp"])."' AND expires>='".date("Y-m-d")." 00:00:00' AND `cal_id`=".intval($_GET["cal"]));
            if (!count($codes))
            {
                echo 'wrongcoupon';
                exit;
            }
        }

        echo 'ok';
        exit;
     }

    if (@$_GET["abcc_authorize"] == '2')
        cpabc_process_authorize();

    if (!isset($_POST["dex_abc"])) {
        // if this isn't the expected post and isn't the captcha verification then nothing to do
	    if ( 'POST' != $_SERVER['REQUEST_METHOD'] || ! isset( $_POST['cpabc_appointments_post'] ) )
	    	if ( 'GET' != $_SERVER['REQUEST_METHOD'] || !isset( $_GET['hdcaptcha'] ) )
	    	    return;


        @session_start();

        if (!isset($_GET["hdcaptcha"]) || $_GET['hdcaptcha'] == '') $_GET['hdcaptcha'] = @$_POST['hdcaptcha'];
        if (
               !apply_filters( 'cpabc_valid_submission', true) ||
               (
                   (!is_admin() && cpabc_get_option('dexcv_enable_captcha', CPABC_TDEAPP_DEFAULT_dexcv_enable_captcha) != 'false') &&
                   ( (strtolower($_GET['hdcaptcha']) != strtolower($_SESSION['rand_code'])) ||
                     ($_SESSION['rand_code'] == '')
                   )
                   &&
                   ( (md5(strtolower($_GET['hdcaptcha'])) != ($_COOKIE['rand_code'])) ||
                     ($_COOKIE['rand_code'] == '')
                   )
               )
           )
        {
            $_SESSION['rand_code'] = '';
            echo 'captchafailed';
            exit;
        }

	    // if this isn't the real post (it was the captcha verification) then echo ok and exit
        if ( 'POST' != $_SERVER['REQUEST_METHOD'] || ! isset( $_POST['cpabc_appointments_post'] ) )
	    {
	        if (!isset($_GET["abcc"]))
	            return;
	        echo 'ok';
            exit;
	    }

        $_SESSION['rand_code'] = '';
    }
    $selectedCalendar = $_POST["cpabc_item"];

    if (is_admin() && $_POST["selMonthcal".$selectedCalendar] != '' && $_POST["freq"] != '10')
        $_POST["selDaycal".$selectedCalendar] .= $_POST["selMonthcal".$selectedCalendar];
    $_POST["dateAndTime"] =   explode(";",str_replace(",","-",$_POST["selDaycal".$selectedCalendar]));
    array_shift($_POST["dateAndTime"]);

    if ($_POST["tzonelistcal".$selectedCalendar] == '')
       $_POST["tzonelistcal".$selectedCalendar] = $_POST["selDaycal".$selectedCalendar];

    $_POST["dateAndTime_customer"] =   explode(";",str_replace(",","-",@$_POST["tzonelistcal".$selectedCalendar]));
    array_shift($_POST["dateAndTime_customer"]);

    $format = cpabc_appointments_getDateFormat();
    for($n=0;$n<count($_POST["dateAndTime"]); $n++)
    {
        $_POST["dateAndTime"][$n] = date("Y-m-d H:i:s",strtotime($_POST["dateAndTime"][$n]));
        $_POST["Date"][$n] = date($format,strtotime($_POST["dateAndTime"][$n]));

        $_POST["dateAndTime_customer"][$n] = date("Y-m-d H:i:s",strtotime(@$_POST["dateAndTime_customer"][$n]));
        $_POST["Date_customer"][$n] = date($format,strtotime($_POST["dateAndTime_customer"][$n]));
    }

    $services_formatted = explode("|",@$_POST["services"]);

    {
        $price = explode(";",cpabc_get_option('request_cost', CPABC_APPOINTMENTS_DEFAULT_COST));
        foreach ($price as $item => $value)
           $price[$item] = trim(str_replace(',','', str_replace(CPABC_APPOINTMENTS_DEFAULT_CURRENCY_SYMBOL,'',
                                                     str_replace(CPABC_APPOINTMENTS_GBP_CURRENCY_SYMBOL,'',
                                                     str_replace(CPABC_APPOINTMENTS_EUR_CURRENCY_SYMBOL_A, '',
                                                     str_replace(CPABC_APPOINTMENTS_EUR_CURRENCY_SYMBOL_B,'', $value )))) ));
        if (isset($price[count($_POST["dateAndTime"])-1]))
            $price = $price[count($_POST["dateAndTime"])-1];
        else
            $price = $price[0] * count($_POST["dateAndTime"]);

        $qant_value_two = cpabc_get_option('quantity_field_two','0');
        if ($qant_value_two != '0' && $qant_value_two != '') {
            $price2 = explode(";",cpabc_get_option('request_cost_st', CPABC_APPOINTMENTS_DEFAULT_COST));
            foreach ($price2 as $item => $value)
               $price2[$item] = trim(str_replace(',','', str_replace(CPABC_APPOINTMENTS_DEFAULT_CURRENCY_SYMBOL,'',
                                                        str_replace(CPABC_APPOINTMENTS_GBP_CURRENCY_SYMBOL,'',
                                                        str_replace(CPABC_APPOINTMENTS_EUR_CURRENCY_SYMBOL_A, '',
                                                        str_replace(CPABC_APPOINTMENTS_EUR_CURRENCY_SYMBOL_B,'', $value )))) ));
            if (isset($price2[count($_POST["dateAndTime"])-1]))
                $price2 = $price2[count($_POST["dateAndTime"])-1];
            else
                $price2 = $price2[0] * count($_POST["dateAndTime"]);
        } else {
            $price2 = 0;
        }
    }

    $_POST["abc_capacity"] = intval( (@$_POST["abc_capacity"]!=''?$_POST["abc_capacity"]:'1') );
    $_POST["abc_capacity_a"] = intval( (@$_POST["abc_capacity_a"]!=''?$_POST["abc_capacity_a"]:'1') );
    $_POST["abc_capacity_s"] = intval( (@$_POST["abc_capacity_s"]!=''?$_POST["abc_capacity_s"]:'0') );

    $price = round($price * $_POST["abc_capacity_a"] + $price2 * $_POST["abc_capacity_s"], 2);

    if (isset($_GET["services"]) && $_GET["services"] != '')
        $_POST["services"] = $_GET["services"];

    if (@$_POST["services"])
    {
        $price += trim($services_formatted[0]) * count($_POST["dateAndTime"]);
        $price2 += trim($services_formatted[0]) * count($_POST["dateAndTime"]);
    }

    $price_updated = $price;
    $last_vs = '0';
    for ($k=CPABC_DISCOUNT_FIELDS; $k>=1; $k--) {
        $vs = cpabc_get_option('discountslots'.$k, '0');
        $vp = cpabc_get_option('discountvalue'.$k, '0');
        if (intval($vs) <= count($_POST["dateAndTime"]) && $vp != '0' && $vp != '' && $vs != '' && intval($last_vs) < intval($vs))
        {
            $last_vs = $vs;
            $price_updated = round( $price - $price*$vp/100, 2);
            $k = 0;
        }
    }
    $price = $price_updated;

    // check discount codes
    //-------------------------------------------------
    if (isset($_POST["dex_abc"]) && isset($_GET["cp"]))
        $_POST["couponcode"] = $_GET["cp"];    
    $discount_note = "";
    $coupon = false;
    $codes = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_DISCOUNT_CODES_TABLE_NAME." WHERE ((dc_times>used) OR dc_times='0') AND code='".esc_sql(@$_POST["couponcode"])."' AND expires>='".date("Y-m-d")." 00:00:00' AND `cal_id`=".CP_CALENDAR_ID);
    if (count($codes))
    {
        $coupon = $codes[0];
        if ($coupon->availability==1)
        {
            $price = number_format (floatval ($price) - $coupon->discount,2);
            $discount_note = " (".cpabc_get_option('currency', CP_CONTACTFORMPP_DEFAULT_CURRENCY)." ".$coupon->discount." discount applied)";
        }
        else
        {
            $price = number_format (floatval ($price) - $price*$coupon->discount/100,2);
            $discount_note = " (".$coupon->discount."% discount applied)";
        }
        //$price = number_format (floatval ($price) - $price*$coupon->discount/100,2);
        //$discount_note = " (".$coupon->discount."% discount applied)";
    }    
    
    if (isset($_POST["dex_abc"]))
    {
        echo number_format($price, 2);exit;
    }

    $params = array();
    $params["UTIMEZONE"] = @$_POST["cpabc_appointments_utime"];
    $params["QUANTITY"] = @$_POST["abc_capacity"];
    $params["ADULTS"] = @$_POST["abc_capacity_a"];
    $params["JUNIORS"] = @$_POST["abc_capacity_s"];
    $params["SERVICES"] = (@$_POST["services"]?"\nService: ".trim($services_formatted[1]):"");

    // get form info
    //---------------------------
    if (get_option('CPABC_APPOINTMENTS_DEFAULT_USE_EDITOR',"1") != "1")
    {
        // get form info
        //---------------------------
        $form_data = json_decode(cpabc_appointment_cleanJSON(cpabc_get_option('form_structure', CPABC_APPOINTMENTS_DEFAULT_form_structure)));
        $fields = array();
        foreach ($form_data[0] as $item)
        {
            $fields[$item->name] = $item->title;

            if ($item->ftype == 'fPhone') // join fields for phone fields
            {
                $_POST[$item->name] = '';
                for($i=0; $i<=substr_count($item->dformat," "); $i++)
                    $_POST[$item->name] .= ($_POST[$item->name."_".$i]!=''?($i==0?'':'-').$_POST[$item->name."_".$i]:'');
            }
            else if (CPABC_APPOINTMENTS_IDENTIFY_PRICES && ($item->ftype == 'fcheck' || $item->ftype == 'fradio' || $item->ftype == 'fdropdown'))
            {
                $values = ( is_array($_POST[$item->name]) ? $_POST[$item->name] : array($_POST[$item->name]) );            
                foreach ($values as $value) 
                {
                    $value = str_replace(':',' ',$value);
                    $value = str_replace('/',' ',$value);                
                    $value = str_replace('(',' ',$value);
                    $value = str_replace('"',' ',$value);
                    $value = str_replace('s',' ',$value);
                    $matches_eur_a = array();
                    preg_match_all ('/([0-9,]+(\.[0-9]{2})?)/', $value, $matches_eur_a);                        
                    $matches = $matches_eur_a[0]; 
                               
                    foreach ($matches as $item)
                    {
                        $item = trim(str_replace(',','', str_replace(CPABC_APPOINTMENTS_DEFAULT_CURRENCY_SYMBOL,'', 
                                                         str_replace(CPABC_APPOINTMENTS_GBP_CURRENCY_SYMBOL,'', 
                                                         str_replace(CPABC_APPOINTMENTS_EUR_CURRENCY_SYMBOL_A, '',
                                                         str_replace(CPABC_APPOINTMENTS_EUR_CURRENCY_SYMBOL_B,'', $item )))) ));                                               
                        if (is_numeric($item)) {                        
                            $nindex = strpos($value, " ".$item);                        
                            $nindex2 = substr($value,0,strlen($item));                        
                            if ($nindex === false && $nindex2 != $item) // exclude items with a blank space before it
                            {
                                $nindexdiscount = strpos($value, "-$".$item);
                                if ($nindexdiscount === false)
                                    $price += $item;
                                else  
                                    $price -= $item;    
                            } else {
                                if ($nindex2 == $item)
                                    $value = substr($value,strlen($item));
                                else    
                                    $value = str_replace(" ".$item,"",$value);
                            }  
                        }
                    }
                }
            }
        }

        // grab posted data
        //---------------------------
        $buffer = "";
        $excluded_field = explode (",",@$_POST["form_structure_hidden"]);
        foreach ($_POST as $item => $value)
            if (isset($fields[$item]) && !in_array($item, $excluded_field) )
            {
                $buffer .= $fields[$item] . ": ". (is_array($value)?(implode(", ",$value)):($value)) . "\n\n";
                $params[$item] = $value;
            }
            
        if ($buffer == '')
        {
            echo '<strong>Error:</strong> No booking data received. <strong>Please be sure that the form contains at least one field</strong>. Go back and try again.';
            exit;
        }            

        require_once(ABSPATH . "wp-admin" . '/includes/file.php');
        foreach ($_FILES as $item => $value)
        {
            //$item = str_replace( $sequence,'',$item );
	    	if ( isset( $fields[ $item ] ) )
            {
	    		$files_names_arr = array();
	    		$files_links_arr = array();
	    		$files_urls_arr  = array();
	    		for( $f = 0; $f < count( $value[ 'name' ] ); $f++ )
	    		{
	    			if( !empty( $value[ 'name' ][ $f ] ) )
	    			{
	    				$uploaded_file = array(
	    					'name' 		=> $value[ 'name' ][ $f ],
	    					'type' 		=> $value[ 'type' ][ $f ],
	    					'tmp_name' 	=> $value[ 'tmp_name' ][ $f ],
	    					'error' 	=> $value[ 'error' ][ $f ],
	    					'size' 		=> $value[ 'size' ][ $f ],
	    				);
	    				if( cpabc_appointments_check_upload( $uploaded_file ) )
	    				{
	    					$movefile = wp_handle_upload( $uploaded_file, array( 'test_form' => false ) );
	    					if ( empty( $movefile[ 'error' ] ) )
	    					{
	    						$files_links_arr[] = $params[ $item."_link" ][ $f ] = $movefile["file"];
	    						$files_urls_arr[]  = $params[ $item."_url" ][ $f ] = $movefile["url"];
	    						$files_names_arr[] = $uploaded_file[ 'name' ];

      							/**
      							 * Action called when the file is uploaded, the file's data is passed as parameter
      							 */
      							do_action( 'cpabc_file_uploaded', $movefile );
	    					} //else echo $movefile[ 'error' ];
	    				}
	    			}
	    		}
	    		$joinned_files_names = implode( ", ", $files_names_arr );
	    		$buffer .= $fields[ $item ] . ": ". $joinned_files_names . "\n\n";
	    		$params[ $item ] = $joinned_files_names;
	    		//$params[ $item."_links"] = implode( ",",  $files_links_arr );
	    		//$params[ $item."_urls"] = implode( ",",  $files_urls_arr );
	    	}
	    }

        $buffer_A = trim($buffer);
        $buffer_A .= (@$_POST["services"]?"\nService: ".trim($services_formatted[1])."\n\n":"");

        $to = cpabc_get_option('cu_user_email_field', CPABC_APPOINTMENTS_DEFAULT_cu_user_email_field);
    }
    else
    {

        $params["NAME"] = $_POST["name"];
        $params["EMAIL"] = $_POST["email"];
        $params["PHONE"] = $_POST["phone"];
        $params["COMMENTS"] = $_POST["question"];

        $buffer_A = $_POST["question"].(@$_POST["services"]?"\nService: ".trim($services_formatted[1]):"");
                                      //.($coupon?"\nCoupon code: ".$coupon->code.$discount_note:"");
        $to = "email";
    }

    if (CPABC_APPOINTMENTS_ACTIVATECC) {
        $added_cost = @$_POST[cpabc_get_option('paypal_price_field', '').$sequence];
        if (is_numeric($added_cost))
            $price += $added_cost;
        else
        {
            $matches_default = array();
            preg_match_all ('/(\\'.CPABC_APPOINTMENTS_DEFAULT_CURRENCY_SYMBOL.'[0-9,]+(\.[0-9]{2})?)/', $added_cost, $matches_default);
            $matches_gbp = array();
            preg_match_all ('/(\\'.CPABC_APPOINTMENTS_GBP_CURRENCY_SYMBOL.'[0-9,]+(\.[0-9]{2})?)/', $added_cost, $matches_gbp);
            $matches_eur_a = array();
            preg_match_all ('/(\\'.CPABC_APPOINTMENTS_EUR_CURRENCY_SYMBOL_A.'[0-9,]+(\.[0-9]{2})?)/', $added_cost, $matches_eur_a);
            $matches_eur_b = array();
            preg_match_all ('/(\\'.CPABC_APPOINTMENTS_EUR_CURRENCY_SYMBOL_B.'[0-9,]+(\.[0-9]{2})?)/', $added_cost, $matches_eur_b);
            $matches = array_merge($matches_default[0], $matches_gbp[0], $matches_eur_a[0], $matches_eur_b[0]);
            foreach ($matches as $item)
            {
                $item = trim(str_replace(',','', str_replace(CPABC_APPOINTMENTS_DEFAULT_CURRENCY_SYMBOL,'',
                                                 str_replace(CPABC_APPOINTMENTS_GBP_CURRENCY_SYMBOL,'',
                                                 str_replace(CPABC_APPOINTMENTS_EUR_CURRENCY_SYMBOL_A, '',
                                                 str_replace(CPABC_APPOINTMENTS_EUR_CURRENCY_SYMBOL_B,'', $item )))) ));
                if (is_numeric($item))
                    $price += $item;
            }
        }
    }


    $params["PRICE"] = number_format ($price, 2);
    $params["final_price"] = $price;
    $params["COUPONCODE"] = ($coupon?"\nCoupon code:".$coupon->code.$discount_note."\n":"");
    $params["coupon"] = ($coupon?$coupon->code:"");
    $buffer_A .= ($coupon?"\nCoupon code: ".$coupon->code.$discount_note:"");

    if (isset($_POST["bccf_payment_option_paypal"]) && $_POST["bccf_payment_option_paypal"] == '0')
        $params["payment_type"] = 'Other';
    else
        $params["payment_type"] = 'PayPal';


    $qant_value = cpabc_get_option('quantity_field','0');
    if ($qant_value != '0' && $qant_value != '') $buffer_A .= "\n".cpabc_get_option('quantity_field_label',CPABC_APPOINTMENTS_ENABLE_QUANTITY_FIELD_LABEL).": ".$_POST["abc_capacity_a"];
    $qant_value_two = cpabc_get_option('quantity_field_two','0');
    if ($qant_value_two != '0' && $qant_value_two != '') $buffer_A .= "\n".cpabc_get_option('quantity_field_two_label',CPABC_APPOINTMENTS_ENABLE_QUANTITY_FIELD_TWO_LABEL)." quantity: ".$_POST["abc_capacity_s"];


    // insert into database
    //---------------------------
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_TABLE_NAME, 'quantity', "VARCHAR(25) DEFAULT '1' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_TABLE_NAME, 'quantity_a', "VARCHAR(25) DEFAULT '1' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_TABLE_NAME, 'quantity_s', "VARCHAR(25) DEFAULT '1' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_TABLE_NAME, 'booked_time_customer', "VARCHAR(250) DEFAULT '1' NOT NULL");

    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_TABLE_NAME, 'who_added', "VARCHAR(50) DEFAULT '' NOT NULL");
    cpabc_appointments_add_field_verify($wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX, 'who_added', "VARCHAR(50) DEFAULT '' NOT NULL");
    cpabc_appointments_add_field_verify($wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX, 'who_edited', "VARCHAR(50) DEFAULT '' NOT NULL");
    cpabc_appointments_add_field_verify($wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX, 'who_cancelled', "VARCHAR(50) DEFAULT '' NOT NULL");
    cpabc_appointments_add_field_verify($wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX, 'is_cancelled', "VARCHAR(50) DEFAULT '0' NOT NULL");
    cpabc_appointments_add_field_verify($wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX, 'is_verified', "VARCHAR(10) DEFAULT '0' NOT NULL");
    cpabc_appointments_add_field_verify($wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX, 'verified_required', "VARCHAR(10) DEFAULT '0' NOT NULL");
    cpabc_appointments_add_field_verify($wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX, 'cancelled_reason', "TEXT");

	/**
	 * Action called before insert the data into database.
	 * To the function is passed an array with submitted data.
	 */
	do_action_ref_array( 'cpabc_process_data_before_insert', array(&$params) );


    if (date("Y",strtotime($_POST["dateAndTime"][0])) == "1970") // if this is spam, skip
        return;

    $current_user = wp_get_current_user();
    $timemysql = current_time('mysql');
    for ($n=0; $n<count($_POST["dateAndTime"]); $n++)
    {
        $params["DATE"] = trim( substr($_POST["Date"][$n], 0, strpos($_POST["Date"][$n],' ') ) );
        $params["TIME"] = trim( substr($_POST["Date"][$n], strpos($_POST["Date"][$n],' ') ) );
        $params["DATE_CUSTOMER"] = trim( substr($_POST["Date_customer"][$n], 0, strpos($_POST["Date_customer"][$n],' ') ) );
        $params["TIME_CUSTOMER"] = trim( substr($_POST["Date_customer"][$n], strpos($_POST["Date_customer"][$n],' ') ) );
        $rows_affected = $wpdb->insert( CPABC_APPOINTMENTS_TABLE_NAME, array( 'calendar' => $selectedCalendar,
                                                                        'time' => $timemysql,
                                                                        'booked_time' => $_POST["Date"][$n],
                                                                        'booked_time_customer' => $_POST["Date_customer"][$n],
                                                                        'booked_time_unformatted' => $_POST["dateAndTime"][$n],
                                                                        'name' => "".@$_POST["name"],
                                                                        'email' => "".@$_POST[$to],
                                                                        'phone' => "".@$_POST["phone"],
                                                                        'question' => $buffer_A,
                                                                        'quantity' => (isset($_POST["abc_capacity"])?$_POST["abc_capacity"]:1),
                                                                        'quantity_a' => (isset($_POST["abc_capacity_a"])?$_POST["abc_capacity_a"]:0),
                                                                        'quantity_s' => (isset($_POST["abc_capacity_s"])?$_POST["abc_capacity_s"]:0),
                                                                        'buffered_date' => serialize($params),
                                                                        'who_added' => $current_user->ID
                                                                         ) );
        if (!$rows_affected)
        {
            echo 'Error saving data! Please try again.';            
            $sql = "ALTER TABLE  `".$wpdb->prefix.CPABC_APPOINTMENTS_TABLE_NAME_NO_PREFIX."` ADD `booked_time_unformatted` text;"; $wpdb->query($sql);
            exit;
        }

        //$myrows = $wpdb->get_results( "SELECT MAX(id) as max_id FROM ".CPABC_APPOINTMENTS_TABLE_NAME );

 	    // save data here
        $item_number[] = $wpdb->insert_id;
    }


	// Call action for data processing
	//---------------------------------
	$params[ 'itemnumber' ] = $item_number[0];
	$params[ 'itemnumbers' ] = $item_number;
	$params[ 'useremail' ] = "".@$_POST[$to];
	$params[ 'formid' ] = $selectedCalendar;    
	$_SESSION[ 'cp_cff_form_data' ] = $item_number[0];
    $_SESSION[ 'cp_cff_form_data_all' ] = $item_number;
	/**
	 * Action called after inserted the data into database.
	 * To the function is passed an array with submitted data.
	 */
	do_action( 'cpabc_process_data', $params );


    $item_number = implode(";", $item_number);

    if (is_admin())
    {
        cpabc_process_ready_to_go_appointment($item_number, '');
        return;
    }
    
    $paypal_option = cpabc_get_option('enable_paypal',CPABC_APPOINTMENTS_DEFAULT_ENABLE_PAYPAL);
    $paypal_optional = (($paypal_option == '2') || ($paypal_option == '3') || ($paypal_option == '7') || ($paypal_option == '4'));

    if (($paypal_option == '3' && @$_POST["bccf_payment_option_paypal"] == '0') || $paypal_option == '7')
    {
        require_once dirname( __FILE__ ) . '/stripe-php-1.10.1/lib/Stripe.php';
        Stripe::setApiKey( cpabc_get_option('stripe_secretkey','') );

        // Get the credit card details submitted by the form
        $token = $_POST['stptok'];

        // Create the charge on Stripe's servers - this will charge the user's card
        try {
        $charge = Stripe_Charge::create(array(
          "amount" => $price * 100, // amount in cents, again
          "currency" => cpabc_get_option('currency', CPABC_APPOINTMENTS_DEFAULT_CURRENCY),
          "card" => $token,
          "description" => cpabc_get_option('paypal_product_name', CPABC_APPOINTMENTS_DEFAULT_PRODUCT_NAME)." - Item Number: ".$item_number)
        );
        } catch(Stripe_CardError $e) {
          // The card has been declined
          //echo 'Transaction failed. The card has been declined. Please <a href="javascript:window.history.back();">go back and try again</a>.';
          header("Location: ".cpabc_get_option('url_cancel', CPABC_APPOINTMENTS_DEFAULT_CANCEL_URL));
          exit;
        }
    }

    if (floatval($price) > 0 && cpabc_get_option('enable_paypal',CPABC_APPOINTMENTS_DEFAULT_ENABLE_PAYPAL) == '5')
    {
        try
        {
            require_once dirname(__FILE__) . "/mollie-api/src/Mollie/API/Autoloader.php";
            $mollie = new Mollie_API_Client;
            $mollie->setApiKey( cpabc_get_option('enable_mollie_id', '') );
            $order_id = $item_number;
            $payment = $mollie->payments->create(array(
		        "amount"       => $price,
		        "description"  => cpabc_get_option('paypal_product_name', CPABC_APPOINTMENTS_DEFAULT_PRODUCT_NAME).($services_formatted[1]!=''?", ".str_replace("\n\n",", ",$services_formatted[1]).". ":"").$discount_note,
		        "redirectUrl"  => cpabc_appointment_get_FULL_site_url().'/?dex_bccf=ipn&ipncheck=1&itemnumber='.$item_number.'&mollieabc=1',
		        "metadata"     => array(
		    	    "order_id" => $order_id,
		        ),
	        ));
            header("Location: " . $payment->getPaymentUrl());
        } catch (Exception $e) {
            echo "Error: ".$e->getMessage();
        }
        exit;
    }

    if (cpabc_get_option('paypal_mode','production') == "sandbox")
        $ppurl = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
    else
        $ppurl = 'https://www.paypal.com/cgi-bin/webscr';

    if (CPABC_ENABLE_DEPOSIT)
        $price = round($price * CPABC_DEPOSIT_PERCENT / 100,2);

    if (floatval($price) > 0 && $paypal_option && ( !$paypal_optional || (@$_POST["bccf_payment_option_paypal"] == '1') ))
    {
?>
<html>
<head><title>Redirecting to Paypal...</title></head>
<body>
<form action="<?php echo $ppurl; ?>" name="ppform3" method="post">
<input type="hidden" name="cmd" value="_xclick" />
<input type="hidden" name="business" value="<?php echo trim(cpabc_get_option('paypal_email', _cpabc_appointments_get_default_paypal_email())); ?>" />
<input type="hidden" name="item_name" value="<?php
   if (function_exists('iconv'))
      echo iconv("utf-8","iso-8859-1",cpabc_get_option('paypal_product_name', CPABC_APPOINTMENTS_DEFAULT_PRODUCT_NAME).(@$_POST["services"]?": ".trim($services_formatted[1]):"").$discount_note);
   else
      echo cpabc_get_option('paypal_product_name', CPABC_APPOINTMENTS_DEFAULT_PRODUCT_NAME).(@$_POST["services"]?": ".trim($services_formatted[1]):"").$discount_note;
   ?>" />
<!--<input type="hidden" name="item_number" value="<?php echo $item_number; ?>" />-->
<input type="hidden" name="custom" value="<?php echo $item_number; ?>" />
<input type="hidden" name="amount" value="<?php echo $price; ?>" />
<input type="hidden" name="page_style" value="Primary" />
<input type="hidden" name="no_shipping" value="1" />
<input type="hidden" name="tax_rate" value="<?php echo cpabc_get_option('paypal_tax', '0'); ?>" />
<input type="hidden" name="return" value="<?php echo esc_url(cpabc_get_option('url_ok', CPABC_APPOINTMENTS_DEFAULT_OK_URL)); ?>">
<input type="hidden" name="cancel_return" value="<?php echo esc_url(cpabc_get_option('url_cancel', CPABC_APPOINTMENTS_DEFAULT_CANCEL_URL)); ?>" />
<input type="hidden" name="currency_code" value="<?php echo strtoupper(cpabc_get_option('currency', CPABC_APPOINTMENTS_DEFAULT_CURRENCY)); ?>" />
<input type="hidden" name="lc" value="<?php echo cpabc_get_option('paypal_language', CPABC_APPOINTMENTS_DEFAULT_PAYPAL_LANGUAGE); ?>" />
<input type="hidden" name="bn" value="NetFactorSL_SI_Custom" />
<input type="hidden" name="notify_url" value="<?php echo cpabc_appointment_get_FULL_site_url(); ?>/?cpabc_ipncheck=<?php echo $item_number; ?>" />
<input class="pbutton" type="hidden" value="Buy Now" /></div>
</form>
<script type="text/javascript">
document.ppform3.submit();
</script>
</body>
</html>
<?php
        exit();
    }
    else
    {
        if (!isset($_POST["woocommerce_cpabc_field"]))
            cpabc_process_ready_to_go_appointment($item_number);

        $redirect = true;

		/**
		 * Filters applied to decide if the website should be redirected to the thank you page after submit the form,
		 * pass a boolean as parameter and returns a boolean
		 */
        $redirect = apply_filters( 'cpabc_redirect', $redirect );
        if( $redirect )
        {
            header("Location: ".cpabc_get_option('url_ok', CPABC_APPOINTMENTS_DEFAULT_OK_URL));
            exit;
        }
    }

}


function cpabc_process_authorize() {
    global $wpdb;
    require_once dirname( __FILE__ ) . '/anet_php_sdk/AuthorizeNet.php';
    $transaction = new AuthorizeNetAIM( cpabc_get_option('authorizenet_api_id',''), cpabc_get_option('authorizenet_tra_key',''));
    $fields = array(
                     'description' => str_replace(",","-",$_POST["d"]),
                     'email' => $_POST['e']
                    );
    $transaction->setFields($fields);
    $transaction->amount = $_POST["cost"];
    $transaction->card_num = $_POST["cc"];
    $transaction->exp_date = $_POST["em"].'/'.$_POST["ey"];;

    $response = $transaction->authorizeAndCapture();

    if ($response->approved) {
      echo "OK";
    } else {
      echo $response->response_reason_text;
    }
    exit;
}


function cpabc_appointments_check_upload($uploadfiles) {
    $filetmp = $uploadfiles['tmp_name'];
    //clean filename and extract extension
    $filename = $uploadfiles['name'];
    // get file info
    $filetype = wp_check_filetype( basename( $filename ), null );

    if ( in_array ($filetype["ext"],array("php","asp","aspx","cgi","pl","perl","exe")) )
        return false;
    else
        return true;
}

function cpabc_appointments_user_access_to($calendar) {
    global $wpdb;
	$current_user = wp_get_current_user();
	$myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME." where id='".$calendar."' AND conwer<>'' AND conwer='".esc_sql($current_user->ID)."'" );
	return count($myrows);
}

function cpabc_appointments_load_discount_codes() {
    global $wpdb;

    if (!defined('CP_CALENDAR_ID'))
        define ('CP_CALENDAR_ID',$_GET["cpabc_item"]);

    if ( ! current_user_can('edit_pages') && !cpabc_appointments_user_access_to(CP_CALENDAR_ID) ) // prevent loading coupons from outside admin area
    {
        echo 'No enough privilegies to load this content.';
        exit;
    }

    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_DISCOUNT_CODES_TABLE_NAME ,"dc_times", "varchar(10) DEFAULT '0' NOT NULL");

    if (isset($_GET["add"]) && $_GET["add"] == "1")
        $wpdb->insert( CPABC_APPOINTMENTS_DISCOUNT_CODES_TABLE_NAME, array('cal_id' => CP_CALENDAR_ID,
                                                                         'code' => $_GET["code"],
                                                                         'discount' => $_GET["discount"],
                                                                         'availability' => $_GET["discounttype"],
                                                                         'dc_times' => $_GET["tm"],
                                                                         'expires' => $_GET["expires"],
                                                                         ));
    if (isset($_GET["delete"]) && $_GET["delete"] == "1")
        $wpdb->query( $wpdb->prepare( "DELETE FROM ".CPABC_APPOINTMENTS_DISCOUNT_CODES_TABLE_NAME." WHERE id = %d", $_GET["code"] ));

    $codes = $wpdb->get_results( 'SELECT * FROM '.CPABC_APPOINTMENTS_DISCOUNT_CODES_TABLE_NAME.' WHERE `cal_id`='.CP_CALENDAR_ID);
    if (count ($codes))
    {
        echo '<table>';
        echo '<tr>';
        echo '  <th style="padding:2px;background-color: #cccccc;font-weight:bold;">Cupon Code</th>';
        echo '  <th style="padding:2px;background-color: #cccccc;font-weight:bold;">Discount</th>';
        echo '  <th style="padding:2px;background-color: #cccccc;font-weight:bold;">Type</th>';
        echo '  <th style="padding:2px;background-color: #cccccc;font-weight:bold;" nowrap>Can be used?</th>';
        echo '  <th style="padding:2px;background-color: #cccccc;font-weight:bold;" nowrap>Used so far</th>';
        echo '  <th style="padding:2px;background-color: #cccccc;font-weight:bold;">Valid until</th>';
        echo '  <th style="padding:2px;background-color: #cccccc;font-weight:bold;">Options</th>';
        echo '</tr>';
        foreach ($codes as $value)
        {
           echo '<tr>';
           echo '<td>'.$value->code.'</td>';
           echo '<td>'.$value->discount.'</td>';
           echo '<td>'.($value->availability==1?"Fixed Value":"Percent").'</td>';
           echo '<td nowrap>'.($value->dc_times=='0'?'Unlimited':$value->dc_times.' times').'</td>';
           echo '<td nowrap>'.$value->used.' times</td>';
           echo '<td>'.substr($value->expires,0,10).'</td>';
           echo '<td>[<a href="javascript:cpabc_delete_coupon('.$value->id.')">Delete</a>]</td>';
           echo '</tr>';
        }
        echo '</table>';
    }
    else
        echo 'No discount codes listed for this calendar yet.';
    exit;
}

add_action( 'init', 'cpabc_appointments_check_IPN_verification', 11 );

function cpabc_appointments_check_IPN_verification() {

    global $wpdb;

	if ( ! isset( $_GET['cpabc_ipncheck'] ) || $_GET['cpabc_ipncheck'] == '' )
		return;
		
    $_GET["itemnumber"] = $_GET['cpabc_ipncheck'];

    $item_name = $_POST['item_name'];
    //$item_number = $_POST['item_number'];
    $payment_status = $_POST['payment_status'];
    $payment_amount = $_POST['mc_gross'];
    $payment_currency = $_POST['mc_currency'];
    $txn_id = $_POST['txn_id'];
    $receiver_email = $_POST['receiver_email'];
    $payer_email = $_POST['payer_email'];
    $payment_type = $_POST['payment_type'];
    $txnid = $_POST['txn_id'];    

    /**
	if ($payment_status != 'Completed' && $payment_type != 'echeck')
	    return;

	if ($payment_type == 'echeck' && $payment_status == 'Completed')
	    return;
    */
    /**
    if (@$_GET["mollieabc"] != '1')
    {
        require_once dirname(__FILE__) . "/mollie-api/src/Mollie/API/Autoloader.php";
        $mollie = new Mollie_API_Client;
        $mollie->setApiKey( cpabc_get_option('enable_mollie_id', '') );
        $payment  = $mollie->payments->get($itemnumber);
	    $order_id = $payment->metadata->order_id;
	    if ($payment->isPaid() != TRUE)
	        header( 'Location: '.cpabc_get_option('url_cancel', DEX_BCCF_DEFAULT_CANCEL_URL) );
    }
    */
    $itemnumber = explode(";",$_GET["itemnumber"]);
    $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_TDEAPP_CALENDAR_DATA_TABLE." WHERE reference='".intval($itemnumber[0])."'" );
    if (count($myrows))
    {
        echo 'OK - Already processed';
        exit;
    }
    
    $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_TABLE_NAME." WHERE id=".intval($itemnumber[0]) );
    $params = unserialize($myrows[0]->buffered_date);
    $params["txnid"] = $txnid;
    $wpdb->query( "UPDATE ".CPABC_APPOINTMENTS_TABLE_NAME." SET buffered_date='".esc_sql(serialize($params))."' WHERE id=".intval($itemnumber[0]) );  
       

    cpabc_process_ready_to_go_appointment($_GET["itemnumber"], $payer_email);
    /**
    if (@$_GET["mollieabc"] == '1')
    {
        header( 'Location: '.cpabc_get_option('url_ok', DEX_BCCF_DEFAULT_CANCEL_URL) );
        exit();
    }
    */

    echo 'OK';

    exit();

}

function cpabc_process_cancel_go_appointment()
{
    global $wpdb;
    $itemnumber = intval(base64_decode($_GET["i"]));
    $item = $wpdb->get_row("SELECT * FROM ".CPABC_TDEAPP_CALENDAR_DATA_TABLE." WHERE id=".$itemnumber);

    if ($item->appointment_calendar_id && !defined('CP_CALENDAR_ID'))
        define ('CP_CALENDAR_ID',$item->appointment_calendar_id);
    if (!$item->appointment_calendar_id && !defined('CP_CALENDAR_ID'))
        define ('CP_CALENDAR_ID',1);

    $expire_date = date("Y-m-d H:i:s", strtotime($item->datatime." -".cpabc_get_option('canceluntil', CPABC_APPOINTMENTS_DEFAULT_CANCEL_AVAILABLE_UNTIL)." hours"));
    $weekday = date("N",strtotime($expire_date));
    
    if (CPABC_APPOINTMENTS_DEFAULT_CANCEL_SKIP_WEEKENDS && $weekday >= 6)
    {
        if ($weekday == 6)
            $expire_date = date("Y-m-d", strtotime($expire_date." -1 day" ));
        else
            $expire_date = date("Y-m-d", strtotime($expire_date." -2 days" ));
        $expire_date .= ' 23:59:59';
    }
    if ($expire_date < date("Y-m-d H:i:s"))
        header("Location: ".cpabc_get_option('cancelredirectexpired', CPABC_APPOINTMENTS_DEFAULT_ON_CANCEL_EXPIRED_REDIRECT_TO));
    else
    {
        $wpdb->query( "UPDATE ".CPABC_TDEAPP_CALENDAR_DATA_TABLE." SET is_cancelled='1',who_cancelled='-1' WHERE id=".$itemnumber );

        // send email to admin
        if ('html' == cpabc_get_option('cnadmin_emailformat')) $content_type = "Content-Type: text/html; charset=utf-8\n"; else $content_type = "Content-Type: text/plain; charset=utf-8\n";
        $email_content = str_replace('%INFORMATION%',str_replace('<br />',"\n",$item->description_customer), cpabc_get_option('cemail_notification_to_admin') );
        $email_subject = cpabc_get_option('cemail_subject_notification_to_admin');

        $app_source = $wpdb->get_results( "SELECT buffered_date FROM ".CPABC_APPOINTMENTS_TABLE_NAME." WHERE id='".$item->reference."'");
        $params = unserialize($app_source[0]->buffered_date);
        $params['ITEMNUMBER'] = $itemnumber;
        foreach ($params as $itemr => $value)
        {
            $email_content = str_replace('<%'.$itemr.'%>',(is_array($value)?(implode(", ",$value)):($value)),$email_content);
            $email_content = str_replace('%'.$itemr.'%',(is_array($value)?(implode(", ",$value)):($value)),$email_content);
            $email_subject = str_replace('<%'.$itemr.'%>',(is_array($value)?(implode(", ",$value)):($value)),$email_subject);
            $email_subject = str_replace('%'.$itemr.'%',(is_array($value)?(implode(", ",$value)):($value)),$email_subject);
        }
        $email_content = str_replace("%CALENDAR%", cpabc_get_option('uname'), $email_content);

        $SYSTEM_EMAIL = cpabc_get_option('notification_from_email');
        $pos = strpos($SYSTEM_EMAIL, "<");
        if ($pos === false)
            $SYSTEM_EMAIL = '"'.$SYSTEM_EMAIL.'" <'.$SYSTEM_EMAIL.'>';

        $to = explode(",",strtolower(cpabc_get_option('notification_destination_email')));
        foreach ($to as $itemto)
            if (trim($itemto) != '' && CPABC_ENABLE_ADMIN_EMAILS)
                wp_mail(trim($itemto), $email_subject, $email_content,
                       "From: ".$SYSTEM_EMAIL."\r\n".
                       $content_type.
                        "X-Mailer: PHP/" . phpversion());

         // send email to customer
        if ('html' == cpabc_get_option('cncustomer_emailformat')) $content_type = "Content-Type: text/html; charset=utf-8\n"; else $content_type = "Content-Type: text/plain; charset=utf-8\n";
        $email_content = str_replace('%INFORMATION%',str_replace('<br />',"\n",$item->description_customer), cpabc_get_option('cemail_notification_to_customer') );
        $email_subject = cpabc_get_option('cemail_subject_notification_to_customer');
        
        foreach ($params as $itemr => $value)
        {
            $email_content = str_replace('<%'.$itemr.'%>',(is_array($value)?(implode(", ",$value)):($value)),$email_content);
            $email_content = str_replace('%'.$itemr.'%',(is_array($value)?(implode(", ",$value)):($value)),$email_content);
            $email_subject = str_replace('<%'.$itemr.'%>',(is_array($value)?(implode(", ",$value)):($value)),$email_subject);
            $email_subject = str_replace('%'.$itemr.'%',(is_array($value)?(implode(", ",$value)):($value)),$email_subject);            
        }
        $email_content = str_replace("%CALENDAR%", cpabc_get_option('uname'), $email_content);

        if (CPABC_ENABLE_CUSTOMER_EMAILS)
            wp_mail(strtolower($item->title), $email_subject, $email_content,
                "From: ".$SYSTEM_EMAIL."\r\n".
                $content_type.
                "X-Mailer: PHP/" . phpversion());

        header("Location: ".cpabc_get_option('cancelredirect', CPABC_APPOINTMENTS_DEFAULT_ON_CANCEL_REDIRECT_TO));
    }
    exit;
}

function cpabc_process_validation_go_appointment()
{
    global $wpdb;
    $itemnumber = intval(base64_decode($_GET["i"]));

    $item_main = $wpdb->get_row("SELECT * FROM ".CPABC_TDEAPP_CALENDAR_DATA_TABLE." WHERE id=".$itemnumber);

    $item = $wpdb->get_row("SELECT * FROM ".CPABC_APPOINTMENTS_TABLE_NAME." WHERE id=".$item_main->reference);

    $expire_date = date("Y-m-d H:i:s", strtotime($item->time." +". get_option('CPABC_VALIDATION_TIMEOUT',CPABC_VALIDATION_TIMEOUT) ." hours"));
    $weekday = date("N",strtotime($expire_date));

    if ($item_main->appointment_calendar_id && !defined('CP_CALENDAR_ID'))
        define ('CP_CALENDAR_ID',$item->appointment_calendar_id);
    if (!$item_main->appointment_calendar_id && !defined('CP_CALENDAR_ID'))
        define ('CP_CALENDAR_ID',1);        

    if (!$item_main->id_verified && $expire_date < date("Y-m-d H:i:s"))
        header("Location: ". get_option('CPABC_VALIDATE_EXPIRED_REDIRECT_TO',CPABC_VALIDATE_EXPIRED_REDIRECT_TO) );
    else
    {
        $related_apps = $wpdb->get_results( "SELECT id FROM ".CPABC_APPOINTMENTS_TABLE_NAME." WHERE time='".$item->time."' AND email='".esc_sql($item->email)."'");
        foreach ($related_apps as $rapp)
            $wpdb->query( "UPDATE ".CPABC_TDEAPP_CALENDAR_DATA_TABLE." SET is_verified='1' WHERE reference=".$rapp->id );
        header("Location: ". get_option('CPABC_VALIDATE_REDIRECT_TO',CPABC_VALIDATE_REDIRECT_TO) );
    }
    exit;
}

function cpabc_update_verifieds()
{
    if (get_option('CPABC_ENABLE_VALIDATIONS',"1") != '2')
        return;
    global $wpdb;
    cpabc_appointments_add_field_verify($wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX, 'is_verified', "VARCHAR(10) DEFAULT '0' NOT NULL");
    cpabc_appointments_add_field_verify($wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX, 'verified_required', "VARCHAR(10) DEFAULT '0' NOT NULL");
    $expire_date = date("Y-m-d H:i:s", strtotime(" -". get_option('CPABC_VALIDATION_TIMEOUT',CPABC_VALIDATION_TIMEOUT) ." hours"));
    $items = $wpdb->get_results("SELECT ".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".* FROM ".CPABC_TDEAPP_CALENDAR_DATA_TABLE." INNER JOIN ".CPABC_APPOINTMENTS_TABLE_NAME." ON ".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".reference=".CPABC_APPOINTMENTS_TABLE_NAME.".id WHERE verified_required='1' AND is_verified<>'1' AND is_cancelled<>'1' AND time<'".$expire_date."'");
    foreach ($items as $item)
        $wpdb->query( "UPDATE ".CPABC_TDEAPP_CALENDAR_DATA_TABLE." SET is_cancelled='1',who_cancelled='-1' WHERE id=".$item->id );
}


function cpabc_process_ready_to_go_appointment($itemnumber, $payer_email = "", $is_resend = false)
{
   global $wpdb;

   cpabc_appointments_add_field_verify(CPABC_TDEAPP_CALENDAR_DATA_TABLE, 'quantity', "VARCHAR(25) DEFAULT '1' NOT NULL");
   cpabc_appointments_add_field_verify(CPABC_TDEAPP_CALENDAR_DATA_TABLE, 'quantity_a', "VARCHAR(25) DEFAULT '1' NOT NULL");
   cpabc_appointments_add_field_verify(CPABC_TDEAPP_CALENDAR_DATA_TABLE, 'quantity_s', "VARCHAR(25) DEFAULT '1' NOT NULL");
   cpabc_appointments_add_field_verify(CPABC_TDEAPP_CALENDAR_DATA_TABLE, 'reminder', "VARCHAR(1) DEFAULT '' NOT NULL");
   cpabc_appointments_add_field_verify(CPABC_TDEAPP_CALENDAR_DATA_TABLE, 'reference', "VARCHAR(20) DEFAULT '' NOT NULL");
   cpabc_appointments_add_field_verify(CPABC_TDEAPP_CALENDAR_DATA_TABLE, 'description_customer');

   $itemnumber = explode(";",$itemnumber);
   $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_TABLE_NAME." WHERE id=".intval($itemnumber[0]) );
   $mycalendarrows = $wpdb->get_results( 'SELECT * FROM '.CPABC_APPOINTMENTS_CONFIG_TABLE_NAME .' WHERE `'.CPABC_TDEAPP_CONFIG_ID.'`='.$myrows[0]->calendar);
   $reminder_timeline = date( "Y-m-d H:i:s", strtotime (date("Y-m-d H:i:s")." +".$mycalendarrows[0]->reminder_hours." hours") );
   if (!defined('CP_CALENDAR_ID'))
        define ('CP_CALENDAR_ID',$myrows[0]->calendar);

   $SYSTEM_EMAIL = trim(cpabc_get_option('notification_from_email', _cpabc_appointments_get_default_from_email() ));
   $SYSTEM_RCPT_EMAIL = cpabc_get_option('notification_destination_email', _cpabc_appointments_get_default_paypal_email() );
   $pos = strpos($SYSTEM_EMAIL, "<");
   if ($pos === false)
       $SYSTEM_EMAIL = '"'.$SYSTEM_EMAIL.'" <'.$SYSTEM_EMAIL.'>';


   $email_subject1 = cpabc_get_option('email_subject_confirmation_to_user', CPABC_APPOINTMENTS_DEFAULT_SUBJECT_CONFIRMATION_EMAIL);
   $email_content1 = cpabc_get_option('email_confirmation_to_user', CPABC_APPOINTMENTS_DEFAULT_CONFIRMATION_EMAIL);
   $email_subject2 = cpabc_get_option('email_subject_notification_to_admin', CPABC_APPOINTMENTS_DEFAULT_SUBJECT_NOTIFICATION_EMAIL);
   $email_content2 = cpabc_get_option('email_notification_to_admin', CPABC_APPOINTMENTS_DEFAULT_NOTIFICATION_EMAIL);

   $email_content1 = str_replace("%CALENDAR%", $mycalendarrows[0]->uname, $email_content1);
   $email_content2 = str_replace("%CALENDAR%", $mycalendarrows[0]->uname, $email_content2);

   $send_ical_file = cpabc_get_option('enable_icalemail','');
   $ical_subject = cpabc_get_option('icalemail_subject', 'Appointment');

   $params = unserialize($myrows[0]->buffered_date);

   if (!$is_resend && $params["coupon"] != '')
      $wpdb->query( "UPDATE ".CPABC_APPOINTMENTS_DISCOUNT_CODES_TABLE_NAME." SET used=used+1 WHERE code='".esc_sql(@$params["coupon"])."' AND expires>='".date("Y-m-d")." 00:00:00' AND `cal_id`=".$myrows[0]->calendar);

   $attachments = array();
   foreach ($params as $item => $value)
   {
       $ical_subject = str_replace('<%'.$item.'%>',(is_array($value)?(implode(", ",$value)):($value)),$ical_subject);
       $email_content1 = str_replace('<%'.$item.'%>',(is_array($value)?(implode(", ",$value)):($value)),$email_content1);
       $email_content2 = str_replace('<%'.$item.'%>',(is_array($value)?(implode(", ",$value)):($value)),$email_content2);
       $email_content1 = str_replace('%'.$item.'%',(is_array($value)?(implode(", ",$value)):($value)),$email_content1);
       $email_content2 = str_replace('%'.$item.'%',(is_array($value)?(implode(", ",$value)):($value)),$email_content2);
       
       $email_subject1 = str_replace('<%'.$item.'%>',(is_array($value)?(implode(", ",$value)):($value)),$email_subject1);
       $email_subject2 = str_replace('<%'.$item.'%>',(is_array($value)?(implode(", ",$value)):($value)),$email_subject2);
       $email_subject1 = str_replace('%'.$item.'%',(is_array($value)?(implode(", ",$value)):($value)),$email_subject1);
       $email_subject2 = str_replace('%'.$item.'%',(is_array($value)?(implode(", ",$value)):($value)),$email_subject2);       
       if (strpos($item,"_link"))
       {
           foreach ($value as $filevalue)
               $attachments[] = $filevalue;
       }
   }
   for ($i=0;$i<500;$i++)
   {
        $ical_subject = str_replace('<%fieldname'.$i.'%>',"",$ical_subject);
        $email_content1 = str_replace('<%fieldname'.$i.'%>',"",$email_content1);
        $email_content2 = str_replace('<%fieldname'.$i.'%>',"",$email_content2);
        $email_subject1 = str_replace('<%fieldname'.$i.'%>',"",$email_subject1);
        $email_subject2 = str_replace('<%fieldname'.$i.'%>',"",$email_subject2);
   }
   $buffered_dates = array();
   $buffered_dates_customer = array();
   $itemnumbers_all = array();
   for ($n=0;$n<count($itemnumber);$n++)
   {
       $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_TABLE_NAME." WHERE id=".intval($itemnumber[$n]) );
       $buffered_dates[] = $myrows[0]->booked_time;
       $buffered_dates_customer[] = $myrows[0]->booked_time_customer;
       $information = $mycalendarrows[0]->uname."\n".
                      $myrows[0]->booked_time."\n".
                      ($myrows[0]->name?$myrows[0]->name."\n":"").
                      $myrows[0]->email."\n".
                      ($myrows[0]->phone?$myrows[0]->phone."\n":"").
                      $myrows[0]->question."\n";
       $information_customer = $mycalendarrows[0]->uname."\n".
                      $myrows[0]->booked_time_customer."\n".
                      ($myrows[0]->name?$myrows[0]->name."\n":"").
                      $myrows[0]->email."\n".
                      ($myrows[0]->phone?$myrows[0]->phone."\n":"").
                      $myrows[0]->question."\n";

       if ($reminder_timeline > date("Y-m-d H:i:s", strtotime($myrows[0]->booked_time_unformatted)))
           $reminder = '1';
       else
           $reminder = '';
       if (!$is_resend)
           $rows_affected = $wpdb->insert( CPABC_TDEAPP_CALENDAR_DATA_TABLE, array( 'appointment_calendar_id' => $myrows[0]->calendar,
                                                                            'datatime' => date("Y-m-d H:i:s", strtotime($myrows[0]->booked_time_unformatted)),
                                                                            'title' => $myrows[0]->email,
                                                                            'reminder' => $reminder,
                                                                            'quantity' =>  (isset($myrows[0]->quantity)?$myrows[0]->quantity:1),
                                                                            'quantity_a' =>  (isset($myrows[0]->quantity_a)?$myrows[0]->quantity_a:1),
                                                                            'quantity_s' =>  (isset($myrows[0]->quantity_s)?$myrows[0]->quantity_s:1),
                                                                            'description' => str_replace("\n","<br />", $information),
                                                                            'description_customer' => str_replace("\n","<br />", $information_customer),
                                                                            'reference' => intval($itemnumber[$n]),
                                                                            'verified_required' => ((get_option('CPABC_ENABLE_VALIDATIONS',"1") == '2')?'1':'0'),
                                                                            'who_added' => $myrows[0]->who_added
                                                                             ) );
                                                                             
       $email_subject1 = str_replace("%ITEMNUMBER%", $wpdb->insert_id, $email_subject1);
       $email_subject2 = str_replace("%ITEMNUMBER%", $wpdb->insert_id, $email_subject2);
       $email_content1 = str_replace("%ITEMNUMBER%", $wpdb->insert_id, $email_content1);
       $email_content2 = str_replace("%ITEMNUMBER%", $wpdb->insert_id, $email_content2);
   
       $itemnumbers_all[] = $wpdb->insert_id;                                                                       
       // SEND EMAILS START
       if ($n == count($itemnumber)-1) // send emails only once
       {

           $params['itemnumber'] = $wpdb->insert_id;
           
           $base_information = ($myrows[0]->name?$myrows[0]->name."\n":"").
                  $myrows[0]->email."\n".
                  ($myrows[0]->phone?$myrows[0]->phone."\n":"").
                  $myrows[0]->question."\n";

           $information = $mycalendarrows[0]->uname."\n".
                  implode("\n",$buffered_dates)."\n".
                  $base_information;

           $information_customer = $mycalendarrows[0]->uname."\n".
                  implode("\n",$buffered_dates_customer)."\n".
                  $base_information;

           $email_content1 = str_replace("%INFORMATION%", $information_customer, $email_content1);
           $email_content2 = str_replace("%INFORMATION%", $information, $email_content2);

           $email_content1 = str_replace("%ALLDATES%", implode("\n",$buffered_dates_customer), $email_content1);
           $email_content2 = str_replace("%ALLDATES%", implode("\n",$buffered_dates), $email_content2);


           $itemnumberdb = $wpdb->insert_id;
           $cancel_link = cpabc_appointment_get_FULL_site_url().'/?cpabc_c=1&i='.base64_encode($itemnumberdb).'&a=1';

           $email_content1 = str_replace("%CANCEL%", $cancel_link, $email_content1);
           $email_content2 = str_replace("%CANCEL%", $cancel_link, $email_content2);
           
           // start:: cancel all buffer
           $cancel_buffer = '';
           for($kc=0; $kc<count($itemnumber); $kc++) 
           {
               $myrowsBooking = $wpdb->get_results( "SELECT booked_time_customer FROM ".CPABC_APPOINTMENTS_TABLE_NAME." WHERE id=".intval($itemnumber[$kc]) );
               $cancel_buffer .= $myrowsBooking[0]->booked_time_customer." -> ".cpabc_appointment_get_FULL_site_url().'/?cpabc_c=1&i='.base64_encode($itemnumbers_all[$kc]).'&a=1  '."\n";
           }

           $email_content1 = str_replace("%ALL_CANCEL_LINKS%", $cancel_buffer, $email_content1);
           $email_content2 = str_replace("%ALL_CANCEL_LINKS%", $cancel_buffer, $email_content2);
           // end:: cancel all buffer
           
           if ((get_option('CPABC_ENABLE_VALIDATIONS',"1") == '2'))
               $val_link = cpabc_appointment_get_FULL_site_url().'/?cpabc_v=1&i='.base64_encode($itemnumberdb).'&a=1';
           else
               $val_link = '';
           $email_content1 = str_replace("%VALIDATION%", $val_link, $email_content1);
           $email_content2 = str_replace("%VALIDATION%", $val_link, $email_content2);

           $attachments_customer = array();

           if ($send_ical_file)
           {
               if (!defined('CPABC_CAL_TIME_ZONE_MODIFY')) define('CPABC_CAL_TIME_ZONE_MODIFY',get_option('CPABC_CAL_TIME_ZONE_MODIFY_SET'," +2 hours"));
               if (!defined('CPABC_CAL_TIME_SLOT_SIZE')) define('CPABC_CAL_TIME_SLOT_SIZE'," +".get_option('CPABC_CAL_TIME_SLOT_SIZE_SET',"15")." minutes");
 
 
                // get ical files
               $ical_content = cpabc_getICalItems($itemnumber, $ical_subject);
               $ical_content_admin = $ical_content[0];
               $ical_content_customer = $ical_content[1];

               $filename1 = cpabc_generateSafeFileName('Appointment').'_'.$myrows[0]->id.'_admin';
               $filename1 = WP_CONTENT_DIR . '/uploads/'.$filename1 .'.ics';
               $handle = fopen($filename1, 'w');
               fwrite($handle,$ical_content_admin);
               fclose($handle);
               $attachments[] = $filename1;

               $filename2 = cpabc_generateSafeFileName('Appointment').'_'.$myrows[0]->id.'_cust';
               $filename2 = WP_CONTENT_DIR . '/uploads/'.$filename2 .'.ics';
               $handle = fopen($filename2, 'w');
               fwrite($handle,$ical_content_customer);
               fclose($handle);
               $attachments_customer[] = $filename2;
           }

           // SEND EMAIL TO USER
           if ('html' == cpabc_get_option('nuser_emailformat', CPABC_APPOINTMENTS_DEFAULT_email_format)) $content_type = "Content-Type: text/html; charset=utf-8\n"; else $content_type = "Content-Type: text/plain; charset=utf-8\n";
           
           if (!is_admin() || isset($_POST["sendemails_admin"]) || defined('CPABC_IS_RESEND') )
           {
               if (CPABC_ENABLE_CUSTOMER_EMAILS)
                   wp_mail(strtolower($myrows[0]->email), $email_subject1, $email_content1,
                        "From: $SYSTEM_EMAIL\r\n".
                        $content_type.
                        "X-Mailer: PHP/" . phpversion(), $attachments_customer);
               
               if (CPABC_ENABLE_CUSTOMER_EMAILS && $payer_email && strtolower($payer_email) != strtolower($myrows[0]->email))
                   wp_mail(strtolower($payer_email), $email_subject1, $email_content1,
                            "From: $SYSTEM_EMAIL\r\n".
                            $content_type.
                            "X-Mailer: PHP/" . phpversion(), $attachments_customer);
               
               // trigger sms action
               do_action( 'cpabc_smssend', array('params' => $params, 'formid' => CP_CALENDAR_ID, 'content' => $email_content1) );   
               
               $replyto = $myrows[0]->email;
               
               // SEND EMAIL TO ADMIN
               if ('html' == cpabc_get_option('nadmin_emailformat', CPABC_APPOINTMENTS_DEFAULT_email_format)) $content_type = "Content-Type: text/html; charset=utf-8\n"; else $content_type = "Content-Type: text/plain; charset=utf-8\n";
               $to = explode(",",$SYSTEM_RCPT_EMAIL);
               foreach ($to as $item)
                    if (trim($item) != '' && CPABC_ENABLE_ADMIN_EMAILS)
                    {
                        wp_mail(strtolower(trim($item)), $email_subject2, $email_content2,
                            "From: $SYSTEM_EMAIL\r\n".
                            ($replyto!=''?"Reply-To: ".$replyto."\r\n":'').
                            $content_type.
                            "X-Mailer: PHP/" . phpversion(), $attachments);
                    }
               foreach ($attachments as $value)
                   @unlink($value);  
               foreach ($attachments_customer as $value)
                   @unlink($value);   
           }              
       }
       // SEND EMAILS END
   }
      
}


function cpabc_getICalItems($itemnumber, $ical_subject = '') 
{
   global $wpdb;
   $ical_content_admin = "BEGIN:VCALENDAR\n".
                                   "PRODID:-//CodePeople//Appointment Booking Calendar for WordPress//EN\n".
                                   "VERSION:2.0\n";
   $ical_content_customer = "BEGIN:VCALENDAR\n".
                                   "PRODID:-//CodePeople//Appointment Booking Calendar for WordPress//EN\n".
                                   "VERSION:2.0\n";
   for ($n=0;$n<count($itemnumber);$n++)
   {
       $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_TABLE_NAME." WHERE id=".intval($itemnumber[$n]) ); 
       $mycalendarrows = $wpdb->get_results( 'SELECT * FROM '.CPABC_APPOINTMENTS_CONFIG_TABLE_NAME .' WHERE `'.CPABC_TDEAPP_CONFIG_ID.'`='.$myrows[0]->calendar);       
       $information = $mycalendarrows[0]->uname."\n".
                      $myrows[0]->booked_time."\n".
                      ($myrows[0]->name?$myrows[0]->name."\n":"").
                      $myrows[0]->email."\n".
                      ($myrows[0]->phone?$myrows[0]->phone."\n":"").
                      $myrows[0]->question."\n";   

        if (CPABC_APPOINTMENTS_ICAL_OBSERVE_DAYLIGHT)
        {
            $full_date = gmdate("Ymd",strtotime($myrows[0]->booked_time_unformatted.CPABC_CAL_TIME_ZONE_MODIFY));
            $year = substr($full_date,0,4);
            if (strtoupper(CPABC_APPOINTMENTS_ICAL_DAYLIGHT_ZONE) == 'EUROPE')
            {
                $dst_start = strtotime('last Sunday GMT', strtotime("1 April $year GMT"));
                $dst_stop = strtotime('last Sunday GMT', strtotime("1 November $year GMT"));
            } else { // USA
                $dst_start = strtotime('first Sunday GMT', strtotime("1 April $year GMT"));
                $dst_stop = strtotime('last Sunday GMT', strtotime("1 November $year GMT"));
            }
            if ($full_date >= gmdate("Ymd",$dst_start) && $full_date < gmdate("Ymd",$dst_stop))
                $myrows[0]->booked_time_unformatted = date("Y-m-d H:i",strtotime($myrows[0]->booked_time_unformatted." -1 hour"));
        }
        
       $ical_content_admin .= "BEGIN:VEVENT\n".
                                   "DTSTART:".gmdate("Ymd",strtotime($myrows[0]->booked_time_unformatted.CPABC_CAL_TIME_ZONE_MODIFY))."T".gmdate("His",strtotime($myrows[0]->booked_time_unformatted.CPABC_CAL_TIME_ZONE_MODIFY))."Z\n".
                                   "DTEND:".gmdate("Ymd",strtotime($myrows[0]->booked_time_unformatted.CPABC_CAL_TIME_ZONE_MODIFY.CPABC_CAL_TIME_SLOT_SIZE))."T".gmdate("His",strtotime($myrows[0]->booked_time_unformatted.CPABC_CAL_TIME_ZONE_MODIFY.CPABC_CAL_TIME_SLOT_SIZE))."Z\n".
                                   "DTSTAMP:".gmdate("Ymd")."T".gmdate("His")."Z\n".
                                   "UID:uid".$myrows[0]->id."@".$_SERVER["SERVER_NAME"]."\n".
                                   "DESCRIPTION:".str_replace("<br>",'\n',str_replace("<br />",'\n',str_replace("\r",'',str_replace("\n",'\n',$information)) ))."\n".
                                   "LAST-MODIFIED:".gmdate("Ymd")."T".gmdate("His")."Z\n".
                                   "LOCATION:\n".
                                   "SEQUENCE:0\n".
                                   "STATUS:CONFIRMED\n".
                                   "SUMMARY: ".str_replace("\n",'\n',$ical_subject)."\n".
                                   "TRANSP:OPAQUE\n".
                                   "END:VEVENT\n";   
                                   
       $ical_content_customer .= "BEGIN:VEVENT\n".
                                   //"DTSTART:".gmdate("Ymd",strtotime($myrows[0]->booked_time_customer.CPABC_CAL_TIME_ZONE_MODIFY))."T".gmdate("His",strtotime($myrows[0]->booked_time_customer.CPABC_CAL_TIME_ZONE_MODIFY))."Z\n".
                                   //"DTEND:".gmdate("Ymd",strtotime($myrows[0]->booked_time_customer.CPABC_CAL_TIME_ZONE_MODIFY.CPABC_CAL_TIME_SLOT_SIZE))."T".gmdate("His",strtotime($myrows[0]->booked_time_customer.CPABC_CAL_TIME_ZONE_MODIFY.CPABC_CAL_TIME_SLOT_SIZE))."Z\n".
                                   "DTSTART:".gmdate("Ymd",strtotime($myrows[0]->booked_time_unformatted.CPABC_CAL_TIME_ZONE_MODIFY))."T".gmdate("His",strtotime($myrows[0]->booked_time_unformatted.CPABC_CAL_TIME_ZONE_MODIFY))."Z\n".
                                   "DTEND:".gmdate("Ymd",strtotime($myrows[0]->booked_time_unformatted.CPABC_CAL_TIME_ZONE_MODIFY.CPABC_CAL_TIME_SLOT_SIZE))."T".gmdate("His",strtotime($myrows[0]->booked_time_unformatted.CPABC_CAL_TIME_ZONE_MODIFY.CPABC_CAL_TIME_SLOT_SIZE))."Z\n".
                                   "DTSTAMP:".gmdate("Ymd")."T".gmdate("His")."Z\n".
                                   "UID:uid".$myrows[0]->id."@".$_SERVER["SERVER_NAME"]."\n".
                                   "DESCRIPTION:".str_replace("<br>",'\n',str_replace("<br />",'\n',str_replace("\r",'',str_replace("\n",'\n',$information_customer)) ))."\n".
                                   "LAST-MODIFIED:".gmdate("Ymd")."T".gmdate("His")."Z\n".
                                   "LOCATION:\n".
                                   "SEQUENCE:0\n".
                                   "STATUS:CONFIRMED\n".
                                   "SUMMARY: ".str_replace("\n",'\n',$ical_subject)."\n".
                                   "TRANSP:OPAQUE\n".
                                   "END:VEVENT\n"; 
    }                               
    return array($ical_content_admin."END:VCALENDAR\n", $ical_content_customer."END:VCALENDAR\n");                                       
}


function cpabc_generateSafeFileName($filename)
{
        $filename = strtolower($filename);
        $filename = str_replace("#","_",$filename);
        $filename = str_replace(" ","_",$filename);
        $filename = str_replace("'","",$filename);
        $filename = str_replace('"',"",$filename);
        $filename = str_replace("__","_",$filename);
        $filename = str_replace("&","and",$filename);
        $filename = str_replace("/","_",$filename);
        $filename = str_replace("\\","_",$filename);
        $filename = str_replace("?","",$filename);
        return $filename;
}


function cpabc_appointments_add_field_verify ($table, $field, $type = "text")
{
    global $wpdb;
    $results = $wpdb->get_results("SHOW columns FROM `".$table."` where field='".$field."'");
    if (!count($results))
    {
        $sql = "ALTER TABLE  `".$table."` ADD `".$field."` ".$type;
        $wpdb->query($sql);
    }
}


function cpabc_appointments_save_edition()
{
    if (substr_count($_POST['editionarea'],"\\\""))
        $_POST["editionarea"] = stripcslashes($_POST["editionarea"]);
    if ($_POST["cfwpp_edit"] == 'js')   
        update_option('CP_ABC_JS', base64_encode($_POST["editionarea"]));  
    else if ($_POST["cfwpp_edit"] == 'css')  
        update_option('CP_ABC_CSS', base64_encode($_POST["editionarea"]));  
}


function cpabc_appointments_save_options()
{
    global $wpdb;
    if (!defined('CP_CALENDAR_ID'))
        define ('CP_CALENDAR_ID',$_POST["cpabc_item"]);

    if ( ! current_user_can('edit_pages') && !cpabc_appointments_user_access_to(CP_CALENDAR_ID) ) // prevent loading coupons from outside admin area
    {
        echo 'No enough privilegies to load this content.';
        exit;
    }

    if ((substr_count($_POST['form_structure_control'],"\\") > 1) || substr_count($_POST['form_structure_control'],"\\\"title\\\":"))
        foreach ($_POST as $item => $value)
            if (!is_array($value))
                $_POST[$item] = @stripcslashes($value);

    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'form_structure');

    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'vs_use_validation');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'vs_text_is_required');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'vs_text_is_email');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'vs_text_datemmddyyyy');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'vs_text_dateddmmyyyy');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'vs_text_number');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'vs_text_digits');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'vs_text_max');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'vs_text_min');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'vs_text_submitbtn');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'cu_user_email_field');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'cv_text_enter_valid_captcha');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'paypal_tax');    

    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'nuser_emailformat');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'nadmin_emailformat');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'nremind_emailformat');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'fu_nremind_emailformat');

    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'enable_reminder');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'reminder_hours');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'reminder_subject');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'reminder_content');

    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'enable_fu_reminder');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'fu_reminder_hours');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'fu_reminder_subject');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'fu_reminder_content');

    cpabc_appointments_add_field_verify(CPABC_TDEAPP_CALENDAR_DATA_TABLE, 'reminder', "VARCHAR(1) DEFAULT '' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_TDEAPP_CALENDAR_DATA_TABLE, 'fu_reminder', "VARCHAR(1) DEFAULT '' NOT NULL");

    cpabc_appointments_add_field_verify(CPABC_TDEAPP_CALENDAR_DATA_TABLE, 'quantity', "VARCHAR(25) DEFAULT '1' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_TDEAPP_CALENDAR_DATA_TABLE, 'quantity_a', "VARCHAR(25) DEFAULT '1' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_TDEAPP_CALENDAR_DATA_TABLE, 'quantity_s', "VARCHAR(25) DEFAULT '1' NOT NULL");

    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'min_slots');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'max_slots');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'close_fpanel');

    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'quantity_field', "VARCHAR(10) DEFAULT '0' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'quantity_field_two', "VARCHAR(10) DEFAULT '0' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'quantity_field_label', "VARCHAR(250) DEFAULT '".CPABC_APPOINTMENTS_ENABLE_QUANTITY_FIELD_LABEL."' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'quantity_field_two_label', "VARCHAR(250) DEFAULT '".CPABC_APPOINTMENTS_ENABLE_QUANTITY_FIELD_TWO_LABEL."' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'ajax_load_enabled', "VARCHAR(10) DEFAULT '".CPABC_APPOINTMENTS_ENABLE_AJAX_PRICE."' NOT NULL");


    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'calendar_startyear', "VARCHAR(20) DEFAULT '' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'calendar_startmonth', "VARCHAR(20) DEFAULT '' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'gmt_enabled', "VARCHAR(20) DEFAULT '' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'gmt_diff', "VARCHAR(20) DEFAULT '' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'calendar_theme');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'paypal_mode');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'master', "VARCHAR(10) DEFAULT '0' NOT NULL");
        cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'paypal_price_field', "VARCHAR(50) DEFAULT '' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'request_cost_st');

    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, "enable_paypal_option_yes", "varchar(250) DEFAULT '' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, "enable_paypal_option_no", "varchar(250) DEFAULT '' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, "stripe_key", "varchar(250) DEFAULT '' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, "stripe_secretkey", "varchar(250) DEFAULT '' NOT NULL");

    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, "authorizenet_api_id", "varchar(250) DEFAULT '' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, "authorizenet_tra_key", "varchar(250) DEFAULT '' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, "enable_mollie_id", "varchar(250) DEFAULT '' NOT NULL");

    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, "enable_icalemail", "varchar(10) DEFAULT '' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, "icalemail_subject", "varchar(250) DEFAULT '' NOT NULL");

    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, "cancelredirect", "varchar(250) DEFAULT '' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, "cancelredirectexpired", "varchar(250) DEFAULT '' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, "canceluntil", "varchar(250) DEFAULT '' NOT NULL");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, "autocreatecals", "varchar(10) DEFAULT '' NOT NULL");

    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, "cemail_subject_notification_to_admin");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, "cnadmin_emailformat");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, "cemail_notification_to_admin");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, "cemail_subject_notification_to_customer");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, "cncustomer_emailformat");
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, "cemail_notification_to_customer");

    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, "tax_rate", "varchar(10) DEFAULT '0' NOT NULL");


    for ($i=1;$i<=CPABC_DISCOUNT_FIELDS;$i++)
    {
       cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'discountslots'.$i, "VARCHAR(10) DEFAULT '1' NOT NULL");
       cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'discountvalue'.$i, "VARCHAR(10) DEFAULT '1' NOT NULL");
    }

    $_POST["request_cost"] = '';
    for ($k=1;$k <= intval($_POST["max_slots"]); $k++)
        $_POST["request_cost"] .= ($k!=1?";":"").$_POST["request_cost_".$k];

    $_POST["request_cost_st"] = '';
    for ($k=1;$k <= intval($_POST["max_slots"]); $k++)
        $_POST["request_cost_st"] .= ($k!=1?";":"").@$_POST["request_cost_st_".$k];

    $data = array(
         'form_structure' => $_POST['form_structure'],
         'calendar_language' => $_POST["calendar_language"],
         'calendar_dateformat' => $_POST["calendar_dateformat"],
         'calendar_pages' => $_POST["calendar_pages"],
         'calendar_militarytime' => $_POST["calendar_militarytime"],
         'calendar_weekday' => $_POST["calendar_weekday"],
         'calendar_mindate' => $_POST["calendar_mindate"],
         'calendar_maxdate' => $_POST["calendar_maxdate"],
         'min_slots' => $_POST["min_slots"],
         'max_slots' => $_POST["max_slots"],
         'close_fpanel' => $_POST["close_fpanel"],
         'paypal_tax' => $_POST["paypal_tax"],

         'quantity_field' => @$_POST["quantity_field"],
         'quantity_field_two' => @$_POST["quantity_field_two"],
         'quantity_field_label' => @$_POST["quantity_field_label"],
         'quantity_field_two_label' => @$_POST["quantity_field_two_label"],
         'ajax_load_enabled' => @$_POST["ajax_load_enabled"],
         'paypal_mode' => @$_POST["paypal_mode"],
         'tax_rate' => @$_POST["tax_rate"],

         'master' => @$_POST["master"],

         'calendar_startyear' => $_POST["calendar_startyear"],
         'calendar_startmonth' => $_POST["calendar_startmonth"],
         'calendar_theme' => $_POST["calendar_theme"],

         'gmt_enabled' => @$_POST["gmt_enabled"],
         'gmt_diff' => @$_POST["gmt_diff"],

         'enable_fu_reminder' => @$_POST["enable_fu_reminder"],
         'fu_reminder_hours' => @$_POST["fu_reminder_hours"],
         'fu_reminder_subject' => @$_POST["fu_reminder_subject"],
         'fu_nremind_emailformat' => @$_POST["fu_nremind_emailformat"],
         'fu_reminder_content' => @$_POST["fu_reminder_content"],

         'cemail_subject_notification_to_admin' => @$_POST["cemail_subject_notification_to_admin"],
         'cnadmin_emailformat' => @$_POST["cnadmin_emailformat"],
         'cemail_notification_to_admin' => @$_POST["cemail_notification_to_admin"],
         'cemail_subject_notification_to_customer' => @$_POST["cemail_subject_notification_to_customer"],
         'cncustomer_emailformat' => @$_POST["cncustomer_emailformat"],
         'cemail_notification_to_customer' => @$_POST["cemail_notification_to_customer"],

         'cancelredirect' => @$_POST["cancelredirect"],
         'cancelredirectexpired' => @$_POST["cancelredirectexpired"],
         'canceluntil' => @$_POST["canceluntil"],
         'autocreatecals' => @$_POST["autocreatecals"],

         'enable_icalemail' => @$_POST["enable_icalemail"],
         'icalemail_subject' => @$_POST["icalemail_subject"],

         'enable_paypal' => @$_POST["enable_paypal"],
         'paypal_email' => $_POST["paypal_email"],
         'request_cost' => $_POST["request_cost"],
         'request_cost_st' => $_POST["request_cost_st"],
         'paypal_price_field' => @$_POST["paypal_price_field"],
         'paypal_product_name' => $_POST["paypal_product_name"],
         'currency' => $_POST["currency"],
         'url_ok' => $_POST["url_ok"],
         'url_cancel' => $_POST["url_cancel"],
         'paypal_language' => $_POST["paypal_language"],

         'enable_paypal_option_yes' => (@$_POST['enable_paypal_option_yes']?$_POST['enable_paypal_option_yes']:CPABC_APPOINTMENTS_DEFAULT_PAYPAL_OPTION_YES),
         'enable_paypal_option_no' => (@$_POST['enable_paypal_option_no']?$_POST['enable_paypal_option_no']:CPABC_APPOINTMENTS_DEFAULT_PAYPAL_OPTION_NO),
         'stripe_key' => @$_POST["stripe_key"],
         'stripe_secretkey' => @$_POST["stripe_secretkey"],

         'authorizenet_api_id' => @$_POST["authorizenet_api_id"],
         'authorizenet_tra_key' => @$_POST["authorizenet_tra_key"],
         'enable_mollie_id' => @$_POST["enable_mollie_id"],

         'nuser_emailformat' => $_POST["nuser_emailformat"],
         'nadmin_emailformat' => $_POST["nadmin_emailformat"],
         'nremind_emailformat' => $_POST["nremind_emailformat"],

         //'vs_use_validation' => $_POST['vs_use_validation'],
         'vs_text_is_required' => $_POST['vs_text_is_required'],
         'vs_text_is_email' => $_POST['vs_text_is_email'],
         'vs_text_datemmddyyyy' => $_POST['vs_text_datemmddyyyy'],
         'vs_text_dateddmmyyyy' => $_POST['vs_text_dateddmmyyyy'],
         'vs_text_number' => $_POST['vs_text_number'],
         'vs_text_digits' => $_POST['vs_text_digits'],
         'vs_text_max' => $_POST['vs_text_max'],
         'vs_text_min' => $_POST['vs_text_min'],
         'vs_text_submitbtn' => $_POST['vs_text_submitbtn'],

         'cu_user_email_field' => @$_POST["cu_user_email_field"],

         'notification_from_email' => $_POST["notification_from_email"],
         'notification_destination_email' => $_POST["notification_destination_email"],
         'email_subject_confirmation_to_user' => $_POST["email_subject_confirmation_to_user"],
         'email_confirmation_to_user' => $_POST["email_confirmation_to_user"],
         'email_subject_notification_to_admin' => $_POST["email_subject_notification_to_admin"],
         'email_notification_to_admin' => $_POST["email_notification_to_admin"],

         'enable_reminder' => @$_POST["enable_reminder"],
         'reminder_hours' => @$_POST["reminder_hours"],
         'reminder_subject' => @$_POST["reminder_subject"],
         'reminder_content' => @$_POST["reminder_content"],

         'dexcv_enable_captcha' => $_POST["dexcv_enable_captcha"],
         'dexcv_width' => $_POST["dexcv_width"],
         'dexcv_height' => $_POST["dexcv_height"],
         'dexcv_chars' => $_POST["dexcv_chars"],
         'dexcv_min_font_size' => $_POST["dexcv_min_font_size"],
         'dexcv_max_font_size' => $_POST["dexcv_max_font_size"],
         'dexcv_noise' => $_POST["dexcv_noise"],
         'dexcv_noise_length' => $_POST["dexcv_noise_length"],
         'dexcv_background' => $_POST["dexcv_background"],
         'dexcv_border' => $_POST["dexcv_border"],
         'dexcv_font' => $_POST["dexcv_font"],
         'cv_text_enter_valid_captcha' => $_POST['cv_text_enter_valid_captcha'],
         'cp_cal_checkboxes' => @$_POST["cp_cal_checkboxes"]
	);

    for ($i=1;$i<=CPABC_DISCOUNT_FIELDS;$i++)
    {
       $data["discountslots".$i] = @$_POST["discountslots".$i];
       $data["discountvalue".$i] = @$_POST["discountvalue".$i];
    }

    $wpdb->update ( CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, $data, array( 'id' => CP_CALENDAR_ID ));
}

function cpabc_appointments_get_field_name ($fieldid, $form)
{
    if (is_array($form))
        foreach($form as $item)
            if ($item->name == $fieldid)
                {
                    if (isset($item->shortlabel) && $item->shortlabel != '')
                        return $item->shortlabel;
                    else
                        return $item->title;
                }
    return $fieldid;
}

function cpabc_appointments_export_csv ()
{
    if (!is_admin())
        return;
    global $wpdb;

    if (!defined('CP_CALENDAR_ID'))
        define ('CP_CALENDAR_ID',intval($_GET["cal"]));

    $form_data = json_decode(cpabc_appointment_cleanJSON(cpabc_get_option('form_structure', CPABC_APPOINTMENTS_DEFAULT_form_structure)));

    $excluded = explode(",",get_option('CPABC_EXCLUDED_COLUMNS',""));
    for ($i=0; $i<count($excluded); $i++)
        $excluded[$i] = trim($excluded[$i]);
    
    if (@$_GET["cancelled_by"] != '')
        $cond = '';
    else
        $cond = " AND ((is_cancelled<>'1') OR is_cancelled is null)";
    if ($_GET["search"] != '') $cond .= " AND (buffered_date like '%".esc_sql($_GET["search"])."%')";
    if ($_GET["dfrom"] != '') { $cond .= " AND (`booked_time_unformatted` >= '".esc_sql($_GET["dfrom"])."')"; $from = $_GET["dfrom"]; }
    if ($_GET["dto"] != '') { $cond .= " AND (`booked_time_unformatted` <= '".esc_sql($_GET["dto"])." 23:59:59')"; $to = $_GET["dto"]; }

    if (@$_GET["added_by"] != '') $cond .= " AND (who_added >= '".esc_sql($_GET["added_by"])."')";
    if (@$_GET["edited_by"] != '') $cond .= " AND (who_edited >= '".esc_sql($_GET["edited_by"])."')";
    if (@$_GET["cancelled_by"] != '') $cond .= " AND (is_cancelled='1' AND who_cancelled >= '".esc_sql($_GET["cancelled_by"])."')";

    if (CP_CALENDAR_ID != 0) $cond .= " AND appointment_calendar_id=".CP_CALENDAR_ID;

    $events = $wpdb->get_results( "SELECT *,".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".id as itemnumber FROM ".CPABC_TDEAPP_CALENDAR_DATA_TABLE." INNER JOIN ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME." ON ".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".appointment_calendar_id=".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME.".id LEFT JOIN ".CPABC_APPOINTMENTS_TABLE_NAME." ON ".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".reference=".CPABC_APPOINTMENTS_TABLE_NAME.".id  WHERE 1=1 ".$cond." ORDER BY ".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".".$_GET["orderby"]."" );

    if (isset($_GET["cpabc_appointments_csv_unused"])  && $from && $to && $to >= $from && CP_CALENDAR_ID)    
    {
        $used = array();
        foreach($events as $item)
            if (isset($used[$item->booked_time_unformatted]))
                $used[$item->booked_time_unformatted]++;
            else
                $used[$item->booked_time_unformatted] = 1;
        $frommark = date("Y-m-d", strtotime($from));
        while ($frommark < $to)
        {
            $times = cpabc_get_slots_for (CP_CALENDAR_ID , $frommark);
            foreach($times as $item)
                if (!isset($used[$frommark." ".$item["time"].":00"]) || $used[$frommark." ".$item["time"].":00"] < $item["capacity"])
                {
                    $count_slots = ($item["capacity"]?$item["capacity"]:1) - $used[$frommark." ".$item["time"].":00"];
                    for ($k=0;$k<$count_slots; $k++)
                        $events[] = (object) [ 
                                                   'buffered_date' => serialize(array('DATE' => date($format, strtotime($frommark)), 'DATE' => $frommark, 'TIME' => $item["time"])),
                                                   'uname' => '',
                                                   'booked_time_unformatted' => $frommark." ".$item["time"].":00",
                                                   'datatime' => $frommark." ".$item["time"].":00",
                                                 ];
                }
            $frommark = date("Y-m-d", strtotime($frommark." +1 day"));
        }
        usort($events, function ($a, $b) { return ($a->booked_time_unformatted < $b->booked_time_unformatted) ? -1 : 1; } );
    }
    
    $fields = array();
    if (!in_array("Calendar ID",$excluded)) $fields[] = "Calendar ID";
    if (!in_array("Calendar",$excluded)) $fields[] = "Calendar";
    if (!in_array("Time",$excluded)) $fields[] = "Time";
    if (!in_array("Itemnumber",$excluded)) $fields[] = "Itemnumber";
    $values = array();

    foreach ($events as $item)
    {
        $value = array();
        if (!in_array("Calendar ID",$excluded)) $value[] = $item->appointment_calendar_id;
        if (!in_array("Calendar",$excluded)) $value[] = $item->uname;
        if (!in_array("Time",$excluded)) $value[] = $item->datatime;
        if (!in_array("Itemnumber",$excluded)) $value[] = $item->itemnumber;

        $fieldsstart = !in_array("Calendar ID",$excluded) + !in_array("Calendar",$excluded) + !in_array("Time",$excluded) + !in_array("Itemnumber",$excluded);
        
        $data = array();
        $data = unserialize($item->buffered_date);

        if (!is_array($data))
        {
            $data = array(
              'title' => $item->title,
              'description' => $item->description
            );
        }
        $end = count($fields);
        for ($i=$fieldsstart; $i<$end; $i++)
            if (isset($data[$fields[$i]]) ){
                $value[$i] = $data[$fields[$i]];
                unset($data[$fields[$i]]);
            }
            else $value[$i] = '';
        foreach ($data as $k => $d)
            if (!in_array($k,$excluded))
            {
               $fields[] = $k;
               $value[] = $d;
            }
        $values[] = $value;
    }

    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=export.csv");

    for ($i=0; $i<count($fields)-1; $i++)
        for ($j=$i+1; $j<count($fields); $j++)
            if ((cpabc_appointments_get_field_name($fields[$i],@$form_data[0])) == (cpabc_appointments_get_field_name($fields[$j],@$form_data[0])))
            {
                for ($l=0; $l<count($values); $l++ )
                {
                    if (!isset($values[$l][$i]) || $values[$l][$i] == '')
                        $values[$l][$i] = $values[$l][$j];
                     array_splice($values[$l], $j, 1);
                }
               array_splice($fields, $j, 1);
               $j--;
            }
       
    $end = count($fields);
    for ($i=0; $i<$end; $i++)
    {
        $hlabel = cpabc_appointments_iconv("utf-8", "ISO-8859-1//TRANSLIT//IGNORE", cpabc_appointments_get_field_name($fields[$i],@$form_data[0]));
        echo '"'.str_replace('"','""', $hlabel).'",';
    }
    echo "\n";
    foreach ($values as $item)
    {
        for ($i=0; $i<$end; $i++)
        {
            if (!isset($item[$i]))
                $item[$i] = '';
            if (is_array($item[$i]))
                $item[$i] = implode($item[$i],',');
            $item[$i] = cpabc_appointments_iconv("utf-8", "ISO-8859-1//TRANSLIT//IGNORE", $item[$i]);
            echo '"'.str_replace('"','""', $item[$i]).'",';
        }
        echo "\n";
    }

    exit;
}


function cpabc_appointments_iconv($from, $to, $text)
{
    if (function_exists('iconv'))
        return iconv($from, $to, $text);
    else
        return $text;
}


function cpabc_appointments_check_reminders() {
    global $wpdb;

    cpabc_appointments_add_field_verify(CPABC_TDEAPP_CALENDAR_DATA_TABLE, 'fu_reminder');

    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'fu_nremind_emailformat');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'fu_reminder_subject');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'fu_reminder_content');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'enable_fu_reminder');
    cpabc_appointments_add_field_verify(CPABC_APPOINTMENTS_CONFIG_TABLE_NAME, 'fu_reminder_hours');
    cpabc_appointments_add_field_verify($wpdb->prefix.CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME_NO_PREFIX, 'is_cancelled', "VARCHAR(50) DEFAULT '0' NOT NULL");

    // INITIAL BLOCK: REMINDER
    // *********************************************************************

    $query = "SELECT ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME.".id as formid,nremind_emailformat,notification_from_email,description_customer,reminder_subject,reminder_content,uname,".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".* FROM ".
              CPABC_TDEAPP_CALENDAR_DATA_TABLE." INNER JOIN ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME." ON ".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".appointment_calendar_id=".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME.".id ".
              " WHERE (".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".who_added<>'-1') AND ((is_cancelled<>'1') OR is_cancelled is null) AND enable_reminder=1 AND reminder<>'1' AND datatime<DATE_ADD(now(),INTERVAL reminder_hours HOUR) AND datatime>'".date("Y-m-d H:i:s")."'";
    $apps = $wpdb->get_results( $query);
    foreach ($apps as $app) {
        // mark as sent
        $wpdb->query("UPDATE ".CPABC_TDEAPP_CALENDAR_DATA_TABLE." SET reminder='1' WHERE id=".$app->id);
    }
    foreach ($apps as $app) {
        // send email
        if ('html' == $app->nremind_emailformat) $content_type = "Content-Type: text/html; charset=utf-8\n"; else $content_type = "Content-Type: text/plain; charset=utf-8\n";
        $email_content = str_replace('%INFORMATION%',str_replace('<br />',"\n",$app->description_customer),$app->reminder_content);

        $cancel_link = cpabc_appointment_get_FULL_site_url().'/?cpabc_c=1&i='.base64_encode($app->id).'&a=1';
        $email_content = str_replace('%CANCEL%', $cancel_link, $email_content);

        $app_source = $wpdb->get_results( "SELECT buffered_date FROM ".CPABC_APPOINTMENTS_TABLE_NAME." WHERE id='".$app->reference."'");
        $params = unserialize($app_source[0]->buffered_date);
        foreach ($params as $item => $value)
        {
            $email_content = str_replace('<%'.$item.'%>',(is_array($value)?(implode(", ",$value)):($value)),$email_content);
            $email_content = str_replace('%'.$item.'%',(is_array($value)?(implode(", ",$value)):($value)),$email_content);
        }
        $email_content = str_replace("%CALENDAR%", $app->uname, $email_content);

        $SYSTEM_EMAIL = $app->notification_from_email;
        $pos = strpos($SYSTEM_EMAIL, "<");
        if ($pos === false)
            $SYSTEM_EMAIL = '"'.$SYSTEM_EMAIL.'" <'.$SYSTEM_EMAIL.'>';

        if ( CPABC_ENABLE_CUSTOMER_EMAILS && strpos($app->title,'@') )        
            wp_mail(strtolower($app->title), $app->reminder_subject, $email_content,
                "From: ".$SYSTEM_EMAIL."\r\n".
                $content_type.
                "X-Mailer: PHP/" . phpversion());
                
        // trigger sms action
        do_action( 'cpabc_smssend', array('params' => $params, 'formid' => $app->formid, 'content' => $email_content) );   

        if (CPABC_APPOINTMENTS_SEND_REMINDER_ADMIN)
        {
            $SYSTEM_RCPT_EMAIL = cpabc_get_option('notification_destination_email', _cpabc_appointments_get_default_paypal_email(), $app->formid);
            $to = explode(",",$SYSTEM_RCPT_EMAIL);
            foreach ($to as $item)
                 if (trim($item) != '')
                 {
                     wp_mail(strtolower(trim($item)), "Copy: ".$app->reminder_subject, $email_content,
                       "From: ".$SYSTEM_EMAIL."\r\n".
                       $content_type.
                       "X-Mailer: PHP/" . phpversion());
                 }
        }        
    }


    // SECOND BLOCK: FOLLOW UP
    // *********************************************************************

    $query = "SELECT ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME.".id as formid,".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME.".fu_nremind_emailformat,notification_from_email,description_customer,".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME.".fu_reminder_subject,".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME.".fu_reminder_content,uname,".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".* FROM ".
              CPABC_TDEAPP_CALENDAR_DATA_TABLE." INNER JOIN ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME." ON ".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".appointment_calendar_id=".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME.".id ".
              " WHERE (".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".who_added<>'-1') AND((is_cancelled<>'1') OR is_cancelled is null) AND ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME.".enable_fu_reminder=1 AND ((fu_reminder<>'1') OR fu_reminder is null) AND now()>DATE_ADD(datatime,INTERVAL ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME.".fu_reminder_hours HOUR) AND now()<DATE_ADD(datatime,INTERVAL 3600 HOUR)"; // 360 hours = 15 days

    $apps = $wpdb->get_results( $query);
    foreach ($apps as $app) {
        // mark as sent
        $wpdb->query("UPDATE ".CPABC_TDEAPP_CALENDAR_DATA_TABLE." SET fu_reminder='1' WHERE id=".$app->id);
    }
    foreach ($apps as $app) {
        // send email
        if ('html' == $app->fu_nremind_emailformat) $content_type = "Content-Type: text/html; charset=utf-8\n"; else $content_type = "Content-Type: text/plain; charset=utf-8\n";
        $email_content = str_replace('%INFORMATION%',str_replace('<br />',"\n",$app->description_customer),$app->fu_reminder_content);

        $app_source = $wpdb->get_results( "SELECT buffered_date FROM ".CPABC_APPOINTMENTS_TABLE_NAME." WHERE id=".$app->reference);
        $params = unserialize($app_source[0]->buffered_date);
        foreach ($params as $item => $value)
        {
            $email_content = str_replace('<%'.$item.'%>',(is_array($value)?(implode(", ",$value)):($value)),$email_content);
            $email_content = str_replace('%'.$item.'%',(is_array($value)?(implode(", ",$value)):($value)),$email_content);
        }

        $SYSTEM_EMAIL = $app->notification_from_email;
        $pos = strpos($SYSTEM_EMAIL, "<");
        if ($pos === false)
            $SYSTEM_EMAIL = '"'.$SYSTEM_EMAIL.'" <'.$SYSTEM_EMAIL.'>';

        $email_content = str_replace("%CALENDAR%", $app->uname, $email_content);
        if (CPABC_ENABLE_CUSTOMER_EMAILS && strpos($app->title,'@') )
            wp_mail(strtolower($app->title), $app->fu_reminder_subject, $email_content,
                "From: ".$SYSTEM_EMAIL."\r\n".
                $content_type.
                "X-Mailer: PHP/" . phpversion());
                
        // trigger sms action
        do_action( 'cpabc_smssend', array('params' => $params, 'formid' => $app->formid, 'content' => $email_content) );         

        if (CPABC_APPOINTMENTS_SEND_REMINDER_ADMIN)
        {
            $SYSTEM_RCPT_EMAIL = cpabc_get_option('notification_destination_email', _cpabc_appointments_get_default_paypal_email(), $app->formid);
            $to = explode(",",$SYSTEM_RCPT_EMAIL);
            foreach ($to as $item)
                 if (trim($item) != '')
                 {
                     wp_mail(strtolower(trim($item)), "Copy: ".$app->fu_reminder_subject, $email_content,
                    "From: ".$SYSTEM_EMAIL."\r\n".
                    $content_type.
                    "X-Mailer: PHP/" . phpversion());
                 }
        }
    }

}


function cpabc_get_slot_capacity ($calid, $time) {
    global $wpdb;
    $capacity = -1;  // 1 is default capacity
    $query = "SELECT * FROM ".CPABC_TDEAPP_CONFIG." where ".CPABC_TDEAPP_CONFIG_ID."='".esc_sql($calid)."'";
    $row = $wpdb->get_results($query,ARRAY_A);
    if ($row[0] && $row[0]["master"] != '0' && $row[0]["master"] != '')
    {
        $query = "SELECT * FROM ".CPABC_TDEAPP_CONFIG." where ".CPABC_TDEAPP_CONFIG_ID."='".esc_sql($row[0]["master"])."'";
        $row_master = $wpdb->get_results($query,ARRAY_A);
        if ($row_master[0]) $row = $row_master;
    }
    
    if ($row[0])
    {
        //$time = "2010-11-15 15:00";
        $hour = date("G",strtotime($time));
        $min = date("i",strtotime($time));
        $weekday = date("w",strtotime($time));
        if (strlen($min) == 2 && $min[0] == '0')
            $min = substr($min,1);
        $needle =  $hour.":".$min.":";
        $needle2 =  $hour.":".$min.",";

        $specialFormat = date("n/j/Y",strtotime($time));
        if ($pos = strpos(" ".$row[0]["specialDates"],$specialFormat))
        {
            $haystack = substr($row[0]["specialDates"], $pos-1);
            $haystack = substr($haystack, 0,  strpos($haystack,";")).",";
        }
        else
            $haystack = $row[0]["timeWorkingDates".$weekday].",";

        $pos = strpos($haystack, $needle);
        if ($pos !== false) {
           $haystack = substr($haystack,$pos+strlen($needle));
           $haystack = substr($haystack,0,strpos($haystack,","));
           if (is_numeric($haystack))
               $capacity = intval($haystack);
        }
        else
        {
            $pos = strpos($haystack, $hour.":".$min);     // for compatibility with free version
            if ($pos !== false) $capacity = 1;
        }
    }
    return $capacity;
}


function cpabc_get_slots_for ($calid, $time) {
    global $wpdb;    
    $rawtimes = array();
    $query = "SELECT * FROM ".CPABC_TDEAPP_CONFIG." where ".CPABC_TDEAPP_CONFIG_ID."='".esc_sql($calid)."'";
    $row = $wpdb->get_results($query,ARRAY_A);
    if ($row[0])
    {
        $weekday = date("w",strtotime($time));
        
        $specialFormat = date("n/j/Y",strtotime($time));
        
        $restrictedDates = ' ,'.$row[0]["restrictedDates"].',';
        
        if ($pos = strpos($restrictedDates, ",".$specialFormat.","))
            $haystack = '';
        else if ($pos = strpos(" ".$row[0]["specialDates"],$specialFormat))
        {
            $haystack = substr($row[0]["specialDates"], $pos-1);
            $haystack = substr($haystack, 0,  strpos($haystack,";"));      
            $haystack = substr($haystack, strpos($haystack,",")+1);            
        }
        else
            $haystack = $row[0]["timeWorkingDates".$weekday];  
        if (trim($haystack))
            $rawtimes = explode(",", $haystack);
        for($i=0; $i<count($rawtimes); $i++)
        {
            //$rawtimes[$i] = substr($rawtimes[$i], 0, strrpos($rawtimes[$i],":"));
            $portions = explode(":",$rawtimes[$i]);            
            if (strlen($portions[0]) == 1) 
                $portions[0] = "0".$portions[0];
            if (strlen($portions[1]) == 1) 
                $portions[1] = "0".$portions[1];
            $rawtimes[$i] = array();
            $rawtimes[$i]["time"] = $portions[0].":".$portions[1]; 
            $rawtimes[$i]["capacity"] = $portions[2];
        }
    }
    return $rawtimes;
}


add_action( 'plugins_loaded', 'cpabc_appointments_calendar_load', 11 );
add_action( 'plugins_loaded', 'cpabc_appointments_calendar_load2', 11 );
add_action( 'plugins_loaded', 'cpabc_appointments_calendar_update', 11 );
add_action( 'plugins_loaded', 'cpabc_appointments_calendar_update2', 11 );

function cpabc_appointments_calendar_load() {
    global $wpdb;
	if ( ! isset( $_GET['cpabc_calendar_load'] ) || $_GET['cpabc_calendar_load'] != '1' )
		return;
    //@ob_clean();
    @header("Cache-Control: no-store, no-cache, must-revalidate");
    @header("Pragma: no-cache");
    $calid = intval(str_replace  (CPABC_TDEAPP_CAL_PREFIX, "",$_GET["id"]));
    $query = "SELECT * FROM ".CPABC_TDEAPP_CONFIG." where ".CPABC_TDEAPP_CONFIG_ID."='".esc_sql($calid)."'";
    $row = $wpdb->get_results($query,ARRAY_A);
    if ($row[0] && $row[0]["master"] != '0' && $row[0]["master"] != '')
    {
        $query = "SELECT * FROM ".CPABC_TDEAPP_CONFIG." where ".CPABC_TDEAPP_CONFIG_ID."='".esc_sql($row[0]["master"])."'";
        $row_master = $wpdb->get_results($query,ARRAY_A);
        if ($row_master[0]) $row = $row_master;
    }
    if ($row[0])
    {
        // New header to mark init of calendar output
        echo '--***--***--***---!';
        // START:: new code to clean corrupted data
        $working_dates = explode(",",$row[0][CPABC_TDEAPP_CONFIG_WORKINGDATES]);
        for($i=0;$i<count($working_dates); $i++)
            if (is_numeric($working_dates[$i]))
                $working_dates[$i] = intval($working_dates[$i]);
            else
                $working_dates[$i] = '';
        if ($working_dates[0] === '')
            unset($working_dates[0]);
        $working_dates = array_unique($working_dates);
        $working_dates = implode(",",$working_dates);
        while (!(strpos($working_dates,",,") === false))
            $working_dates = str_replace(",,",",",$working_dates);
        if ($working_dates[strlen($working_dates)-1] == ',')
            $working_dates = substr($working_dates,0,strlen($working_dates)-1);
        $buffer = $working_dates.";";
        // END:: new code to clean corrupted data
        $buffer .= $row[0][CPABC_TDEAPP_CONFIG_RESTRICTEDDATES].";";
        $buffer .= $row[0][CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES0].";";
        $buffer .= $row[0][CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES1].";";
        $buffer .= $row[0][CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES2].";";
        $buffer .= $row[0][CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES3].";";
        $buffer .= $row[0][CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES4].";";
        $buffer .= $row[0][CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES5].";";
        $buffer .= $row[0][CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES6].";";
        $buffer .= $row[0]["specialDates"];
        
        $buffer = apply_filters( 'cpabc_available_slots', $buffer, $calid );
        echo $buffer;
    }

    exit();
}

function cpabc_appointments_calendar_load2() {
    global $wpdb;
	if ( ! isset( $_GET['cpabc_calendar_load2'] ) || $_GET['cpabc_calendar_load2'] != '1' )
		return;
    //@ob_clean();
    header("Cache-Control: no-store, no-cache, must-revalidate");
    header("Pragma: no-cache");
    $calid = str_replace  (CPABC_TDEAPP_CAL_PREFIX, "",$_GET["id"]);

    // identify master calendar
    $master = $calid;
    $query = "SELECT * FROM ".CPABC_TDEAPP_CONFIG." where ".CPABC_TDEAPP_CONFIG_ID."='".esc_sql($calid)."'";
    $row = $wpdb->get_results($query,ARRAY_A);
    if ($row[0] && $row[0]["master"] != '0' && $row[0]["master"] != '')
    {
        $query = "SELECT * FROM ".CPABC_TDEAPP_CONFIG." where ".CPABC_TDEAPP_CONFIG_ID."='".esc_sql($row[0]["master"])."'";
        $row_master = $wpdb->get_results($query,ARRAY_A);
        if ($row_master[0])
            $master = $row[0]["master"];
    }

    // get all the calendars sharing this master calendar
    $bquery = '';
    $query = "SELECT ".CPABC_TDEAPP_CONFIG_ID." FROM ".CPABC_TDEAPP_CONFIG." where  master='".esc_sql($master)."' OR ".CPABC_TDEAPP_CONFIG_ID."='".esc_sql($master)."'";
    $row = $wpdb->get_results($query,ARRAY_A);
    foreach ($row as $item)
        $bquery .= " OR ".CPABC_TDEAPP_DATA_IDCALENDAR."='".esc_sql($item[CPABC_TDEAPP_CONFIG_ID])."'";


    $query = "SELECT * FROM ".CPABC_TDEAPP_CALENDAR_DATA_TABLE." where 1=0".$bquery;
    $row_array = $wpdb->get_results($query,ARRAY_A);
    
    if (isset($_GET["cpabc_action"]) && $_GET["cpabc_action"] == 'mvparse' && is_admin())
    {
        $ret = array();
        $ret['events'] = array();
        $ret["issort"] = true;
        $ret['error'] = null;
        $d1 = cpabc_js2PhpTime($_POST["startdate"]);
        $d2 = cpabc_js2PhpTime($_POST["enddate"]);
        $d1 = mktime(0, 0, 0,  date("m", $d1), date("d", $d1), date("Y", $d1));
        $d2 = mktime(0, 0, 0, date("m", $d2), date("d", $d2), date("Y", $d2))+24*60*60-1;
        $ret["start"] = cpabc_php2JsTime($d1);
        $ret["end"] = cpabc_php2JsTime($d2);
        
        define('CPABC_CAL_TIME_SLOT_SIZE'," +".get_option('CPABC_CAL_TIME_SLOT_SIZE_SET',"30")." minutes");
        
        foreach ($row_array as $row)
        {
            //if ($ret["start"] == '' || $ret["start"] > strtotime($row[CPABC_TDEAPP_DATA_DATETIME]))
            //    $ret["start"] = strtotime($row[CPABC_TDEAPP_DATA_DATETIME]);
            //if ($ret["end"] == '' || $ret["end"] < strtotime($row[CPABC_TDEAPP_DATA_DATETIME]))
            //    $ret["end"] = strtotime($row[CPABC_TDEAPP_DATA_DATETIME]);
            $ev = array(
                $row["id"],
                $row[CPABC_TDEAPP_DATA_TITLE],
                cpabc_php2JsTime(cpabc_mySql2PhpTime($row[CPABC_TDEAPP_DATA_DATETIME])),
                cpabc_php2JsTime(cpabc_mySql2PhpTime( date("Y-m-d H:i",strtotime($row[CPABC_TDEAPP_DATA_DATETIME].CPABC_CAL_TIME_SLOT_SIZE)))),
                0, // is  all day event?
                0, // more than one day event
                '',//Recurring event rule,
                '#3CF',
                0,//editable
                '',
                '',//$attends
                $row[CPABC_TDEAPP_DATA_DESCRIPTION],
                '',
                1
            );
            $ret['events'][] = $ev;
        }
        echo json_encode($ret);
        exit;
    }
    
    foreach ($row_array as $row)
    if (@$row["is_cancelled"] != '1')
    {
        echo $row[CPABC_TDEAPP_DATA_ID]."\n";
        $dn =  explode(" ", $row[CPABC_TDEAPP_DATA_DATETIME]);
        $d1 =  explode("-", $dn[0]);
        $d2 =  explode(":", $dn[1]);

        echo intval($d1[0]).",".intval($d1[1]).",".intval($d1[2])."\n";
        echo intval($d2[0]).":".($d2[1])."\n";
        echo ($row["quantity"]?$row["quantity"]:'1')."\n";
        if (is_admin())
        {
            echo $row[CPABC_TDEAPP_DATA_TITLE]."\n";
            echo $row[CPABC_TDEAPP_DATA_DESCRIPTION]."\n*-*\n";
        }
        else
        {
            echo "Booked\n";
            echo "OK\n*-*\n";
        }
    }

    exit();
}


function cpabc_js2PhpTime($jsdate){
  if(preg_match('@(\d+)/(\d+)/(\d+)\s+(\d+):(\d+)((am|pm)*)@', $jsdate, $matches)==1){
    if ($matches[6]=="pm")
        if ($matches[4]<12)
            $matches[4] += 12;
    $ret = mktime($matches[4], $matches[5], 0, $matches[1], $matches[2], $matches[3]);
  }else if(preg_match('@(\d+)/(\d+)/(\d+)@', $jsdate, $matches)==1){
    $ret = mktime(0, 0, 0, $matches[1], $matches[2], $matches[3]);
  }
  return $ret;
}


function cpabc_php2MySqlTime($phpDate){
    return date("Y-m-d H:i:s", $phpDate);
}


function cpabc_php2JsTime($phpDate){
    return @date("m/d/Y H:i", $phpDate);
}


function cpabc_mySql2PhpTime($sqlDate){
    $a1 = explode (" ",$sqlDate);
    $a2 = explode ("-",$a1[0]);
    $a3 = explode (":",$a1[1]);
    $t = mktime($a3[0],$a3[1],$a3[2],$a2[1],$a2[2],$a2[0]);
    return $t;
}


function cpabc_appointments_calendar_update() {
    global $wpdb, $user_ID;

	if ( ! isset( $_GET['cpabc_calendar_update'] ) || $_GET['cpabc_calendar_update'] != '1' )
		return;

    $calid = intval(str_replace  (CPABC_TDEAPP_CAL_PREFIX, "",$_GET["id"]));
    if ( ! current_user_can('edit_pages') && !cpabc_appointments_user_access_to($calid) )
        return;

    cpabc_appointments_add_field_verify(CPABC_TDEAPP_CONFIG, 'specialDates');

    //@ob_clean();
    header("Cache-Control: no-store, no-cache, must-revalidate");
    header("Pragma: no-cache");
    if ( $user_ID )
        $wpdb->query("update  ".CPABC_TDEAPP_CONFIG." set specialDates='".esc_sql($_POST["specialDates"])."',".CPABC_TDEAPP_CONFIG_WORKINGDATES."='".esc_sql($_POST["workingDates"])."',".CPABC_TDEAPP_CONFIG_RESTRICTEDDATES."='".esc_sql($_POST["restrictedDates"])."',".CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES0."='".esc_sql($_POST["timeWorkingDates0"])."',".CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES1."='".esc_sql($_POST["timeWorkingDates1"])."',".CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES2."='".esc_sql($_POST["timeWorkingDates2"])."',".CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES3."='".esc_sql($_POST["timeWorkingDates3"])."',".CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES4."='".esc_sql($_POST["timeWorkingDates4"])."',".CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES5."='".esc_sql($_POST["timeWorkingDates5"])."',".CPABC_TDEAPP_CONFIG_TIMEWORKINGDATES6."='".esc_sql($_POST["timeWorkingDates6"])."'  where ".CPABC_TDEAPP_CONFIG_ID."=".$calid);

    exit();
}

function cpabc_appointments_calendar_update2() {
    global $wpdb, $user_ID;

	if ( ! isset( $_GET['cpabc_calendar_update2'] ) || $_GET['cpabc_calendar_update2'] != '1' )
		return;

    $calid = intval(str_replace  (CPABC_TDEAPP_CAL_PREFIX, "",$_GET["id"]));
    if ( ! current_user_can('edit_pages') && !cpabc_appointments_user_access_to($calid) )
        return;

    //@ob_clean();
    header("Cache-Control: no-store, no-cache, must-revalidate");
    header("Pragma: no-cache");
    if ( $user_ID )
    {
        if ($_GET["act"]=='del')
            $wpdb->query("delete from ".CPABC_TDEAPP_CALENDAR_DATA_TABLE." where ".CPABC_TDEAPP_DATA_IDCALENDAR."=".$calid." and ".CPABC_TDEAPP_DATA_ID."=".$_POST["sqlId"]);
        else if ($_GET["act"]=='edit')
        {
            $data = explode("\n", $_POST["appoiments"]);
            $d1 =  explode(",", $data[0]);
            $d2 =  explode(":", $data[1]);
	        $datetime = $d1[0]."-".$d1[1]."-".$d1[2]." ".$d2[0].":".$d2[1];
	        $capacity = $data[2];
	        $title = $data[3];
            $description = "";
            for ($j=4;$j<count($data);$j++)
            {
                $description .= $data[$j];
                if ($j!=count($data)-1)
                    $description .= "\n";
            }
            // ,".CPABC_TDEAPP_DATA_TITLE."='".esc_sql($title)."',".CPABC_TDEAPP_DATA_DESCRIPTION."='".esc_sql($description)."'
            $wpdb->query("update  ".CPABC_TDEAPP_CALENDAR_DATA_TABLE." set ".CPABC_TDEAPP_DATA_DATETIME."='".$datetime."',quantity='".$capacity."' where ".CPABC_TDEAPP_DATA_IDCALENDAR."=".$calid." and ".CPABC_TDEAPP_DATA_ID."=".$_POST["sqlId"]);
        }
        else if ($_GET["act"]=='add')
        {
            $data = explode("\n", $_POST["appoiments"]);
            $d1 =  explode(",", $data[0]);
            $d2 =  explode(":", $data[1]);
	        $datetime = $d1[0]."-".$d1[1]."-".$d1[2]." ".$d2[0].":".$d2[1];
	        $capacity = $data[2];
	        $title = $data[3];
            $description = "";
            for ($j=4;$j<count($data);$j++)
            {
                $description .= $data[$j];
                if ($j!=count($data)-1)
                    $description .= "\n";
            }
            $wpdb->query("insert into ".CPABC_TDEAPP_CALENDAR_DATA_TABLE."(".CPABC_TDEAPP_DATA_IDCALENDAR.",".CPABC_TDEAPP_DATA_DATETIME.",".CPABC_TDEAPP_DATA_TITLE.",".CPABC_TDEAPP_DATA_DESCRIPTION.",quantity) values(".$calid.",'".$datetime."','".esc_sql($title)."','".esc_sql($description)."','".$capacity."') ");
            echo  $wpdb->insert_id;

        }
    }

    exit();
}

function cpabc_appointment_cleanJSON($str)
{
    $str = str_replace('&qquot;','"',$str);
    $str = str_replace('	',' ',$str);
    $str = str_replace("\n",'\n',$str);
    $str = str_replace("\r",'',$str);
    return $str;
}

function cpabc_appointment_translate_json($str)
{
    $form_data = json_decode($str);      
    
    $form_data[1][0]->title = __($form_data[1][0]->title,'cpabc');   
    $form_data[1][0]->description = __($form_data[1][0]->description,'cpabc');   
          
    for ($i=0; $i < count($form_data[0]); $i++)    
    {
        $form_data[0][$i]->title = __($form_data[0][$i]->title,'cpabc');   
        $form_data[0][$i]->userhelpTooltip = __($form_data[0][$i]->userhelpTooltip,'cpabc'); 
        $form_data[0][$i]->userhelp = __($form_data[0][$i]->userhelp,'cpabc'); 
        if ($form_data[0][$i]->ftype == 'fCommentArea')
            $form_data[0][$i]->userhelp = __($form_data[0][$i]->userhelp,'cpabc');   
        else 
            if ($form_data[0][$i]->ftype == 'fradio' || $form_data[0][$i]->ftype == 'fcheck' || $form_data[0][$i]->ftype == 'fradio')    
            {
                for ($j=0; $j < count($form_data[0][$i]->choices); $j++)  
                    $form_data[0][$i]->choices[$j] = __($form_data[0][$i]->choices[$j],'cpabc'); 
            } 
    }    
    $str = json_encode($form_data);
    return $str;
}

function cpabc_appointment_available_templates(){
	global $CP_ABC_global_templates;

	if( empty( $CP_ABC_global_templates ) )
	{
		// Get available designs
		$tpls_dir = dir( plugin_dir_path( __FILE__ ).'templates' );
		$CP_ABC_global_templates = array();
		while( false !== ( $entry = $tpls_dir->read() ) )
		{
			if ( $entry != '.' && $entry != '..' && is_dir( $tpls_dir->path.'/'.$entry ) && file_exists( $tpls_dir->path.'/'.$entry.'/config.ini' ) )
			{
				if( ( $ini_array = parse_ini_file( $tpls_dir->path.'/'.$entry.'/config.ini' ) ) !== false )
				{
					if( !empty( $ini_array[ 'file' ] ) ) $ini_array[ 'file' ] = plugins_url( 'templates/'.$entry.'/'.$ini_array[ 'file' ], __FILE__ );
					if( !empty( $ini_array[ 'thumbnail' ] ) ) $ini_array[ 'thumbnail' ] = plugins_url( 'templates/'.$entry.'/'.$ini_array[ 'thumbnail' ], __FILE__ );
					$CP_ABC_global_templates[ $ini_array[ 'prefix' ] ] = $ini_array;
				}
			}
		}
	}

	return $CP_ABC_global_templates;
}

function cpabc_get_captcha_params()
{
    $str = '&inAdmin=1';
    $tmp = cpabc_get_option('dexcv_width', CPABC_TDEAPP_DEFAULT_dexcv_width);
    if ($tmp != CPABC_TDEAPP_DEFAULT_dexcv_width)  $str .='&width='.$tmp;
    
    $tmp = cpabc_get_option('dexcv_height', CPABC_TDEAPP_DEFAULT_dexcv_height);
    if ($tmp != CPABC_TDEAPP_DEFAULT_dexcv_height) $str .='&height='.$tmp;
    
    $tmp = cpabc_get_option('dexcv_chars', CPABC_TDEAPP_DEFAULT_dexcv_chars);
    if ($tmp != CPABC_TDEAPP_DEFAULT_dexcv_chars) $str .='&letter_count='.$tmp;
    
    $tmp = cpabc_get_option('dexcv_min_font_size', CPABC_TDEAPP_DEFAULT_dexcv_min_font_size);
    if ($tmp != CPABC_TDEAPP_DEFAULT_dexcv_min_font_size) $str .='&min_size='.$tmp;
    
    $tmp = cpabc_get_option('dexcv_max_font_size', CPABC_TDEAPP_DEFAULT_dexcv_max_font_size);
    if ($tmp != CPABC_TDEAPP_DEFAULT_dexcv_max_font_size) $str .='&max_size='.$tmp;
    
    $tmp = cpabc_get_option('dexcv_noise', CPABC_TDEAPP_DEFAULT_dexcv_noise);
    if ($tmp != CPABC_TDEAPP_DEFAULT_dexcv_noise) $str .='&noise='.$tmp;
    
    $tmp = cpabc_get_option('dexcv_noise_length', CPABC_TDEAPP_DEFAULT_dexcv_noise_length);
    if ($tmp != CPABC_TDEAPP_DEFAULT_dexcv_noise_length) $str .='&noiselength='.$tmp;
    
    $tmp = cpabc_get_option('dexcv_background', CPABC_TDEAPP_DEFAULT_dexcv_background);
    if ($tmp != CPABC_TDEAPP_DEFAULT_dexcv_background) $str .='&bcolor='.$tmp;
    
    $tmp = cpabc_get_option('dexcv_border', CPABC_TDEAPP_DEFAULT_dexcv_border);
    if ($tmp != CPABC_TDEAPP_DEFAULT_dexcv_border) $str .='&border='.$tmp;
    
    $tmp = cpabc_get_option('dexcv_font', CPABC_TDEAPP_DEFAULT_dexcv_font);
    if ($tmp != CPABC_TDEAPP_DEFAULT_dexcv_font) $str .='&font='.$tmp;
    
    return $str;    
}

function cpabc_auto_language($calendar_language)
{
    if ($calendar_language == '-')
    {
        $calendar_language = substr(strtoupper(get_bloginfo('language')),0,2);
        $calendar_language = str_replace ( array('ES','CS','NL','JA','KO','NB','SV',''), 
                                           array('SP','CZ','DU','JP','KR','NW','SE',''), $calendar_language);
    }
    return $calendar_language;
}


function cpabc_data_management_loaded() 
{
    global $wpdb, $cpabc_postURL;

    $action = @$_POST['cpabc_do_action_loaded'];
	if (!$action) return; // go out if the call isn't for this one

    if ($_POST['cpabc_publish_id']) $item = $_POST['cpabc_publish_id'];

    if ($action == "wizard")
    {
        $shortcode = '[CPABC_APPOINTMENT_CALENDAR calendar="'.$item .'"]';
        $cpabc_postURL = cpabc_publish_on($_POST["whereto"], $_POST["publishpage"], $_POST["publishpost"], $shortcode, $_POST["posttitle"]);            
        return;
    }

    // ...
    echo 'Some unexpected error happened. If you see this error contact the support service at https://bccf.dwbooster.com/contact-us';

    exit();
}    


function cpabc_publish_on($whereto, $publishpage = '', $publishpost = '', $content = '', $posttitle = 'Booking Form')
{
    global $wpdb;
    $id = '';
    if ($whereto == '0' || $whereto =='1') // new page
    {
        $my_post = array(
          'post_title'    => $posttitle,
          'post_type' => ($whereto == '0'?'page':'post'),
          'post_content'  => 'This is a <b>preview</b> page, remember to publish it if needed. You can edit the full form settings into the admin settings page.<br /><br /> '.$content,
          'post_status'   => 'draft'
        );
        
        // Insert the post into the database
        $id = wp_insert_post( $my_post );
    }
    else 
    {
        $id = ($whereto == '2'?$publishpage:$publishpost);
        $post = get_post( $id );
        $pos = strpos($post->post_content,$content);
        if ($pos === false)
        {
            $my_post = array(
                  'ID'           => $id,
                  'post_content' => $content.$post->post_content,
              );
            // Update the post into the database
            wp_update_post( $my_post );
        }
    }
    return get_permalink($id);
}


function cpabc_appointment_get_site_url($admin = false)
{
    $blog = get_current_blog_id();
    if( $admin )
        $url = get_admin_url( $blog );
    else
        $url = get_home_url( $blog );

    $url = parse_url($url);
    $url = rtrim(@$url["path"],"/");
    if (is_ssl())
        $url = str_replace('http://', 'https://', $url);    
    return $url;
}


function cpabc_appointment_get_FULL_site_url($admin = false)
{
    $blog = get_current_blog_id();
    if( $admin )
        $url = get_admin_url( $blog );
    else
        $url = get_home_url( $blog );

    $url = parse_url($url);
    $url = rtrim(@$url["path"],"/");
    $pos = strpos($url, "://");
    if ($pos === false)
        $url = 'http://'.$_SERVER["HTTP_HOST"].$url;
    if (is_ssl())
        $url = str_replace('http://', 'https://', $url);
    return $url;
}


// cpabc_cpabc_get_option:
$cpabc_option_buffered_item = false;
$cpabc_option_buffered_id = -1;

function cpabc_get_option ($field, $default_value = '', $id = '')
{
    global $wpdb, $cpabc_option_buffered_item, $cpabc_option_buffered_id;
    if ($id == '')
    {
        if (!defined('CP_CALENDAR_ID'))
            $id = 0;
        else 
            $id = CP_CALENDAR_ID;
    }
    if ($cpabc_option_buffered_id == $id)
        $value = @$cpabc_option_buffered_item->$field;
    else
    {

       $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_CONFIG_TABLE_NAME." WHERE id=".$id );
       $value = @$myrows[0]->$field;
       $cpabc_option_buffered_item = @$myrows[0];
       $cpabc_option_buffered_id  = $id;
    }
    if ($value == '' && @$cpabc_option_buffered_item->calendar_language == '')
        $value = $default_value;

    $value = apply_filters( 'cpabc_get_option', $value, $field, $id );

    return $value;
}

function cpabc_appointment_is_administrator()
{
    return current_user_can('manage_options');
}

// Auxiliar functions
// ***********************************************************************


function dex_cpabc_form_result( $atts, $content = "", $id = 0 )
	{
        @session_start();
		global $wpdb;

		if( $id == 0 && !empty( $_SESSION[ 'cp_cff_form_data' ] ) ) $id = $_SESSION[ 'cp_cff_form_data' ];
		if( !empty( $id ) )
		{
			$content = html_entity_decode( $content );
			$result = $wpdb->get_row( $wpdb->prepare( "SELECT form_settings.form_structure AS form_structure, form_data.question AS data, form_data.buffered_date AS paypal_post FROM ".$wpdb->prefix.CPABC_APPOINTMENTS_CONFIG_TABLE_NAME_NO_PREFIX." AS form_settings,".CPABC_APPOINTMENTS_TABLE_NAME." AS form_data WHERE form_data.id=%d AND form_data.calendar=form_settings.id", $id ) );

			if( !is_null( $result ) )
			{
				$atts = shortcode_atts( array( 'fields' => '' ), $atts );
				if( !empty( $atts[ 'fields' ] ) || !empty( $content ) )
				{
					$raw_form_str = cpabc_appointment_cleanJSON( $result->form_structure );
					$form_data = json_decode( $raw_form_str );

					if( is_null( $form_data ) )
					{
						$json = new JSON;
						$form_data = $json->unserialize( $raw_form_str );
					}
				}

				if( empty( $form_data ) )
				{
					return "<p>" . preg_replace( "/\n+/", "<br />", $result->data ) . "</p>";
				}
				else
				{
					$fields = array();
					foreach($form_data[0] as $item)
					{
						$fields[$item->name] = $item;
					}
					$fields[ 'ipaddr' ] = $_SERVER["REMOTE_ADDR"]; //$result->ipaddr;
					$result->paypal_post = unserialize( $result->paypal_post );
					$str = '';
					$atts[ 'fields' ] = explode( ",", str_replace( " ", "", $atts[ 'fields' ] ) );
					foreach( $atts[ 'fields' ] as $field )
					{
                        if( isset( $fields[ $field ] ) )
                        {
                            if( isset( $result->paypal_post[ $field ] ) )
                            {
                                if( is_array( $result->paypal_post[ $field ] ) ) $result->paypal_post[ $field ] = implode( ',', $result->paypal_post[ $field ] );
                                $str .= "<p>{$fields[ $field ]->title} {$result->paypal_post[ $field ]}</p>";
                            }
                            elseif( in_array( $fields[ $field ]->ftype, array( 'fSectionBreak' ) ) )
                            {
                                $str .= "<p><strong>".$fields[ $field ]->title."</strong>".(( !empty($fields[ $field ]->userhelp) ) ? "<br /><pan class='uh'>".$fields[ $field ]->userhelp."</span>" : '' )."</p>";
                            }
						}

					}

                    if( $content != '' )
                    {
	                    $replaced_values = _dex_cpabc_replace_vars( $fields, $result->paypal_post, $content, $result->data, 'html', $id );
	                    $str .= $replaced_values[ 'message' ];
                    }

					return $str;
				}
			}
		}

		return '';
	}


function _dex_cpabc_extract_tags( $message )
{
    $message = str_replace('% ','% '."\n".' ',$message);
    $message = str_replace(' %'," \n".' %',$message);
	$tags_arr = array();
	if(
		preg_match_all(	"/%(INFORMATION|fieldname\d+|fieldname\d+_label|fieldname\d+_shortlabel|fieldname\d+_value|fieldname\d+_url|fieldname\d+_urls|coupon|itemnumber|final_price|payment_option|CALENDAR|DATE|TIME|ALLDATES|COUPONCODE|payment_type|SERVICES|PRICE|QUANTITY|EMAIL|PHONE|COMMENTS|NAME|subject|message|ipaddress|currentdate_mmddyyyy|currentdate_ddmmyyyy)\b(?:(?!%>).)*%/i",
			$message,
			$matches
		)
	)
	{
		$tag = array();
		foreach( $matches[ 0 ] as $index => $value )
		{
			$tag[ 'node' ] = $value;
			$tag[ 'tag' ]  = strtolower( $matches[ 1 ][ $index ] );
			$tag[ 'if_not_empty' ] 	= preg_match( "/if_not_empty/i", $value );
			$tag[ 'before' ]    	= ( preg_match( "/before\s*=\s*\{\{((?:(?!\}\}).)*)\}\}/i",  $value, $match ) ) ? $match[ 1 ] : '';
			$tag[ 'after' ]   		= ( preg_match( "/after\s*=\s*\{\{((?:(?!\}\}).)*)\}\}/i", $value, $match ) ) ? $match[ 1 ] : '';
			$tag[ 'separator' ]    	= ( preg_match( "/separator\s*=\s*\{\{((?:(?!\}\}).)*)\}\}/i",  $value, $match ) ) ? $match[ 1 ] : '';

			$baseTag = ( preg_match( "/(fieldname\d+)_(label|value|shortlabel)/i", $tag[ 'tag' ], $match ) ) ? $match[ 1 ] : $tag[ 'tag' ];

			if( empty( $tags_arr[ $baseTag ] ) ) $tags_arr[ $baseTag ] = array();
			$tags_arr[ $baseTag ][] = $tag;
		}
	}
	return $tags_arr;
}

function _dex_cpabc_replace_vars( $fields, $params, $message, $buffer = '', $contentType = 'html', $itemnumber = '' )
{
    global $wpdb;
    
	// Lambda functions
	$arrayReplacementFunction = function ( &$tags, $tagName, $replacement, &$message ) { if(isset($tags[ $tagName ])){foreach( $tags[ $tagName ] as $tagData ){ $message = str_replace( $tagData[ "node" ], $tagData[ "before" ].$replacement.$tagData[ "after" ], $message );}unset( $tags[ $tagName ] );} };

	$singleReplacementFunction = function ( $tagData, $value, &$message ) { $message = str_replace( $tagData[ "node" ], $tagData[ "before" ].$value.$tagData[ "after" ],$message ); };

	$message = str_replace( '< %', '<%', $message );
    $attachments = array();    

	// Remove empty blocks
	while( preg_match( "/%\s*fieldname(\d+)_block\s*%/", $message, $matches ) )
	{
		if( empty( $params[ 'fieldname'.$matches[ 1 ] ] ) )
		{
			$from = strpos( $message, $matches[ 0 ] );
			if( preg_match( "/%\s*fieldname(".$matches[ 1 ].")_endblock\s*%/", $message, $matches_end ) )
			{
				$lenght = strpos( $message, $matches_end[ 0 ] ) + strlen( $matches_end[ 0 ] ) - $from;
			}
			else
			{
				$lenght = strlen( $matches[ 0 ] );
			}
			$message = substr_replace( $message, '', $from, $lenght );
		}
		else
		{
			$message = preg_replace( array( "/%\s*fieldname".$matches[ 1 ]."_block\s*%/", "/%\s*fieldname".$matches[ 1 ]."_endblock\s*%/"), "", $message );
		}
	}

	$tags = _dex_cpabc_extract_tags( $message );

	if ( 'html' == $contentType )
    {
        $message = str_replace( "\n", "", $message );
        $buffer = str_replace( array('&lt;', '&gt;', '\"', "\'"), array('<', '>', '"', "'" ), $buffer );
    }

	// Replace the INFO tags
    if( !empty( $tags[ 'information' ] ) )
	{
		$buffer1 = $buffer;
		do{
			$tmp = $buffer1;
			$buffer1 = preg_replace(
				array(
					"/^[^\n:]*:{1,2}\s*\n/",
					"/\n[^\n:]*:{1,2}\s*\n/",
					"/\n[^\n:]*:{1,2}\s*$/"
				),
				array(
					"",
					"\n",
					""
				),
				$buffer1
			);
		}while( $buffer1 <> $tmp );

		foreach( $tags[ 'information' ] as $tagData )
		{
			$singleReplacementFunction( $tagData, ( ( $tagData[ 'if_not_empty' ] ) ? $buffer1 : $buffer ), $message );
		}
		unset( $tags[ 'information' ] );
	}

    $params["alldates"] = '';
    for ($n=0;$n<count($_SESSION["cp_cff_form_data_all"]);$n++)
    {
       $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_TABLE_NAME." WHERE id=".intval($_SESSION["cp_cff_form_data_all"][$n]) );
       $params["alldates"] .= $myrows[0]->booked_time."\n";
    }       

	foreach ($params as $item => $value)
    {
		$value_bk = $value;
		if( isset( $tags[ strtolower($item) ] ) )
		{
			$label 		= ( isset( $fields[ $item ] ) && property_exists( $fields[ $item ], 'title' ) ) ? $fields[ $item ]->title : '';
			$shortlabel = ( isset( $fields[ $item ] ) && property_exists( $fields[ $item ], 'shortlabel' ) ) ? $fields[ $item ]->shortlabel : '';
			$value = ( !empty( $value ) || is_numeric( $value ) && $value == 0 ) ? ( ( is_array( $value ) ) ? implode( ", ", $value ) : $value ) : '';

			if ( 'html' == $contentType )
			{
				$label = str_replace( array('&lt;', '&gt;', '\"', "\'"), array('<', '>', '"', "'" ), $label );
				$shortlabel = str_replace( array('&lt;', '&gt;', '\"', "\'"), array('<', '>', '"', "'" ), $shortlabel );
				$value = str_replace( array('&lt;', '&gt;', '\"', "\'"), array('<', '>', '"', "'" ), $value );
			}

			foreach( $tags[ strtolower($item) ] as $tagData )
			{               
				if( $tagData[ 'if_not_empty' ] == 0 || $value !== '' )
				{
                    
					switch( strtolower($tagData[ 'tag' ]) )
					{
						case strtolower($item):
							$singleReplacementFunction( $tagData, $label.$tagData[ 'separator' ].$value, $message );
						break;
						case strtolower($item.'_label'):
							$singleReplacementFunction( $tagData, $label, $message );
						break;
						case strtolower($item.'_value'):
							$singleReplacementFunction( $tagData, $value, $message );
						break;
						case strtolower($item.'_shortlabel'):
							$singleReplacementFunction( $tagData, $shortlabel, $message );
						break;
					} 
				}
				else
				{                    
					$message = str_replace( $tagData[ 'node' ], '', $message );                  
				}
			}
			unset( $tags[ $item ] );
		}
        if( preg_match( "/_link\b/i", $item ) )
        {
            $attachments = array_merge( $attachments, $value_bk );
        }
    }

	$arrayReplacementFunction( $tags, 'itemnumber', $itemnumber, $message );
	$arrayReplacementFunction( $tags, 'currentdate_mmddyyyy', date("m/d/Y H:i:s"), $message );
	$arrayReplacementFunction( $tags, 'currentdate_ddmmyyyy', date("d/m/Y H:i:s"), $message );
	$arrayReplacementFunction( $tags, 'ipaddress', $fields[ 'ipaddr' ], $message );

    // Replace coupons code
	if( isset( $_REQUEST[ 'couponcode' ] ) && isset( $tags[ 'couponcode' ] ) )
    {
		$arrayReplacementFunction( $tags, 'couponcode', $_REQUEST[ 'couponcode' ], $message );
    }

	foreach( $tags as $tagArr )
    {
        foreach( $tagArr as $tagData )
		{
			$message = str_replace( $tagData[ 'node' ], '', $message );
		}
	}

    if ( 'html' == $contentType )
    {
        $message = str_replace( "\n", "<br>", $message );
    }
    $message = str_replace( '\\', '', stripslashes( stripcslashes( $message ) ) );

	return array( 'message' => $message, 'attachments' => $attachments );
}


// WIDGET CODE BELOW

class CPABC_App_Widget extends WP_Widget
{
  function __construct()
  {
    $widget_ops = array('classname' => 'CPABC_App_Widget', 'description' => 'Displays a booking form' );
    parent::__construct('CPABC_App_Widget', 'Appointment Booking Calendar', $widget_ops);
  }

  function form($instance)
  {
    $instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
    $title = $instance['title'];
?>
  <p><label for="<?php echo $this->get_field_id('title'); ?>">Title: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" /></label></p>
<?php
  }

  function update($new_instance, $old_instance)
  {
    $instance = $old_instance;
    $instance['title'] = $new_instance['title'];
    return $instance;
  }

  function widget($args, $instance)
  {
    extract($args, EXTR_SKIP);

    echo $before_widget;
    $title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);

    if (!empty($title))
      echo $before_title . $title . $after_title;;

    // WIDGET CODE GOES HERE
    define('CPABC_AUTH_INCLUDE', true);
    cpabc_appointments_get_public_form(false, true);

    echo $after_widget;
  }

}
add_action( 'widgets_init', function() { return register_widget("CPABC_App_Widget"); } );

// this filter has been applied to avoid problems with WP Rocket Optimizations
add_filter( 'rocket_exclude_js', 'cpabc_wprockert_exclude_js_minify' );
function cpabc_wprockert_exclude_js_minify( $js_files ) {
	$js_files[] = plugins_url('/TDE_AppCalendar/all-scripts.js', __FILE__);
	$js_files[] = plugins_url('/js/(.*).js', __FILE__);    
	return $js_files;
}

// elementor integration
include_once dirname( __FILE__ ) . '/controllers/elementor/cp-elementor-widget.inc.php';


?>