<?php
/*
    Reference: https://www.twilio.com/docs/quickstart/php/sms/sending-via-rest#send-sms-via-rest
*/
require_once dirname( __FILE__ ).'/base.addon.php';

if( !class_exists( 'CPABC_TwilioSMS' ) )
{
    class CPABC_TwilioSMS extends CPABC_BaseAddon
    {

        /************* ADDON SYSTEM - ATTRIBUTES AND METHODS *************/
		protected $addonID = "addon-TwilioSMS-20180301";
		protected $name = "Twilio SMS notifications for bookings and reminders";
		protected $description;
        protected $share_for_all = false;

		public function get_addon_form_settings( $form_id )
		{
			global $wpdb;
			// Insertion in database
			if(
				isset( $_REQUEST[ 'CPABC_TwilioSMS_id' ] )
			)
			{
                cpabc_appointments_add_field_verify($wpdb->prefix.$this->form_table, 'twilio_tophone', "VARCHAR(50) DEFAULT '' NOT NULL");
                cpabc_appointments_add_field_verify($wpdb->prefix.$this->form_table, 'twilio_tomsg', "mediumtext");
                
                $_REQUEST["twilio_tomsg"] = stripcslashes($_REQUEST["twilio_tomsg"]);
                $_REQUEST["twilio_notification_to_customer"] = stripcslashes($_REQUEST["twilio_notification_to_customer"]);
              
                if ($this->share_for_all)
			        $wpdb->query( "DELETE FROM ".$wpdb->prefix.$this->form_table );
                else
                    $wpdb->delete( $wpdb->prefix.$this->form_table, array( 'formid' => $form_id ), array( '%d' ) );
				$wpdb->insert(
								$wpdb->prefix.$this->form_table,
								array(
									'formid' => $form_id,
									
									'twilio_enable'	 => $_REQUEST["twilio_enable"],
                                    
                                    'twilio_accountsid'	 => $_REQUEST["twilio_accountsid"],
                                    'twilio_authtoken'	 => $_REQUEST["twilio_authtoken"],
                                    'twilio_phonefield'	 => $_REQUEST["twilio_phonefield"],
                                    'twilio_fromphone'	 => $_REQUEST["twilio_fromphone"],
                                    'twilio_notification_to_customer'	 => $_REQUEST["twilio_notification_to_customer"],
                                    
                                    'twilio_tophone'	 => $_REQUEST["twilio_tophone"],
                                    'twilio_tomsg'	 => $_REQUEST["twilio_tomsg"],

								),
								array( '%d', '%d',   
                                             '%s', '%s', '%s', '%s', '%s', '%s', '%s'
								              )
							);
			}

            if ($this->share_for_all)                
			    $rows = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix.$this->form_table );
            else
                $rows = $wpdb->get_results(
						$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE formid=%d", $form_id )
					);
			if (!count($rows))
			{
			    $row["twilio_enable"] = 0;
			    $row["twilio_accountsid"] = '';
                $row["twilio_authtoken"] = '';
                $row["twilio_phonefield"] = 'fieldname2';
                $row["twilio_fromphone"] = '+15017250604';
                $row["twilio_notification_to_customer"] = "Reminder for appointment on %DATE% %TIME%";
                $row["twilio_tophone"] = '';
                $row["twilio_tomsg"] = "Notification for appointment on %DATE% %TIME%";
			} else {
			    $row["twilio_enable"] = $rows[0]->twilio_enable;
			    $row["twilio_accountsid"] = $rows[0]->twilio_accountsid;
                $row["twilio_authtoken"] = $rows[0]->twilio_authtoken;
                $row["twilio_phonefield"] = $rows[0]->twilio_phonefield;
                $row["twilio_fromphone"] =  $rows[0]->twilio_fromphone;
                $row["twilio_notification_to_customer"] = $rows[0]->twilio_notification_to_customer;
                $row["twilio_tophone"] =  $rows[0]->twilio_tophone;
                $row["twilio_tomsg"] =  $rows[0]->twilio_tomsg;
			}

			?>
			<div id="metabox_basic_settings" class="postbox" >
				<h3 class='hndle' style="padding:5px;"><span><?php print $this->name; ?></span></h3>
				<div class="inside">
				   <input type="hidden" name="CPABC_TwilioSMS_id" value="1" />
                     Enable TwilioSMS? :<br />
                        <?php $option = $row['twilio_enable']; ?>
                        <select name="twilio_enable" id="twilio_enable" onchange="twilio_display_emails(this)">
                          <option value="0"<?php if ($option != '1') echo ' selected'; ?>>No</option>
                          <option value="1"<?php if ($option == '1') echo ' selected'; ?>>Yes</option>
                         </select><br />
                   
                   <div id="twilioemailcontent_yes" <?php if ($option != '1') echo ' style="display:none"'; ?>>
                         <br />
                         <strong>Important note: This add-on requires to enable also the "Reminder" addon.</strong> 
                         <br /><br />                         
                         <strong>Twilio AccountSid:</strong><br />
                         <input type="text" name="twilio_accountsid" size="70" value="<?php $text = esc_attr($row['twilio_accountsid']); echo $text; ?>" /><br />
                         <strong>Twilio AuthToken:</strong><br />
                         <input type="text" name="twilio_authtoken" size="70" value="<?php $text = esc_attr($row['twilio_authtoken']); echo $text; ?>" /><br />
                         <strong>ID of the field that contains the phone number:</strong><br />
                         <input required type="text" name="twilio_phonefield" size="70" value="<?php $text = esc_attr($row['twilio_phonefield']); echo $text; ?>" /><br /><em>* Click the field in the form builder to see its ID. Example: fieldname1, fieldname2, .... put only the ID without tags<br />
                         <strong>Phone number used as "from":</strong><br />
                         <input required type="text" name="twilio_fromphone" size="70" value="<?php $text = esc_attr($row['twilio_fromphone']); echo $text; ?>" /><br /><em>* Change the 'From' number above to be a valid Twilio number that you've purchased<br />
                         <div style="display:none">
                           <strong>Twilio SMS content:</strong><br />
                           <input type="text" size="125" name="twilio_notification_to_customer" size="70" value="<?php $text = esc_attr($row['twilio_notification_to_customer']); echo $text; ?>" /><br />
                         </div>
                         <br />
                         <div style="border-top: 1px dotted gray;">
                           <strong>Phone number of admin for "new booking" notification:</strong><br />
                           <input type="text" name="twilio_tophone" size="70" value="<?php $text = esc_attr($row['twilio_tophone']); echo $text; ?>" />  <br /><em>* Leave empty to ignore this notification<br />
                           <strong>Twilio SMS content to admin (on new booking):</strong><br />
                           <input type="text" size="125" name="twilio_tomsg" size="70" value="<?php $text = esc_attr($row['twilio_tomsg']); echo $text; ?>" /><br />
                         </div>
                         
                                                
                   </div>
                   <script type="text/javascript">
                       function twilio_display_emails(item) 
                       {                         
                           if (item.selectedIndex == 1) 
                               document.getElementById("twilioemailcontent_yes").style.display = '';
                           else
                               document.getElementById("twilioemailcontent_yes").style.display = 'none';
                       }
                   </script>
				</div>
			</div>
			<?php
		} // end get_addon_form_settings



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

        /************************ ATTRIBUTES *****************************/

        private $form_table = 'cpabc_form_TwilioSMS';
        private $_inserted = false;
		private $_sid;
		private $_auth;
		private $_from;        

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

        function __construct()
        {
			$this->description = __("The add-on adds support for Twilio SMS notifications", 'cpappb' );
            // Check if the plugin is active
			if( !$this->addon_is_active() ) return;
            
			add_action( 'cpabc_process_data', array( &$this, 'pp_TwilioSMS_send_to_admin' ), 10, 1 );
            
            add_action( 'cpabc_smssend', array( &$this, 'pp_TwilioSMS_send' ), 10, 1 );
            
            add_action( 'cpabc_cloneitem', array( &$this, 'pp_TwilioSMS_clone' ), 10, 2 );

            $this->update_database();

        } // End __construct



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

		/**
         * Create the database tables
         */
        protected function update_database()
		{
			global $wpdb, $cp_appb_plugin;

			$charset_collate = $wpdb->get_charset_collate();
			$sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix.$this->form_table." (
					id mediumint(9) NOT NULL AUTO_INCREMENT,
					formid INT NOT NULL,
                    twilio_enable INT NOT NULL,
                    twilio_accountsid varchar(255) DEFAULT '' NOT NULL,
                    twilio_authtoken varchar(255) DEFAULT '' NOT NULL, 
                    twilio_phonefield varchar(255) DEFAULT '' NOT NULL, 
                    twilio_fromphone varchar(255) DEFAULT '' NOT NULL, 
                    twilio_notification_to_customer mediumtext,
                    twilio_tophone VARCHAR(50) DEFAULT '' NOT NULL,
                    twilio_tomsg mediumtext,                    
					UNIQUE KEY id (id)
				) $charset_collate;";
            
			$wpdb->query($sql);
            
		} // end update_database


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


		/**
		 * mark the item as paid
		 */
		private function _log($adarray = array())
		{
			$h = fopen( __DIR__.'/logs.txt', 'a' );
			$log = "";
			foreach( $_REQUEST as $KEY => $VAL )
			{
				$log .= $KEY.": ".$VAL."\n";
			}
			foreach( $adarray as $KEY => $VAL )
			{
				$log .= $KEY.": ".$VAL."\n";
			}
			$log .= "================================================\n";
			fwrite( $h, $log );
			fclose( $h );
		}
        
        
		/**
		 * 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 twilio
		 */
		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))
				{
					$params = array(
						'From' => $this->_from,
						'To' => $phone,
						'Body' => $mssg
					);
					$args = array(
						'headers' 	=> array(
							'Authorization' => 'Basic '. base64_encode( $this->_sid.':'.$this->_auth )
						),
						'body' 		=> $params,
						'timeout' 	=> 45,
						'sslverify'	=> false,
					);

					$request = wp_remote_post(
						'https://api.twilio.com/2010-04-01/Accounts/'.$this->_sid.'/Messages.json',
						$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 function pp_TwilioSMS_send_to_admin( $params  )
		{
            global $wpdb;
 
            $formid = $params["formid"];

            if ($this->share_for_all)
                $settings = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE twilio_enable=1" ); 
            else    
                $settings = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE twilio_enable=1 AND formid=".intval($formid) );

            if (!count($settings))
                return;
            
            $email_content = trim($settings[0]->twilio_tomsg);
            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);
            }
            
            // Step 2: set our AccountSid and AuthToken from https://twilio.com/console
            $AccountSid = $settings[0]->twilio_accountsid;
            $AuthToken = $settings[0]->twilio_authtoken;
            
            $phonedest = $settings[0]->twilio_tophone;
            if (!$phonedest)
                return;
            if ($phonedest != '' && substr($phonedest,0,1) != '+')
               $phonedest = '+'.$phonedest; 

            $this->_from = $settings[0]->twilio_fromphone;
            $this->_sid = $AccountSid;
            $this->_auth = $AuthToken;
            $this->_send_sms($phonedest, $email_content);                           
         
		}
        
        
		public function pp_TwilioSMS_send( $params  )
		{
            global $wpdb, $cp_appb_plugin;
 
            $formid = $params["formid"];
            $email_content_customer = substr(trim($params["content"]),0,160);
            $params = $params["params"];

            if ($this->share_for_all)
                $settings = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE twilio_enable=1" ); 
            else    
                $settings = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE twilio_enable=1 AND formid=".intval($formid) );

            if (!count($settings))
                return;
            
            // Step 2: set our AccountSid and AuthToken from https://twilio.com/console
            $AccountSid = $settings[0]->twilio_accountsid;
            $AuthToken = $settings[0]->twilio_authtoken;
            
            $phonedest = $params[$settings[0]->twilio_phonefield];
            if ($phonedest != '' && substr($phonedest,0,1) != '+')
               $phonedest = '+'.$phonedest; 
            
            $this->_from = $settings[0]->twilio_fromphone;
            $this->_sid = $AccountSid;
            $this->_auth = $AuthToken;
            $this->_send_sms($phonedest, $email_content_customer);                           
         
		}
        
        
       function pp_TwilioSMS_clone ($formid,$newformid) {
           global $wpdb;
           $myrows = $wpdb->get_row( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE formid=".intval($formid), ARRAY_A);    
           $myrows["formid"] = $newformid;
           unset($myrows["id"]);
           $wpdb->insert( $wpdb->prefix.$this->form_table, $myrows);
       }


    } // End Class

    // Main add-on code
    $CPABC_TwilioSMS_obj = new CPABC_TwilioSMS();

	// Add addon object to the objects list
	global $cpabc_addons_objs_list;
	$cpabc_addons_objs_list[ $CPABC_TwilioSMS_obj->get_addon_id() ] = $CPABC_TwilioSMS_obj;
}

