<?php

session_start();

include("include/db.conn.php");

include("include/conf.class.php");

include("include/admin.class.php");



require_once('include/paypal.class.php');  // include the class file

$pg_details=$cartCore->fetch_payment_gateway_by_company_id($_SESSION['GLOBAL_ID_FOR_TAX_SHIPPING']);

$p = new paypal_class;             // initiate an instance of the class


if($pg_details['ACTIVE']==1)
{
	$p->paypal_url = 'https://www.paypal.com/cgi-bin/webscr';     // paypal url
	$pg_mail_account=$pg_details['LIVE_EMAIL'];
}
else
{
	$p->paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';   // testing paypal url
	$pg_mail_account=$pg_details['SANDBOX_EMAIL'];
}





// setup a variable for this script (ie: 'http://www.micahcarrick.com/paypal.php')



$this_script = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];







// if there is not action variable, set the default action of 'process'



if (empty($_GET['action'])) $_GET['action'] = $cartCore->md5_base64_encode('process');  







switch ($cartCore->md5_base64_decode($_GET['action'])) {



	case 'process':      // Process and order...   
		
			$ORDER_DETAIL=$cartCore->fetch_invoice_details_by_invoice_id($_POST['invoice']);
			$CURRENCY_DETAIL=$cartCore->fetch_currency_by_symbol($ORDER_DETAIL['CURRENCY']);
			$GLOBAL_DETAIL=$cartCore->fetch_global_config_by_company_id($ORDER_DETAIL['COMPANY_ID']);

		$p->add_field('business', $pg_mail_account);

		$p->add_field('return', $this_script.'?action='.$cartCore->md5_base64_encode('wow_fine_work').'&item_number='.$cartCore->md5_base64_encode($_POST['item_number']).'&token_id='.$_SESSION['token']);

		$p->add_field('cancel_return', $this_script.'?action='.$cartCore->md5_base64_encode('wow_cancel_work').'&item_number='.$cartCore->md5_base64_encode($_POST['item_number']).'&token_id='.$_SESSION['token']);

		$p->add_field('notify_url', $this_script.'?action=ipn');

		$p->add_field('item_name', $GLOBAL_DETAIL['COMPANY_NAME']);

		$p->add_field('invoice', $_POST['invoice']);
		
		$p->add_field('item_number', $_POST['item_number']);

		$p->add_field('currency_code', $CURRENCY_DETAIL['CURRENCY_VALUE']);  

		$p->add_field('amount', $_POST['amount']);		

		$p->submit_paypal_post(); // submit the fields to paypal
		

		//$p->dump_fields();      // for debugging, output a table of all the fields


      break;



      



	case 'wow_fine_work':      // Order was successful... 

//*****************************************************************************************
$item_no=$cartCore->md5_base64_decode($_GET['item_number']);
$token_id=$_GET['token_id'];

				$invoiceROWS = mysql_fetch_assoc(mysql_query("SELECT BILLING_FULL_NAME, BILLING_EMAIL,SHIPPING_EMAIL FROM cart_order WHERE ORDER_ID='".$item_no."'"));
				
				mysql_query("UPDATE cart_order SET STATUS='PAID',PAYMENT_SUCCESS=true, PAYMENT_TXNID='Collect from Owner' WHERE ORDER_ID='".$item_no."'");			

				
		$fetch_global_details=$cartCore->fetch_global_config_by_company_id($_SESSION['GLOBAL_ID_FOR_TAX_SHIPPING']);

		//email to customer
		$notifyemailscontent[]=$invoiceROWS['BILLING_EMAIL'];
		$COMPANY_ID=$fetch_global_details['GLOBAL_ID'];
		$email_subject=$fetch_global_details['COMPANY_NAME'].': invoice '.$item_no.'';
		$message=$cartAdminMain->email_customer_template($COMPANY_ID,$item_no);
		
		//email to admin
		$notifyemailscontent_admin[]=$fetch_global_details['COMPANY_EMAIL_01'];
		$email_subject_admin=$invoiceROWS['BILLING_EMAIL'].' makes a purchase: invoice '.$item_no.'';
		$message_admin=$cartAdminMain->email_admin_template($COMPANY_ID,$item_no);
		
		$send_customer=$cartCore->configuration_email($message,$email_subject,$notifyemailscontent,$COMPANY_ID,$message_admin,$email_subject_admin);
		
		$encrypt_company_id=$cartCore->md5_base64_encode($COMPANY_ID);
		
		unset($_SESSION['GLOBAL_ID_FOR_TAX_SHIPPING']);
		unset($_SESSION['CHECKOUT']);
		unset($_SESSION['ITEM_ID']);
		unset($_SESSION['ONE_BACK_ID']);
		unset($_SESSION['QUANTITY_VALUE']);
		unset($_SESSION['CURRENCY']);
		
		if($send_customer=='ok')
		{
		$encrypt_success_code=$cartCore->md5_base64_encode('fine');
		header("location:payment_success.php?ref_id=".$_GET['item_number']."&success_code=".$encrypt_success_code."&token_id=".$token_id."&comp=".$encrypt_company_id."");
		}
		else
		{
			$encrypt_success_code=$cartCore->md5_base64_encode('email_error');
			header("location:payment_success.php?ref_id=".$_GET['item_number']."&success_code=".$encrypt_success_code."&token_id=".$token_id."&comp=".$encrypt_company_id."");
		}
		
		break;



      



	case 'wow_cancel_work':       // Order was canceled...		

		$item_no=$cartCore->md5_base64_decode($_GET['item_number']);
		$result=$cartCore->fetch_oneproduct_by_invoice_number($item_no);
		$encrypt_back_item=$cartCore->md5_base64_encode($result['PRODUCT_CATAGORY_ID']);
		$token_id=$_GET['token_id'];
		

		mysql_query("delete from cart_order where ORDER_ID='".$item_no."'");
		mysql_query("delete from cart_order_product where ORDER_ID='".$item_no."'");
		$encryp_condition=$cartCore->md5_base64_encode('CUSTOMER');
		header("location:logout.php?condition=".$encryp_condition."&bk=".$encrypt_back_item."");

		break;		



      



	case 'ipn':          // Paypal is calling page for IPN validation...     



		if ($p->validate_ipn()) {  



			if($p->ipn_data['payment_status'] == "Completed" || $p->ipn_data['payment_status'] == "Pending"){	



			   //*****************************************************************************************

			   	mysql_query("UPDATE bsi_bookings SET payment_success=true, payment_txnid='".$p->ipn_data['txn_id']."', paypal_email='".$p->ipn_data['payer_email']."' WHERE booking_id='".$p->ipn_data['invoice']."'");

	

				$invoiceROWS = mysql_fetch_assoc(mysql_query("SELECT client_name, client_email, invoice FROM bsi_invoice WHERE booking_id='".$p->ipn_data['invoice']."'"));

				mysql_query("UPDATE bsi_clients SET existing_client = 1 WHERE email='".$invoiceROWS['client_email']."'");

				

				$invoiceHTML = $invoiceROWS['invoice'];		

				$invoiceHTML.= '<br><br><table  style="font-family:Verdana, Geneva, sans-serif; font-size: 12px; background:#999999; width:700px; border:none;" cellpadding="4" cellspacing="1"><tr><td align="left" colspan="2" style="font-weight:bold; font-variant:small-caps; background:#eeeeee">'.mysql_real_escape_string(INV_PAY_DETAILS).'</td></tr><tr><td align="left" width="30%" style="font-weight:bold; font-variant:small-caps; background:#ffffff">'.mysql_real_escape_string(INV_PAY_OPTION).'</td><td align="left" style="background:#ffffff">PayPal</td></tr><tr><td align="left" width="30%" style="font-weight:bold; font-variant:small-caps; background:#ffffff">Payer E-Mail</td><td align="left" style="background:#ffffff">'.$p->ipn_data['payer_email'].'</td></tr><tr><td align="left" style="font-weight:bold; font-variant:small-caps; background:#ffffff">'.mysql_real_escape_string(INV_TXN_ID).'</td><td align="left" style="background:#ffffff">'.$p->ipn_data['txn_id'].'</td></tr></table>';

				

				mysql_query("UPDATE bsi_invoice SET invoice = '$invoiceHTML' WHERE booking_id='".$p->ipn_data['invoice']."'");

				

				

				

				$emailBody = "Dear ".$invoiceROWS['client_name'].",<br><br>";

				$emailBody .= html_entity_decode($emailContent['body'])."<br><br>";

				$emailBody .= $invoiceHTML;

				$emailBody .= "<br><br>".mysql_real_escape_string(PP_REGARDS).",<br>".$bsiCore->config['conf_hotel_name'].'<br>'.$bsiCore->config['conf_hotel_phone'];

				$emailBody .= "<br><br><font style=\"color:#F00; font-size:10px;\">[ ".mysql_real_escape_string(PP_CARRY)." ]</font>";

				$flag = 1;

				$bsiMail->sendEMail($invoiceROWS['client_email'], $emailContent['subject'], $emailBody, $p->ipn_data['invoice'], $flag);

				

				/* Notify Email for Hotel about Booking */

				$notifyEmailSubject = "Booking no.".$p->ipn_data['invoice']." - Notification of Room Booking by ".$invoiceROWS['client_name'];

				

				$bsiMail->sendEMail($bsiCore->config['conf_notification_email'], $notifyEmailSubject, $invoiceHTML);

			//*****************************************************************************************

			}elseif($p->ipn_data['payment_status'] == "Refunded"){



			   mysql_query("update paypal_payment set payment_success='0' where invoice=".$p->ipn_data['invoice']);  



			}elseif($p->ipn_data['payment_status'] == "Reversed"){



			   mysql_query("update paypal_payment set payment_success='0' where invoice=".$p->ipn_data['invoice']);		



			}



		}



	break;



  }   

?>