<?php


// Set flag that this is a parent file
define('_FEXEC', 1);

// Load application session management
require('includes/application_top.php');
require('includes/functions/sessions.php');

include_once(DIR_WS_LANGUAGES . $FSESSION->language . '/' . FILENAME_CHECKOUT_CONFIRMATION);
include_once(DIR_WS_LANGUAGES . $FSESSION->language . '/modules/payment/paypal_api.php');

//stop hack from not logged in folks
if (!$FSESSION->is_registered('customer_id')) {
    exit(MODULE_PAYMENT_PAYPAL_API_TEXT_NO_ORDER);
}

//check for order_id
if (!$FSESSION->is_registered('paypal_api_id')) {
			
				exit(MODULE_PAYMENT_PAYPAL_API_TEXT_NO_ORDER);
}


// check for a returned id in the url
//check the token
$paymentId = $_GET['paymentId'];

if(!tep_not_null($paymentId)){
               exit(MODULE_PAYMENT_PAYPAL_API_TEXT_NO_ORDER);
			   }
			   
$this_order_id = $order_id = $_SESSION['paypal_api_id'];


$_SESSION['paypal_api_return'] = $this_order_id;

require_once('includes/classes/order.php');
require_once('includes/classes/payment.php');

$order = new order($this_order_id );
$payment = new payment('paypal_api');

$FSESSION->remove('paypal_api_id');
$FSESSION->remove('paypal_api_token');
			   
//curl to PayPal for order result
			      if (MODULE_PAYMENT_PAYPAL_API_TEST_MODE=='True') {
				    $data_url=MODULE_PAYMENT_PAYPAL_API_ADMIN . '/logs/data_test.json';
					$ppurl   ='api.sandbox.paypal.com';
					   }else{
					$data_url=MODULE_PAYMENT_PAYPAL_API_ADMIN . '/logs/data_live.json';
					$ppurl   ='api.paypal.com';}
					
$url='https://'.$ppurl.'/v1/payments/payment/'.$paymentId.'/execute';
$JSONrequest = '{"payer_id":"'.$_GET['PayerID'].'"}';

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		'Content-Type: application/json',
		'Authorization: Bearer '.$_SESSION['access_token']
	));
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $JSONrequest);

	// Capture the raw response
	$rawResponse = curl_exec($ch);

	// Capture HTTP response code
	$httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);

	// Capture any cURL errors
	$curlError = curl_error($ch);

	curl_close($ch);

	// Log everything
	error_log("PayPal API Request URL: " . $url);
	error_log("PayPal API Request Data: " . $JSONrequest);
	error_log("HTTP Status Code: " . $httpStatus);
	error_log("Raw PayPal API Response: " . $rawResponse);
	if ($curlError) {
		error_log("cURL Error: " . $curlError);
	}

	// Decode response
	$resultExecutePayment = json_decode($rawResponse, true);

	curl_close ($ch);
	//exit (print_r($resultExecutePayment));
	$duplicate = "";
	if (strtoupper($resultExecutePayment['name']) == 'DUPLICATE_TRANSACTION'){
	$duplicate = " Paypal notifies that a duplicate invoice number was seen - payment has not been fully processed.";
				if (MODULE_PAYMENT_PAYPAL_API_DEBUG == 'True' && tep_not_null(MODULE_PAYMENT_PAYPAL_API_DEBUG_EMAIL)){
	             tep_mail('DUPLICATE_TRANSACTION', MODULE_PAYMENT_PAYPAL_API_DEBUG_EMAIL, 'PayPal DUPLICATE_TRANSACTION', "Order #: ".$order_id. " seats reserved but payment not accepted at PayPal - update your PayPal settings to allow duplicate invoice numbers.", STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);	
			}
	}

$delivered = "no";
  

