<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}

class fbbttmCheckout
{

	public function fbbttm_place_order($cartdata=null,$paymentmethod=null){

			global $wpdb, $fbbttm_helperobj, $fbbttm_cartobj;

			$foodbooking_table  = FBBTTM_TB_FOODBOOKING;
			$foodbookingitem_table  = FBBTTM_TB_FOODBOOKING_ITEMINFO;
			$cart_table  = FBBTTM_TB_FOODBOOKING_CART;
			$cartsummary = $fbbttm_cartobj->fbbttm_get_cart_summaryata($cartdata);

			$grandtotal = $cartsummary['grandtotal'];
			$subtotal = $cartsummary['subtotal'];
			$tax = $cartsummary['tax'];

			$cartid =  $cartdata[0]->fbbttm_fdcartid;
			$user_id = $cartdata[0]->fbbttm_user_id;

			$option = array();
			$itemdata = array();

			$currentuserid = $user_id;
			$tokenid = $fbbttm_helperobj->fbbttm_get_user_cookie_data(); 
			$orderkey = 'fbbttm_order_'.$tokenid;

			$foodbooking_data = array(
			  'fbbttm_user_id'=> $currentuserid,
			  'fbbttm_grand_total'=> $grandtotal,
			  'fbbttm_order_key' => $orderkey,
			  'fbbttm_sub_total'=> $subtotal,
			  'fbbttm_payment_id'=>'',
			  'fbbttm_payment_method'=> $paymentmethod,
			  'fbbttm_fdcartid'=> $cartid,
			  'fbbttm_booking_status'=>1,
			  'fbbttm_tax'=> $tax,
			  'fbbttm_discount'=>0
			);

			//$fbid = $wpdb->insert($carttablename,  $data );
			
			$foodbooking_id = $fbbttm_helperobj->fbbttm_common_insert($foodbooking_table,  $foodbooking_data );
			
			for($i=0;$i<count($cartdata);$i++)	
				{
						$itemdata['fbbttm_fdbid'] = $foodbooking_id;
						$itemdata['fbbttm_fbcartitem_id'] = $cartdata[$i]->fbbttm_fbcartitem_id;
						$itemdata['fbbttm_pack_id'] = $cartdata[$i]->fbbttm_pack_id;
						$itemdata['fbbttm_fd_id'] = $cartdata[$i]->fbbttm_fd_id;
						$itemdata['fbbttm_food_name'] = $cartdata[$i]->fbbttm_food_name;
						$itemdata['fbbttm_food_details'] = $cartdata[$i]->fbbttm_food_details;
						$itemdata['fbbttm_food_time'] = $cartdata[$i]->fbbttm_food_time;
						$itemdata['fbbttm_lunch_qty'] = $cartdata[$i]->fbbttm_lunch_qty;
						$itemdata['fbbttm_dinner_qty'] = $cartdata[$i]->fbbttm_dinner_qty;
						$itemdata['fbbttm_total_food'] = $cartdata[$i]->fbbttm_total_food;
						$itemdata['fbbttm_booking_deliveryday'] = $cartdata[$i]->fbbttm_booking_deliveryday;
						$itemdata['fbbttm_food_startdate'] = $cartdata[$i]->fbbttm_food_startdate;
						$itemdata['fbbttm_food_enddate'] = $cartdata[$i]->fbbttm_food_enddate;
						$itemdata['fbbttm_pack_name'] = $cartdata[$i]->fbbttm_pack_name;
						$itemdata['fbbttm_fitem_price'] = $cartdata[$i]->fbbttm_fitem_price;
						$itemdata['fbbttm_package_price'] = $cartdata[$i]->fbbttm_package_price;
						$itemdata['fbbttm_special_price'] = $cartdata[$i]->fbbttm_special_price;
						$itemdata['fbbttm_package_day'] = $cartdata[$i]->fbbttm_package_day;
						$itemdata['fbbttm_package_description'] = $cartdata[$i]->fbbttm_package_description;
						
						$option[] = $itemdata;
				}
				
				$fbbttm_helperobj->fbbttm_common_multiple_insert($foodbookingitem_table,  $option );
				
				//Need to add confirm order mail functionality
				$cart_table  = FBBTTM_TB_FOODBOOKING_CART;	
				$data = array(
						'order_placed'=>'1',
						'fbbttm_ordid'=> $foodbooking_id
					);
				$fbbttm_helperobj->fbbttm_common_updatetable($cart_table,$data,'fbbttm_fdcartid',$cartid,'fbbttm_cartupdate_date');
	
				if($paymentmethod=='cod')
				{
					//need to do mail funtion for order confirmation 
					return $orderkey;
				}
				else
				{
				return $foodbooking_id;
				}
		}


