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

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

        /************* ADDON SYSTEM - ATTRIBUTES AND METHODS *************/
		protected $addonID = "addon-appLimit-20180607";
		protected $name = "Limit the number of appointments per user";
		protected $description;

		public function get_addon_form_settings( $form_id )
		{
			global $wpdb;
			// Insertion in database
			if(
				isset( $_REQUEST[ 'CPABC_appLimit_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,
									'applimit_enable'	 => $_REQUEST["applimit_enable"],
                                    'daylimit'	 => $_REQUEST["daylimit"],
                                    'weeklimit'	 => $_REQUEST["weeklimit"],
                                    'monthlimit'	 => $_REQUEST["monthlimit"],
                                    'limitby'	 => $_REQUEST["limitby"]   // 0 means email, 1 means registered user
								),
								array( '%d', '%d', '%d', '%d', '%d', '%d' )
							);          
			}

			$rows = $wpdb->get_results(
						$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE formid=%d", $form_id )
					);
			if (!count($rows))
			{
			    $row["applimit_enable"] = 0;
			    $row["daylimit"] = 0;
                $row["weeklimit"] = 0;
                $row["monthlimit"] = 0;
                $row["limitby"] = 0;
			} else {
			    $row["applimit_enable"] = $rows[0]->applimit_enable;
			    $row["daylimit"] = $rows[0]->daylimit;
                $row["weeklimit"] = $rows[0]->weeklimit;
                $row["monthlimit"] = $rows[0]->monthlimit;
                $row["limitby"] = $rows[0]->limitby;
			}

			?>
			<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_appLimit_id" value="1" />
                     Enable appointments limits  for this calendar? :<br />
                        <?php $option = $row['applimit_enable']; ?>
                        <select name="applimit_enable" id="applimit_enable" onchange="abcical_display_option(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="appLimitcontent_yes" <?php if ($option != '1') echo ' style="display:none"'; ?>>
                         <br />
                         <strong>Daily Limit (# of appointments):</strong><br />
                         <select name="daylimit">
                          <option value="0"> - unlimited - </option>
                          <?php for($i=1; $i<100; $i++) {?><option value="<?php echo $i; ?>" <?php if ($i==$row["daylimit"]) echo 'selected'; ?>><?php echo $i; ?></option><?php } ?>
                         </select>
                         <br />

                         <strong>Weekly Limit (# of appointments):</strong><br />
                         <select name="weeklimit">
                          <option value="0"> - unlimited - </option>
                          <?php for($i=1; $i<100; $i++) {?><option value="<?php echo $i; ?>" <?php if ($i==$row["weeklimit"]) echo 'selected'; ?>><?php echo $i; ?></option><?php } ?>
                         </select>
                         <br />

                         <strong>Monthly Limit (# of appointments):</strong><br />
                         <select name="monthlimit">
                          <option value="0"> - unlimited - </option>
                          <?php for($i=1; $i<100; $i++) {?><option value="<?php echo $i; ?>" <?php if ($i==$row["monthlimit"]) echo 'selected'; ?>><?php echo $i; ?></option><?php } ?>
                         </select>
                         <br />
                         
                         <strong>Limit type:</strong><br />
                         <select name="limitby">
                          <option value="0" <?php if (0 ==$row["limitby"]) echo 'selected'; ?>>Apply limit using the customer email address</option>
                          <option value="1" <?php if (1 ==$row["limitby"]) echo 'selected'; ?>>Apply limit for registered WordPress users</option>                         
                         </select>
                         <br />                         
                   </div>
                   <script type="text/javascript">
                       function abcical_display_option(item) 
                       {                         
                           if (item.selectedIndex == 1) 
                               document.getElementById("appLimitcontent_yes").style.display = '';
                           else
                               document.getElementById("appLimitcontent_yes").style.display = 'none';
                       }
                   </script>
				</div>
			</div>
			<?php
		} // end get_addon_form_settings



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

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

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

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

        function __construct()
        {
			$this->description = __("The add-on adds support for limiting the number of appointments per user", 'cpappb' );
            // Check if the plugin is active
			if( !$this->addon_is_active() ) return;
            
            // Insert the JS code to validate the recaptcha code through AJAX
		    add_action( 'cpabc_script_after_validation', array( &$this, 'validate_form_script'), 1, 2 );
            
            add_action( 'cpabc_process_data_before_insert', array( &$this, 'validate_before_insert' ), 10, 1 );
            
            add_action( 'init', array( &$this, 'applimit_check' ), 10, 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,
                    applimit_enable INT NOT NULL,
                    daylimit INT NOT NULL, 
                    weeklimit INT NOT NULL, 
                    monthlimit INT NOT NULL, 
                    limitby INT NOT NULL, 
					UNIQUE KEY id (id)
				) $charset_collate;";
            
			$wpdb->query($sql);
            
		} // end update_database
        
        
       

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

        public function validate_before_insert (&$params) 
        {
            global $wpdb;
            
            $_GET["form"] = $_POST["cpabc_item"];
            $_GET["cpabc_validate_limits_halt"] = 2;  
            $_GET["sel"] = $_POST["selDaycal".$_POST["cpabc_item"]];
            
            $to = cpabc_get_option('cu_user_email_field', CPABC_APPOINTMENTS_DEFAULT_cu_user_email_field);
            $_GET["cpabc_validate_limits"] = $_POST[$to];
            
            $this->applimit_check();
           
        }        
        
        
		public function applimit_check( )
		{
            global $wpdb;
            
            if (!isset($_GET["cpabc_validate_limits"]) || !isset($_GET["form"]) )
                return;
            $rows = $wpdb->get_results( 
						$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE formid=%d", $_GET["form"] ) 
					);
			if (!$rows[0]->applimit_enable)		
			    return;            

            $orgdates = explode(";", $_GET["sel"]);
            $current_user = wp_get_current_user();
            foreach ($orgdates as $orgdate)
                if (trim($orgdate) != '')
                {            
                    $orgdate = str_replace(",","-",$orgdate);                    
                    if ($rows[0]->daylimit)
                    {
                        $from = date("Y-m-d 00:00", strtotime($orgdate));
                        $to = date("Y-m-d 23:59", strtotime($orgdate));
                        $this->check_interval($from, $to, $rows[0]->daylimit, $current_user, $rows[0]);                               
                    }    
                    if ($rows[0]->weeklimit)
                    {
                        $from = date("Y-m-d 00:00", strtotime('sunday last week ', strtotime($orgdate)));
                        $to = date("Y-m-d 23:59", strtotime('saturday this week ', strtotime($orgdate)));
                        $this->check_interval($from, $to, $rows[0]->weeklimit, $current_user, $rows[0]);                
                    }              
                    if ($rows[0]->monthlimit)
                    {
                        $from = date("Y-m-01 00:00", strtotime($orgdate));
                        $to = date("Y-m-01 00:00", strtotime('first day of '.$orgdate." +1 month"));
                        $this->check_interval($from, $to, $rows[0]->monthlimit, $current_user, $rows[0]);                
                    }              
                }
  
            if (@$_GET["cpabc_validate_limits_halt"] != 2)
            {
                echo 'OK';
                exit ();
            }

		}        
        
        
        private function check_interval($from, $to, $max, $current_user, $settings)
        {
            global $wpdb;
            if ($settings->limitby)
                $result = $wpdb->get_results( "SELECT * FROM ".CPABC_TDEAPP_CALENDAR_DATA_TABLE.
                      " WHERE appointment_calendar_id=".intval($_GET["form"]).
                      " AND (datatime>='".esc_sql($from)."') AND (datatime<='".esc_sql($to)."') AND (who_added='".$current_user->ID."') AND ((is_cancelled is Null) OR (is_cancelled<>'1'))");   
            else 
                $result = $wpdb->get_results( "SELECT * FROM ".CPABC_TDEAPP_CALENDAR_DATA_TABLE.
                      " WHERE appointment_calendar_id=".intval($_GET["form"]).
                      " AND (datatime>='".esc_sql($from)."') AND (datatime<='".esc_sql($to)."') AND (title='".esc_sql($_GET["cpabc_validate_limits"])."') AND ((is_cancelled is Null) OR (is_cancelled<>'1'))");                   
            //echo "SELECT * FROM ".CPABC_TDEAPP_CALENDAR_DATA_TABLE.
            //          " WHERE appointment_calendar_id=".intval($_GET["form"]).
            //          " AND (datatime>='".esc_sql($from)."') AND (datatime<='".esc_sql($to)."') AND (title='".esc_sql($_GET["cpabc_validate_limits"])."') AND ((is_cancelled is Null) OR (is_cancelled<>'1'))";             
      
            if (count($result) >= $max)
            {
                echo 'Result abcappexceeded';
                exit();
            }               
        }

       	/**
         * validation script
         */
        public function validate_form_script( $sequence, $formid )
        {            
            global $wpdb;
            
            $rows = $wpdb->get_results( 
						$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE formid=%d", $formid ) 
					);
			if (!$rows[0]->applimit_enable)		
			    return;
            
		?>
            var email = '';
            try{
                var emfield = '#<?php echo cpabc_get_option('cu_user_email_field', CPABC_APPOINTMENTS_DEFAULT_cu_user_email_field); ?>';
                email = $dexQuery(emfield).val();
            } catch (e) {
            }
            try{
               if (email == '')
                   email = document.FormEdit.email.value;
            } catch (e) {
            }
			var result = $dexQuery.ajax({
				type: "GET",
				url:  "<?php echo cpabc_appointment_get_site_url(); ?>",
				data: {
					form: "<?php echo $formid; ?>",
                    sel: $dexQuery("#selDaycal"+cpabc_current_calendar_item).val(),
					cpabc_validate_limits: email
				},
				async: false
			}).responseText;
			if (result.indexOf("abcappexceeded") != -1)
			{
				alert('<?php echo( _e('Number of allowed appointments exceeded.', 'cpabc') ); ?>');
				return false;
			}		
		<?php            
        }
        
        

		/**
		 * 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_appLimit_obj = new CPABC_appLimit();

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


?>