if (strtoupper($resultExecutePayment['state']) == 'APPROVED' && (($resultExecutePayment['transactions'][0]['related_resources'][0]['sale']['state'] == 'completed'))){ 

	// change order status

				$order_status=tep_db_query("select orders_status from orders where orders_id='".$this_order_id."'");
				$order_result= tep_db_fetch_array($order_status);
				
				$status = MODULE_PAYMENT_PAYPAL_API_COMP_ORDER_STATUS_ID;
				$delivered ='yes';
						
				if ($order_result['orders_status']!= $status){//completed status not found 			
						//update the status						
					
					$status = MODULE_PAYMENT_PAYPAL_API_COMP_ORDER_STATUS_ID;
					$sql_data_array = array(
						'orders_status' => $status,
									);
					tep_db_perform(TABLE_ORDERS, $sql_data_array, "update", "orders_id='" . $this_order_id. "'");
					    //update status history
					$sql_data_array = array('orders_id' => $this_order_id,
					'orders_status_id' => $status,
					'date_added' => date('Y-m-d H:i:s',getServerDate(false)), 
					'customer_notified' => '0',
					'comments' => MODULE_PAYMENT_PAYPAL_API_CUSTOMER_RETURNS);

					tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
					
					//better late than never - update the orders products table
					  tep_db_query("update orders_products set orders_products_status = ". $status . " where orders_id = '" . $this_order_id . "'");
					
					}// end of order status change to completed 
				
					
//send order emails 
			$order_is_printable = 0;
				if (!is_null($order->products) && is_array($order->products)) {
					for ($i = 0, $n = sizeof($order->products); $i < $n; $i++) {
						$order_is_printable += $order->products[$i]['is_printable'];
					}
				} else {
					$order_is_printable = 0;
				}

		// (2) If printable, setup ticket and generate PDFs for both eTickets and vouchers
		$filename = "";
		$vfilename = "";

		$is_eticket = false;
		$is_voucher = false;
		// Determine if order contains eTickets and/or vouchers (use your SKU definitions)
		foreach ($order->products as $product) {
			if ($product['sku'] == 6 || $product['sku'] == 8) { // Vouchers
				$is_voucher = true;
			}
			if ($product['sku'] == 1 || $product['sku'] == 9) { // eTickets
				$is_eticket = true;
			}
		}

		if (EMAIL_PDF_DELIVERED_ONLY == 'true' && E_TICKETS == 'true' && $status == E_TICKET_STATUS) {
			try {
				// Generate eTicket PDF if applicable
				if ($is_eticket) {
					require_once('includes/functions/products_ticket.php');
					$filename = create_checkout_pdf($this_order_id);  // Generate eTicket PDF
				}
				// Generate Voucher PDF if applicable
				if ($is_voucher) {
					require_once('includes/functions/voucher_ticket.php');
					$vfilename = create_voucher_checkout_pdf($this_order_id);  // Generate Voucher PDF
					// If needed, convert to absolute path:
					if ($vfilename && !file_exists($vfilename)) {
						$vfilename = DIR_FS_CATALOG . $vfilename;
					}
				}
			} catch (Exception $e) {
				error_log("Exception during PDF generation: " . $e->getMessage());
				$delivered ='no';
			}

			// Log file paths for debugging
			//error_log("eTicket file path: " . $filename);
			//error_log("Voucher file path: " . $vfilename);

			// Mark tickets as printed
			tep_db_query("UPDATE " . TABLE_ORDERS . " SET ticket_printed='Y' WHERE orders_id = " . $this_order_id);
		}


    try {
        $email_sent = tep_db_query("SELECT * FROM email_data WHERE order_id='" . $this_order_id . "'");
        while ($email_result = tep_db_fetch_array($email_sent)) {
            // Send email with both attachments: $filename (eTicket) and $vfilename (Voucher)
           


		   if (is_array($filename)) {
				$filename = $filename[0]; // Use the first element if it's an array
			}
			if (is_array($vfilename)) {
				$vfilename = $vfilename[0]; // Use the first element if it's an array
			}

			tep_send_default_email(
				"PRD",
				unserialize(base64_decode($email_result['merge_data'])),
				unserialize(base64_decode($email_result['send_data'])),
				$filename,
				$vfilename
			);
        }
    } catch (Exception $e) {
        error_log("Exception during email sending: " . $e->getMessage());
		$delivered ='no';
    }

				
//if delivered then delete email from table
  if ($delivered == 'yes'){
	  tep_db_query("delete from email_data where order_id='".$this_order_id."'");
	  tep_db_query("update  " . TABLE_ORDERS . "  set ticket_printed='Y' where orders_id = (" . $this_order_id . ")");
	  
	  	    // Payment succeeded, so activate all vouchers for this order
			$sql = "UPDATE " . TABLE_COUPONS . " 
					SET coupon_active = 'Y' 
					WHERE orders_id = " . (int)$this_order_id;
			tep_db_query($sql);
    
    // Optionally log this action:
    error_log("Activated all vouchers for order " . $this_order_id);
	
		
		
		//update status history
		$sql_data_array = array('orders_id' => $this_order_id,
		'orders_status_id' => $status,
		'date_added' => date('Y-m-d H:i:s',getServerDate(false)), 
		'customer_notified' => '1',
		'comments' => MODULE_PAYMENT_PAYPAL_API_TICKETS);

		tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
  }
		
			
tep_db_query("DELETE FROM `customers_away_basket` where `customers_id`='".$_SESSION['customer_id']."'");
	            $cart->reset(true);
				$FSESSION->set('error_count',0);
				// unregister session variables used during checkout
				$FSESSION->remove('BoxOffice');
				$FSESSION->remove('sendto');
				$FSESSION->remove('billto');
				$FSESSION->remove('shipping');
				$FSESSION->remove('payment');
				$FSESSION->remove('comments');
				$FSESSION->remove('order_timestamp');
				$FSESSION->remove('receiptNo');
				$FSESSION->remove('transactionNr');
				$FSESSION->remove('coupon');
				$FSESSION->remove('ccno');
				$FSESSION->remove('gv_redeem_code');
				$FSESSION->remove('billto_array');
				$FSESSION->remove('sendto_array');
				$FSESSION->remove('paypal_ipn_started');
				//Add Extra Fields
				$FSESSION->remove('other');
				$FSESSION->remove('field_1'); 
				$FSESSION->remove('field_2');
				$FSESSION->remove('field_3');
				$FSESSION->remove('field_4');
				//Add Extra Fields end


				
			 tep_redirect(tep_href_link(FILENAME_CHECKOUT_SUCCESS, 'order_id='. $order_id . '&payment=paypal_api', 'SSL'));
				 
				 exit();

}// end APPROVED && completed