	public function fbbttm_check_payment_method($name=null)
	{
		global $wpdb, $fbbttm_helperobj;

		$table_fbbttm_setting = FBBTTM_TB_SETTING;
		$method = 'fbbttm_'.$name.'_method_status';

		$fbbttm_settingdata = $fbbttm_helperobj->fbbttm_comman_single_tableinfo($table_fbbttm_setting,'fbbttm_setting_name',$method);
		return $fbbttm_settingdata;
	}


	public function fbbttm_get_payment_methodkey($arrwith,$key1=null,$key2=null,$key3=null,$key4=null,$key5=null,$key6=null)
	{

		global $wpdb, $fbbttm_helperobj;

		$fbbttm_settingdata = $fbbttm_helperobj->fbbttm_comman_single_tableinfo(FBBTTM_TB_SETTING,'fbbttm_setting_id');

		$keyarray = array();
		$array_withkey = array(); 


		foreach($fbbttm_settingdata as $dataval)
		  {

		  	if($dataval->fbbttm_setting_name == $key1)
		  	{
		  		array_push($keyarray,$dataval->fbbttm_setting_value);

		  		$array_withkey[$dataval->fbbttm_setting_name] = $dataval->fbbttm_setting_value;
		  	}
		  	if($dataval->fbbttm_setting_name == $key2)
		  	{
		  		array_push($keyarray,$dataval->fbbttm_setting_value);
		  		$array_withkey[$dataval->fbbttm_setting_name] = $dataval->fbbttm_setting_value;
		  	}
		  	if($dataval->fbbttm_setting_name == $key3)
		  	{
		  		array_push($keyarray,$dataval->fbbttm_setting_value);
		  		$array_withkey[$dataval->fbbttm_setting_name] = $dataval->fbbttm_setting_value;
		  	}
		  	if($dataval->fbbttm_setting_name == $key4)
		  	{
		  		array_push($keyarray,$dataval->fbbttm_setting_value);
		  		$array_withkey[$dataval->fbbttm_setting_name] = $dataval->fbbttm_setting_value;
		  	}
		  	if($dataval->fbbttm_setting_name == $key5)
		  	{
		  		array_push($keyarray,$dataval->fbbttm_setting_value);
		  		$array_withkey[$dataval->fbbttm_setting_name] = $dataval->fbbttm_setting_value;
		  	}

		  	if($dataval->fbbttm_setting_name == $key6)
		  	{
		  		array_push($keyarray,$dataval->fbbttm_setting_value);
		  		$array_withkey[$dataval->fbbttm_setting_name] = $dataval->fbbttm_setting_value;
		  	}

		  }

		

		if($arrwith == 'fieldkey'){

			return $array_withkey;

		}else{
		  return $keyarray;
		  }	


	}





	public function fbbttm_get_payment_method_list()
	{

		$paymentmethod = array('stripe','paypal');
		$availmethod = array();

		for($i=0;$i<count($paymentmethod);$i++){
			
			$paymentdata = $this->fbbttm_check_payment_method($paymentmethod[$i]);

			foreach ($paymentdata as $paymentdatamethod )
				{
					$fbbttm_setting_name = $paymentdatamethod->fbbttm_setting_name;

					$fbbttm_setting_value = $paymentdatamethod->fbbttm_setting_value;

					if($fbbttm_setting_value=='yes')
						{
							array_push($availmethod,$fbbttm_setting_name);
						}
				
				}


		}

		return $availmethod;
	}



	 /**
	   *  Function 
	   */ 

