<?php
/*
	 
	
	osConcert, Online Seat Booking 
  	http://www.osconcert.com

  	Copyright (c) 2020-2025 osConcert

	Released under the GNU General Public License
*/

// file to handle the customer returning from Stripe after payment etc etc

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

  require('includes/application_top.php');  

  $secret_key=$secret_key2="";
  
    if(isset($_GET['c_id'])  )
		{
			$stripe_customer_id = $_GET['c_id'];
		}else{
			// fail silently
			exit();
		}
// 1. No customer session   then redirect to login

if (!$FSESSION->is_registered('customer_id') ) {
					tep_redirect(tep_href_link(FILENAME_LOGIN, '', 'SSL'));
				exit();
				
				}

//Now we do some extra security checks
// 2. check that there is a stripe_order_id in the session

      if (!isset($_SESSION['stripe_order_id'])) {
        			tep_redirect(tep_href_link('index.php', '', 'SSL'));
				exit();
      }
// grab it and unset the session this stops customers refreshing the page 
// casuing multiple restocking

         $this_order_id = $_SESSION['stripe_order_id'];        

		require_once('./includes/classes/order.php');
		$order = new order($this_order_id);
		 	 
		 unset($_SESSION['stripe_order_id']);
		 
// 3. paranoia check

       if ($stripe_customer_id  != $FSESSION->get('customer_id') ) {
       				tep_redirect(tep_href_link('index.php', '', 'SSL'));
				exit();
      }
	  
//4. stripe session id?
            if (!isset($_SESSION['stripe_id'])) {
        			tep_redirect(tep_href_link('index.php', '', 'SSL'));
				exit();
              }

require_once('./includes/modules/payment/stripesca.php');
require_once(DIR_WS_LANGUAGES . $FSESSION->language . '/modules/payment/stripesca.php');
require_once('./ext/modules/payment/stripesca/init.php');

//$stripesca = new stripesca;	
$secret_key = ((MODULE_PAYMENT_STRIPESCA_TESTMODE == 'Test') ? MODULE_PAYMENT_STRIPESCA_TESTING_SECRET_KEY : MODULE_PAYMENT_STRIPESCA_LIVE_SECRET_KEY);

\Stripe\Stripe::setApiKey($secret_key);
	\Stripe\Stripe::setApiVersion( '2019-12-03');
    $result = \Stripe\Checkout\Session::retrieve($_SESSION['stripe_id'] );
    $intent = \Stripe\PaymentIntent::retrieve($result["payment_intent"]);
	
//check a few things

//get current 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_orig = $order_result['orders_status'];				

// If webhook has already fulfilled the order, continue to checkout success.
if ($status_orig == MODULE_PAYMENT_STRIPESCA_COMP_ORDER_STATUS_ID) {
    $cart->reset(true);
    tep_redirect(tep_href_link(FILENAME_CHECKOUT_SUCCESS, 'order_id=' . (int)$this_order_id . '&payment=stripesca', 'SSL'));
    exit();
}

// If webhook has NOT fulfilled the order, do not fulfill from success.php.
// This usually means the webhook secret is missing/wrong, or Stripe has not called back yet.
tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, array(
    'orders_id' => (int)$this_order_id,
    'orders_status_id' => $status_orig,
    'date_added' => date('Y-m-d H:i:s', getServerDate(false)),
    'customer_notified' => 0,
    'comments' => 'Stripe payment return detected, but webhook has not confirmed fulfillment yet. Check Stripe webhook signing secret.'
));

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

    $delivered = '';
	$message= MODULE_PAYMENT_STRIPESCA_UNCONFIRMED;

if (isset($intent['status']) && $intent['status'] === 'succeeded') {

    // Refresh the order status from database
    $order_status_query = tep_db_query("
        select orders_status 
        from " . TABLE_ORDERS . " 
        where orders_id = '" . (int)$this_order_id . "'
        limit 1
    ");

    $order_status_result = tep_db_fetch_array($order_status_query);
    $current_order_status = (int)$order_status_result['orders_status'];

    // If webhook has already fulfilled the order, go to checkout success
    if ($current_order_status == MODULE_PAYMENT_STRIPESCA_COMP_ORDER_STATUS_ID) {

        tep_redirect(
            tep_href_link(
                FILENAME_CHECKOUT_SUCCESS,
                'order_id=' . (int)$this_order_id . '&payment=stripesca',
                'SSL'
            )
        );

        exit();
    }

    // Payment succeeded at Stripe, but webhook has not completed fulfillment yet.
    // Do NOT deliver tickets/downloads here.
    $sql_data_array = array(
        'orders_id' => (int)$this_order_id,
        'orders_status_id' => $current_order_status,
        'date_added' => date('Y-m-d H:i:s', getServerDate(false)),
        'customer_notified' => 0,
        'comments' => 'Stripe payment succeeded, but webhook has not confirmed fulfillment yet. Check Stripe webhook signing secret.'
    );

    tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);

    $messageStack->add_session(
        'checkout',
        'Payment received. Your order is awaiting Stripe confirmation. Please wait a few moments and refresh your order page.',
        'warning'
    );

    tep_redirect(
        tep_href_link(
            FILENAME_CHECKOUT_SUCCESS,
            'order_id=' . (int)$this_order_id . '&payment=stripesca_pending',
            'SSL'
        )
    );

    exit();

} else {

    error_log("Stripe Success: PaymentIntent status is not succeeded: " . print_r($intent, true));

    $messageStack->add_session(
        'checkout',
        'Stripe payment was not completed. Please contact us if payment was taken.',
        'error'
    );

    tep_redirect(tep_href_link(FILENAME_SHOPPING_CART, '', 'SSL'));
    exit();
}
//send order emails 

//set/check the sending email flag
	$sending_status=tep_db_query("select email_sending from email_data where order_id='".$this_order_id."'");
	$sending_result= tep_db_fetch_array($sending_status);
	if($sending_result['email_sending'] == 0){
//email not yet sent

          //(a) set the sending flag
          tep_db_query("update email_data set email_sending = 1 where order_id = " . $this_order_id);
          
					//(1) run through the order products list and compile $ order_is printable
					$order_is_printable = 0;
					for ($i=0, $n=sizeof($order->products); $i<$n; $i++) {								
		                 $order_is_printable = $order_is_printable + $order->products[$i]['is_printable'];
					}
					
					// (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());
			}
			
				// 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)

						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());
				}
				
				try {
					if (function_exists('update_season_queue')) {
						update_season_queue((int)$this_order_id, $status);
					}
				} catch (Exception $e) {
					unset($e);
				}
				

		//if delivered then delete email from table
		  if ($delivered == 'yes'){
			  tep_db_query("delete from email_data where order_id='".$this_order_id."'");
		  }

          }//end of sending email

				$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');
		
				//Add Extra Fields
				$FSESSION->remove('other');
				$FSESSION->remove('field_1'); 
				$FSESSION->remove('field_2');
				$FSESSION->remove('field_3');
				$FSESSION->remove('field_4');
			
	             tep_db_query("DELETE FROM `customers_away_basket` where `customers_id`='".(int)$FSESSION->customer_id."'");
	
	
		$FSESSION->remove('credit_covers');

		tep_redirect(tep_href_link(FILENAME_CHECKOUT_SUCCESS, 'order_id='. $this_order_id . '&payment=stripesca', 'SSL'));


?>