else {//do nothing

        
// payment is unknown or in progress
	// change order status

				$order_status=tep_db_query("select orders_status from orders where orders_id='".$this_order_id."'");
				$order_result= tep_db_fetch_array($order_status);
				
								
					$status = MODULE_PAYMENT_PAYPAL_API_AWAITS_ORDER_STATUS_ID;
					$sql_data_array = array(
						'orders_status' => $status,
									);
					tep_db_perform(TABLE_ORDERS, $sql_data_array, "update", "orders_id='" . $this_order_id. "'");
					    //update status history
					$sql_data_array = array('orders_id' => $this_order_id,
					'orders_status_id' => MODULE_PAYMENT_PAYPAL_API_AWAITS_ORDER_STATUS_ID,
					'date_added' => date('Y-m-d H:i:s',getServerDate(false)), 
					'customer_notified' => '0',
					'comments' => MODULE_PAYMENT_PAYPAL_API_AWAITING);

					tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
					//better late than never - update the orders products table
					  tep_db_query("update orders_products set orders_products_status = ". $status . " where orders_id = '" . $this_order_id . "'");

				
tep_db_query("DELETE FROM `customers_away_basket` where `customers_id`='".$_SESSION['customer_id']."'");
	            $cart->reset(true);
				$FSESSION->set('error_count',0);
				// unregister session variables used during checkout
				$FSESSION->remove('BoxOffice');
				$FSESSION->remove('sendto');
				$FSESSION->remove('billto');
				$FSESSION->remove('shipping');
				$FSESSION->remove('payment');
				$FSESSION->remove('comments');
				$FSESSION->remove('order_timestamp');
				$FSESSION->remove('receiptNo');
				$FSESSION->remove('transactionNr');
				$FSESSION->remove('coupon');
				$FSESSION->remove('ccno');
				$FSESSION->remove('gv_redeem_code');
				$FSESSION->remove('billto_array');
				$FSESSION->remove('sendto_array');
				//$FSESSION->remove('paypal_ipn_started');
				//Add Extra Fields
				$FSESSION->remove('other');
				$FSESSION->remove('field_1'); 
				$FSESSION->remove('field_2');
				$FSESSION->remove('field_3');
				$FSESSION->remove('field_4');
				//Add Extra Fields end


				
			 tep_redirect(tep_href_link(FILENAME_CHECKOUT_SUCCESS, 'order_id='. $order_id . '&payment=paypal_api', 'SSL'));
				 
				 exit();



}


exit('error');

/////////////////////////////////////////////////////////
function table_exists($tablename, $database = false)
{
$CheckTable = tep_db_query("SHOW TABLES LIKE '".$tablename."'");
if( tep_db_num_rows($CheckTable) > 0 ) {
  return true;
  	}else{
  return false;
  }
    

}

?>