<?php                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 require_once dirname( __FILE__ ).'/base.addon.php';

if( !class_exists( 'CPABC_Clickatell' ) )
{
    class CPABC_Clickatell extends CPABC_BaseAddon
    {
        /************* ADDON SYSTEM - ATTRIBUTES AND METHODS *************/
		protected $addonID = "addon-clickatell-20170403";
		protected $name = "Clickatell";
		protected $description;

		public function get_addon_form_settings( $form_id )
		{
			global $wpdb;

			// Insertion in database
			if( isset( $_REQUEST[ 'cpabc_clickatell' ] ) )
			{
				$wpdb->delete( $wpdb->prefix.$this->form_clickatell_table, array( 'formid' => $form_id ), array( '%d' ) );

				$active = ($_REQUEST['cpabc_clickatell_active']) ? 1 : 0;

				$settings = array();
				if(isset($_REQUEST['cpabc_clickatell_sid'])) $settings['sid'] = trim($_REQUEST['cpabc_clickatell_sid']);
				if(isset($_REQUEST['cpabc_clickatell_auth'])) $settings['auth'] = trim($_REQUEST['cpabc_clickatell_auth']);
				if(isset($_REQUEST['cpabc_clickatell_from'])) $settings['from'] = trim($_REQUEST['cpabc_clickatell_from']);
				if(isset($_REQUEST['cpabc_clickatell_to_website'])) $settings['to_website'] = trim($_REQUEST['cpabc_clickatell_to_website']);
				if(isset($_REQUEST['cpabc_clickatell_to_users'])) $settings['to_users'] = trim($_REQUEST['cpabc_clickatell_to_users']);
				if(isset($_REQUEST['cpabc_clickatell_mssg_website'])) $settings['mssg_website'] = trim($_REQUEST['cpabc_clickatell_mssg_website']);
				if(isset($_REQUEST['cpabc_clickatell_mssg_users'])) $settings['mssg_users'] = trim($_REQUEST['cpabc_clickatell_mssg_users']);
                if(isset($_REQUEST['cpabc_clickatell_users_prefix'])) $settings['mssg_users_prefix'] = trim($_REQUEST['cpabc_clickatell_users_prefix']);

				$wpdb->insert(
					$wpdb->prefix.$this->form_clickatell_table,
					array(
						'formid' => $form_id,
						'active' => $active,
						'data'	 => serialize($settings)
					),
					array( '%d', '%d', '%s' )
				);
			}

			$row = $wpdb->get_row(
						$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_clickatell_table." WHERE formid=%d", $form_id )
					);

			if(!empty($row))
			{
				$active = $row->active;
				$settings = unserialize($row->data);
			}

			?>
			<div id="metabox_basic_settings" class="postbox" >
				<h3 class='hndle' style="padding:5px;"><span><?php print $this->name; ?></span></h3>
				<div class="inside">
					<table style="width:100%;" cellspacing="3">
						<tr>
							<td style="white-space:nowrap;width:100px;"><?php _e('Clickatell enabled','cpabc'); ?>:</td>
							<td><input type="checkbox" name="cpabc_clickatell_active" <?php print (isset($settings) && !empty($active)) ? 'CHECKED' : ''; ?> /></td>
						</tr>
						<tr>
							<td style="white-space:nowrap;width:100px;"><?php _e('Account API Key','cpabc'); ?>:</td>
							<td><input type="text" name="cpabc_clickatell_sid" value="<?php print esc_attr((isset($settings) && !empty($settings['sid'])) ? trim($settings['sid']) : ''); ?>" size="70" /></td>
						</tr>
						<!--<tr>
							<td style="white-space:nowrap;width:100px;"><?php _e('Authentication Token','cpabc'); ?>:</td>
							<td><input type="text" name="cpabc_clickatell_auth" value="<?php print esc_attr((isset($settings) && !empty($settings['auth'])) ? trim($settings['auth']) : ''); ?>" size="70" /></td>
						</tr>
						<tr>
							<td style="white-space:nowrap;width:100px;"><?php _e('From Phone Number','cpabc'); ?>:</td>
							<td><input type="text" name="cpabc_clickatell_from" value="<?php print esc_attr((isset($settings) && !empty($settings['from'])) ? trim($settings['from']) : ''); ?>" size="70" /></td>
						</tr>-->
						<tr><td colspan="2"><hr /></td></tr>
						<tr>
							<td style="white-space:nowrap;width:100px;"><?php _e('To Phone Number','cpabc'); ?>:</td>
							<td>
								<input type="text" name="cpabc_clickatell_to_website" value="<?php print esc_attr((isset($settings) && !empty($settings['to_website'])) ? trim($settings['to_website']) : ''); ?>" size="70" /><br />
								<i><?php _e('For sending multiple messages, separate the phone numbers by comma symbols.'); ?></i>
							</td>
						</tr>
						<tr>
							<td style="white-space:nowrap;width:100px;" valign="top"><?php _e('Message','cpabc'); ?>:</td>
							<td>
								<textarea name="cpabc_clickatell_mssg_website" cols="80" rows="6" style="resize:both;"><?php print esc_textarea((isset($settings) && !empty($settings['mssg_website'])) ? trim($settings['mssg_website']) : ''); ?></textarea><br />
								<i><?php _e('It is possible to use the same <a href="https://form2email.dwbooster.com/faq#q81" target="_blank">special tags</a> than in notifications emails.', 'cpabc'); ?></i>
							</td>
						</tr>
						<tr><td colspan="2"><hr /></td></tr>
						<tr><td colspan="2"><h2><?php _e('Copy to the users', 'cpabc'); ?></h2></td></tr>
						<tr>
							<td style="white-space:nowrap;width:100px;"><?php _e('Customers country code (leave empty if customers will enter it in the form)','cpabc'); ?>:</td>
							<td>
								<input type="text" name="cpabc_clickatell_users_prefix" value="<?php print esc_attr((isset($settings) && !empty($settings['mssg_users_prefix'])) ? trim($settings['mssg_users_prefix']) : ''); ?>" placeholder="" size="10" /><br />
								<i><?php _e('ex: 1 for USA, 34 for Spain, 44 for UK, etc... '); ?></i>
							</td>
						</tr>                        
						<tr>
							<td style="white-space:nowrap;width:100px;"><?php _e('To Phone fields','cpabc'); ?>:</td>
							<td>
								<input type="text" name="cpabc_clickatell_to_users" value="<?php print esc_attr((isset($settings) && !empty($settings['to_users'])) ? trim($settings['to_users']) : ''); ?>" placeholder="fieldname#" size="70" /><br />
								<i><?php _e('For sending multiple messages, separate the phone fields by comma symbols.'); ?></i>
							</td>
						</tr>
						<tr>
							<td style="white-space:nowrap;width:100px;" valign="top"><?php _e('Message','cpabc'); ?>:</td>
							<td>
								<textarea name="cpabc_clickatell_mssg_users" cols="80" rows="6" style="resize:both;"><?php print esc_textarea((isset($settings) && !empty($settings['mssg_users'])) ? trim($settings['mssg_users']) : ''); ?></textarea><br />
								<i><?php _e('It is possible to use the same <a href="https://form2email.dwbooster.com/faq#q81" target="_blank">special tags</a> than in notifications emails.', 'cpabc'); ?></i>
							</td>
						</tr>
					</table>
				</div>
				<input type="hidden" name="cpabc_clickatell" value="1" />
			</div>
			<?php
		}

		/************************ ADDON CODE *****************************/
        /************************ ATTRIBUTES *****************************/

		private $form_clickatell_table = 'cpabc_clickatell';
		private $_sid;
		private $_auth;
		private $_from;

        /************************ CONSTRUCT *****************************/

        function __construct()
        {
			$this->description = __("The add-on allows to send notification messages (SMS) via Clickatell after submitting the form", 'cpabc');

            // Check if the plugin is active
			if( !$this->addon_is_active() ) return;

			// Export the lead
			//add_action( 'cpabc_process_data', array( &$this, 'put_data' ), 10, 1 );
            
            add_action( 'cpabc_smssend', array( &$this, 'put_data' ), 10, 1 );
            
            $this->update_database();

        } // End __construct

        /************************ PROTECTED METHODS *****************************/

		/**
         * Creates the database tables
         */
        protected function update_database()
		{
			global $wpdb;
			$charset_collate = $wpdb->get_charset_collate();
			$sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix.$this->form_clickatell_table." (
					formid INT NOT NULL,
					active INT NOT NULL DEFAULT 0,
					data TEXT,
					UNIQUE KEY formid (formid)
				) $charset_collate;";

			$wpdb->query($sql);
		} // End update_database

        /************************ PRIVATE METHODS *****************************/

		/**
		 * Checks the format of phone's number and transform it is needed
		 */
		private function _phone_number($phone)
		{
			$phone = preg_replace('/[^\d\+]/', '', $phone);
			$phone = preg_replace('/^00/', '+', $phone);
			if(preg_match('/^\+?[1-9]\d{1,14}$/', $phone)) return $phone;
			return false;
		} // End _validate_phone_number

		/**
		 * Cuts the message to 160 characters
		 */
		private function _message($mssg)
		{
			return substr($mssg, 0, 160);
		} // End _message

		/**
		 * Sends the SMS using clickatell
		 */
		private function _send_sms($to, $mssg)
		{
			$to = explode(',', $to);
			$mssg = $this->_message($mssg);            
			foreach($to as $phone)
			{
				$phone = $this->_phone_number($phone);
				if(!empty($phone))
				{
					$args = array(
						'timeout' 	=> 120
					);

					$request = wp_remote_get(
						'https://platform.clickatell.com/messages/http/send?apiKey='.$this->_sid.'&to='.$phone.'&content='.urlencode($mssg),
                        $args
					);

					if(!is_wp_error($request))
					{
						$response_body = wp_remote_retrieve_body($request);
						//$body = json_decode($response_body);
						//if(!empty($body) && !empty($body->error_code) )
						//{
						//	if(!empty($body->error_message)) error_log( print_r( $body->error_message, true ) );
						//}
					}
					else
					{
						error_log( print_r( $request->get_error_message(), true ) );
					}
				}
			}
            
            
		} // End send_sms

		/************************ PUBLIC METHODS  *****************************/

		/**
         * Send message to Clickatell
         */
        public function	put_data( $params )
		{
			global $wpdb;

			$form_id = @intval( $params[ 'formid' ] );
			$itemnumber = @intval( $params['params'][ 'itemnumber' ] );

			if( $form_id && $itemnumber )
			{
				$row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_clickatell_table." WHERE formid=%d", $form_id ) );

				if(!empty($row) && ($row->active == '1' || $row->active == 1))
				{
					// Clean data
					foreach( $params as $key => $val )
					{
						try
						{
							$tmp = @json_decode( $val );
							if( !empty($tmp) ) $params[ $key ] = $tmp;
						}
						catch( Exception $err )
						{

						}
					}

					if(
						!empty($row->data) &&
						($data = unserialize($row->data)) !== false
					)
					{
						$this->_sid   = (isset($data['sid']))  ? trim($data['sid'])  : '';
						$this->_auth  = (isset($data['auth'])) ? trim($data['auth']) : '';
						$this->_from  = (isset($data['from'])) ? trim($data['from']) : '';

						if(!empty($this->_sid))
						{

							$to_website = (isset($data['to_website'])) ? trim($data['to_website']) : '';
							$mssg_website   = (isset($data['mssg_website'])) ? trim($data['mssg_website']) : '';

							if(!empty($to_website) && !empty($mssg_website))
							{
                                $mssg_website = str_replace("%INFORMATION%", $params["content"], $mssg_website);
                                foreach ($params as $item => $value)
                                {
                                    $to_website = str_replace('%'.$item.'%', $value, $to_website);
                                    $mssg_website = str_replace('%'.$item.'%', $value, $mssg_website);
                                    $to_website = str_replace(''.$item.'', $value, $to_website);
                                    $mssg_website = str_replace(''.$item.'', $value, $mssg_website);
                                }

								$this->_send_sms(
									$to_website,
									$mssg_website
								);
							}

							$to_users   = (isset($data['to_users'])) 	? trim($data['to_users']) 	: '';
							$mssg_users = (isset($data['mssg_users'])) 	? trim($data['mssg_users']) : '';

							if(!empty($params["params"][$to_users]) && !empty($mssg_users))
							{
                                //$to_users = str_replace("%INFORMATION%", $params["content"], $to_users);
                                $mssg_users = str_replace("%INFORMATION%", $params["content"], $mssg_users);
                                foreach ($params as $item => $value)
                                {
                                    //$to_users = str_replace('%'.$item.'%', $value, $to_users);
                                    $mssg_users = str_replace('%'.$item.'%', $value, $mssg_users);
                                    //$to_users = str_replace(''.$item.'', $value, $to_users);
                                    $mssg_users = str_replace(''.$item.'', $value, $mssg_users);
                                }
								$this->_send_sms(
									@$data['mssg_users_prefix'].[$to_users].$params["params"][$to_users],
									$mssg_users
								);
							}
						}
					}
				}
			}
		} // End export_lead



    } // End Class

    // Main add-on code
    $cpabc_clickatell_obj = new CPABC_Clickatell();

    global $cpabc_addons_objs_list;
	$cpabc_addons_objs_list[ $cpabc_clickatell_obj->get_addon_id() ] = $cpabc_clickatell_obj;
}
?>