<?php
/*
    iCal Import Addon
*/
require_once dirname( __FILE__ ).'/base.addon.php';

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

        /************* ADDON SYSTEM - ATTRIBUTES AND METHODS *************/
		protected $addonID = "addon-summaryDisplay-20180607";
		protected $name = "Summary Display";
		protected $description;

		public function get_addon_form_settings( $form_id )
		{
			global $wpdb;
			// Insertion in database
			if(
				isset( $_REQUEST[ 'CPABC_summaryDisplay_id' ] )
			)
			{
			    $wpdb->delete( $wpdb->prefix.$this->form_table, array( 'formid' => $form_id ), array( '%d' ) );
				$wpdb->insert(
								$wpdb->prefix.$this->form_table,
								array(
									'formid' => $form_id,
                                    'abcsummarycontent'	 => $_REQUEST["abcsummarycontent"]
								),
								array( '%d', '%s' )
							);           
			}

			$rows = $wpdb->get_results(
						$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE formid=%d", $form_id )
					);
			if (!count($rows))
			{
			    $row["abcsummary_enable"] = 0;
			    $row["abcsummarycontent"] = '<pre>%INFORMATION%</pre>';
			} else {
			    $row["abcsummary_enable"] = $rows[0]->abcsummary_enable;
			    $row["abcsummarycontent"] = $rows[0]->abcsummarycontent;
			}

			?>
			<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_summaryDisplay_id" value="1" />
                   
                   <p>To display the summary into a page put the following shortcode on the page, usually into the 'thank you' page where the customer is redirected after the booking:<br /><br /> <strong>[CPABC_DISPLAY_SUMMARY calendar="<?php echo $form_id; ?>"]</strong><p>
                   
                   <strong>Summary content:</strong><br />
                   <textarea name="abcsummarycontent" cols="70"  rows="5"><?php echo $row['abcsummarycontent']; ?></textarea><br />
                   <em>* Use the same <a href="https://abc.dwbooster.com/faq?page=faq#q507" target="_blank">tags available for the emails</a></em>
				</div>
			</div>
			<?php
		} // end get_addon_form_settings



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

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

        private $form_table = 'cpabc_form_summarydisplay';
        private $_inserted = false;

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

        function __construct()
        {
			$this->description = __("The add-on provides a shortcode to display a summary in the 'thank you' page.", 'cpappb' );
            // Check if the plugin is active
			if( !$this->addon_is_active() ) return;           		

            add_action( 'cpabc_process_data', array( &$this, 'processDataAction' ), 1, 1);

            $this->update_database();

        } // End __construct



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

		/**
         * Create 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_table." (
					id mediumint(9) NOT NULL AUTO_INCREMENT,
					formid INT NOT NULL,
                    abcsummarycontent TEXT,
					UNIQUE KEY id (id)
				) $charset_collate;";
            
			$wpdb->query($sql);
            
		} // end update_database
      

		/**
         * Store data id in a session
         */      
        public function processDataAction($params)
		{
            @session_start();
            $itemnumbers = implode(",", $params["itemnumbers"]);
            $_SESSION['abcsummary'] = $itemnumbers;
            @setCookie('abcsummary', $itemnumbers, time()+36000,"/");
        }
        
        
		/**
         * summary display shortcode processing
         */
        public function summaryDisplay($atts)
		{
			global $wpdb;
            extract( shortcode_atts( array(
	        	'calendar' => '1'
	        ), $atts ) );      
            
            $rows = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE formid=".intval($calendar) );
            // display here
            $content = $rows[0]->abcsummarycontent;
            
            @session_start();
            $itemnumbers_all = @$_SESSION['abcsummary'];
            if (!$itemnumbers_all)
                $itemnumbers_all = @$_COOKIE['abcsummary'];
            if (!$itemnumbers_all)
                return;
            $itemnumber = explode(",", $itemnumbers_all);
            
            $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);
   
            $content = str_replace("%CALENDAR%", $mycalendarrows[0]->uname, $content);
            //$content = str_replace("%ITEMNUMBER%", $itemnumber[0], $content);
            $params = unserialize($myrows[0]->buffered_date);
            foreach ($params as $item => $value)
            {
                $content = str_replace('<%'.$item.'%>',(is_array($value)?(implode(", ",$value)):($value)),$content);
                $content = str_replace('%'.$item.'%',(is_array($value)?(implode(", ",$value)):($value)),$content);
            }            
            for ($i=0;$i<500;$i++)
            {
                 $content = str_replace('<%fieldname'.$i.'%>',"",$content);
                 $content = str_replace('%fieldname'.$i.'%',"",$content);
            }            
            for ($n=0;$n<count($itemnumber);$n++)
            {
//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 ".                
                $myrows = $wpdb->get_results( "SELECT ".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".id as tid,".CPABC_APPOINTMENTS_TABLE_NAME.".* FROM ".CPABC_APPOINTMENTS_TABLE_NAME." INNER JOIN ".CPABC_TDEAPP_CALENDAR_DATA_TABLE." ON ".CPABC_TDEAPP_CALENDAR_DATA_TABLE.".reference=".CPABC_APPOINTMENTS_TABLE_NAME.".id WHERE ((is_cancelled<>'1') OR is_cancelled is null) AND ".CPABC_APPOINTMENTS_TABLE_NAME.".id=".intval($itemnumber[$n]) );                
                if (count($myrows))
                {
                    $content = str_replace("%ITEMNUMBER%", $myrows[0]->tid, $content);
                    $buffered_dates_customer[] = $myrows[0]->booked_time_customer;
                    $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_customer = $mycalendarrows[0]->uname."\n".
                                        implode("\n",$buffered_dates_customer)."\n".
                                        $base_information;
                }
               
            }  
            $content = str_replace("%INFORMATION%", $information_customer, $content);
            $content = str_replace("%ALLDATES%", implode("\n",$buffered_dates_customer), $content);            
            return $content;
		} // end summaryDisplay        


		/************************ 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 );
		}
        


    } // End Class
                
    // Main add-on code
    $CPABC_summaryDisplay_obj = new CPABC_summaryDisplay();

    add_shortcode( 'CPABC_DISPLAY_SUMMARY', array( $CPABC_summaryDisplay_obj, 'summaryDisplay' ) );
    
	// Add addon object to the objects list
	global $cpabc_addons_objs_list;
	$cpabc_addons_objs_list[ $CPABC_summaryDisplay_obj->get_addon_id() ] = $CPABC_summaryDisplay_obj;
}


