<?php
/**
* WPPIZZA_CRON Class
*
* @package     WPPIZZA
* @subpackage  Cronjobs
* @copyright   Copyright (c) 2015, Oliver Bach
* @license     http://opensource.org/licenses/gpl-2.0.php GNU Public License
* @since       3.0
*
*/
if ( ! defined( 'ABSPATH' ) ) exit;/*Exit if accessed directly*/


/************************************************************************************************************************
*
*
*	WPPIZZA_CRON
*
*
************************************************************************************************************************/
class WPPIZZA_CRON{


	function __construct() {
		
		/**add cronjob action**/
		add_action( 'wppizza_cron', array( $this, 'wppizza_remove_stale_order_entries'));
	}

	/*********************************************************
	*
	*		[cron events]
	*
	*********************************************************/
	/**********************************
	*	[setup or delete cronjob]
	***********************************/
	function wppizza_cron_setup_schedule($cron_args) {
		/**clear all other old schedules**/
		wp_clear_scheduled_hook( 'wppizza_cron');
		/*setup new**/
		if($cron_args['schedule']!=''){
			if ( ! wp_next_scheduled( 'wppizza_cron' ) ) {
				wp_schedule_event( time(), $cron_args['schedule'], 'wppizza_cron');
			}
		}
	}

	/**********************************
	*	[do cronjob or run on save ]
	***********************************/
	function wppizza_remove_stale_order_entries($args=array()) {
		global $wpdb, $wppizza_options;

		/*days to delete**/
		$days=!empty($args['days']) ? max(1, absint($args['days'])) : max(1, absint($wppizza_options['cron']['days_delete']));


		$delete_all_stale=false;
		/**delete now**/
		if(count($args)!=0 && !empty($args['failed_delete']) ){
			$delete_all_stale=true;
		}
		/**delete cron**/
		if(count($args)==0 && !empty($wppizza_options['cron']['failed_delete']) ){
			$delete_all_stale=true;
		}

		/**************************************************
			Which ones to delete:
			default: ONLY delete INITIALIZED, CANCELLED and EXPIRED orders
			alternative: delete ALL that are NOT 'COMPLETED', 'INPROGRESS', 'AUTHORIZED', 'CAPTURED', 'REFUNDED', 'REJECTED'
			filtered: as required
		**************************************************/
		$pStatusQuery = array(
			'operator' => !$delete_all_stale ? 'IN' : 'NOT IN',
			'q_payment_status' => !$delete_all_stale ? array('INITIALIZED' , 'CANCELLED' , 'EXPIRED') :  array('COMPLETED', 'INPROGRESS', 'AUTHORIZED', 'CAPTURED', 'REFUNDED', 'REJECTED'),
		);

		/*-------------------------------------
			allow filtering - for the brave...
			KNOW WHAT YOU ARE DOING !!!!!

			example filter return values:
			$pStatusQuery = array(
				'operator' => 'NOT IN',
				'q_payment_status' => array('CANCELLED' , 'EXPIRED'),
			);
		-------------------------------------*/
		$pStatusQuery = apply_filters('wppizza_remove_order_entries_by_payment_status', $pStatusQuery );

		// whitelist and sanitise operators
		$allowed_operators = array( 'IN', 'NOT IN');
		$operator = in_array( strtoupper( trim( $pStatusQuery['operator'] ) ), $allowed_operators, true ) ? strtoupper( trim( $pStatusQuery['operator'] ) ) : 'IN';

		// generate placeholders string separately to not get PluginCheck.Security.DirectDB.UnescapedDBParameter errors
		$placeholders = implode( ', ', array_fill( 0, count( $pStatusQuery['q_payment_status'] ), '%s' ) );

		// replacement parameters(table names, days) + payment status placeholders, combined into one array for prepare()
		$replacements = array_merge(
		    array( 
		        $wpdb->prefix . WPPIZZA_TABLE_ORDERS, // Matches first %i - orders table name
		        $wpdb->prefix . WPPIZZA_TABLE_ORDERS_META,  // Matches second %i - orders metatable name
		        $days        // Matches %d - number of days of data/orders to keep before now
		    ), 
		    $pStatusQuery['q_payment_status'] // Matches all %s placeholders
		);

		// prepare query - to make the WordPress Plugin Check (PCP) happy, we cannot use the operator ('IN', 'NOT IN') variable but we must hardcode it
		if( $operator == 'IN' ){
			$sql_prepare = $wpdb->prepare( 
				"DELETE orders, metas FROM %i orders LEFT JOIN %i metas ON metas.order_id = orders.id WHERE orders.order_date < TIMESTAMPADD(DAY, -%d, NOW()) AND orders.payment_status IN ( $placeholders )" ,
				$replacements, 
			);
		}
		if( $operator == 'NOT IN' ){
			$sql_prepare = $wpdb->prepare( 
				"DELETE orders, metas FROM %i orders LEFT JOIN %i metas ON metas.order_id = orders.id WHERE orders.order_date < TIMESTAMPADD(DAY, -%d, NOW()) AND orders.payment_status NOT IN ( $placeholders )" ,
				$replacements, 
			);
		}		

		 error_log(print_r($sql_prepare, true));
		
		// run
		$rows = $wpdb->query($sql_prepare);

		/**add to log if cron**/
		if(count($args) == 0){
			error_log("WPPIZZA CRON RUN");
		}
	}
}
?>