	  public function fbbttm_get_fullcart_infowithuser($id=null,$tokenid=null)
	  {

	  	global $wpdb, $fbbttm_helperobj;

		$carttablename = FBBTTM_TB_FOODBOOKING_CART;
		$cartitemtablename = FBBTTM_TB_FOODBOOKING_CART_ITEMINFO;
		$wpusers_table  =FBBTTM_WP_USER;
		$table_fbbttm_delivery_address  = FBBTTM_DELIVERY_ADDRESS;

		$orderinfo = array();

		// Prepare the SQL statement with placeholders
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- $carttablename $wpusers_table $table_fbbttm_delivery_address is hardcoded.
		// Escape table names to ensure safety
		$carttablename = esc_sql($carttablename);
		$cartitemtablename = esc_sql($cartitemtablename);
		$wpusers_table = esc_sql($wpusers_table);
		$table_fbbttm_delivery_address = esc_sql($table_fbbttm_delivery_address);

		// Define the WHERE clause directly in the query
		if ($id == '0') {
	   	// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery 
	    // phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching 

	    $fbbttm_result = $wpdb->get_results( 
	    	//phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
	    $wpdb->prepare("
	        SELECT * 
	        FROM {$carttablename} AS FC 
	        LEFT JOIN {$wpusers_table} AS wu ON wu.ID = FC.fbbttm_user_id 
	        LEFT JOIN {$table_fbbttm_delivery_address} AS da ON da.fbbttm_user_id = wu.ID 
	        WHERE FC.fbbttm_token_id = %s AND FC.order_placed = 0 
	        ORDER BY FC.fbbttm_fdcartid DESC
	    ", $tokenid), OBJECT);
} else {
   
		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery 
		// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching 
 
	    $fbbttm_result = $wpdb->get_results( 
		//phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
	    $wpdb->prepare("
	        SELECT * 
	        FROM {$carttablename} AS FC 
	        LEFT JOIN {$wpusers_table} AS wu ON wu.ID = FC.fbbttm_user_id 
	        LEFT JOIN {$table_fbbttm_delivery_address} AS da ON da.fbbttm_user_id = wu.ID 
	        WHERE FC.fbbttm_user_id = %d AND FC.order_placed = 0 
	        ORDER BY FC.fbbttm_fdcartid DESC
	    ", $id), OBJECT);
}

// Execute the query
//$fbbttm_result = $wpdb->get_results($preparedQuery, OBJECT);
			// phpcs:enable		 

		if(empty($fbbttm_result)) return $fbbttm_result;	

		$orderinfo['cartinfo'] = $fbbttm_result;
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery 
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching 
		$iteminfo = array();

		// Define the SQL query directly with placeholders
		if ($id == '0') {
			
		$iteminfo =  $wpdb->get_results( 
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		     $wpdb->prepare("
		        SELECT * 
		        FROM {$carttablename} AS FC 
		        LEFT JOIN {$cartitemtablename} AS FCITEM ON FCITEM.fbbttm_fdcartid = FC.fbbttm_fdcartid 
		        WHERE FC.fbbttm_token_id = %s AND FC.order_placed = 0 
		        ORDER BY FCITEM.fbbttm_fbcartitem_id DESC
		    ", $tokenid), OBJECT);
		} else {
		    
		   $iteminfo =  $wpdb->get_results( 
			//phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		   	$wpdb->prepare("
		        SELECT * 
		        FROM {$carttablename} AS FC 
		        LEFT JOIN {$cartitemtablename} AS FCITEM ON FCITEM.fbbttm_fdcartid = FC.fbbttm_fdcartid 
		        WHERE FC.fbbttm_user_id = %d AND FC.order_placed = 0 
		        ORDER BY FCITEM.fbbttm_fbcartitem_id DESC
		    ", $id), OBJECT);
		}

		// Execute the query
	//	$iteminfo = $wpdb->get_results($preparedQuery, OBJECT);


		
		if(empty($iteminfo)) return $iteminfo;

		$orderinfo['cartiteminfo'] = $iteminfo;

		return $orderinfo;

	  }


	  /**
	   * 
	   * Function for update cart table and delete that order related data
	   * 
	   */ 


	  public function fbbttm_update_cart_chewcan($id)
	  {

	  	global $fbbttm_helperobj;

	  	$paymentid = $cartid = '';
	  	$message = array();

	  	$checkoutdata = $fbbttm_helperobj->fbbttm_comman_single_tableinfo(FBBTTM_TB_FOODBOOKING,'fbbttm_fdbid',$id);

	  	$noncename = sanitize_text_field($formdata['fbbttm_meta_box_noncename']);

			

	  	if(!empty($checkoutdata)){
		  	foreach($checkoutdata as $checkd)
		  	{
		  	  	$paymentid = $checkd->fbbttm_payment_id;
		  	 	$cartid = $checkd->fbbttm_fdcartid;
		  	}


	  	$fbbttm_helperobj->fbbttm_delete_from_table(FBBTTM_TB_PAYMENT,'fbbttm_payment_id',$paymentid);

	  	$data = array(
                        'fbbttm_ordid'=>'0',
                        'order_placed' => '0',
                );
                    
        $cartdata = $fbbttm_helperobj->fbbttm_common_updatetable(FBBTTM_TB_FOODBOOKING_CART,$data,'fbbttm_fdcartid',$cartid,'fbbttm_cartupdate_date');


	  	$fbbttm_helperobj->fbbttm_delete_from_table(FBBTTM_TB_FOODBOOKING,'fbbttm_fdbid',$id);

	  	$message['success']  = esc_html__('Cart table update successfully','foodboxbooker');

	  	}
	  	else
	  	{
	  		$message['error_message'] = esc_html__('There is no record','foodboxbooker');
	  	}

	  	return $message;
	  }


	  
}