<?php
/*
	osCommerce, Open Source E-Commerce Solutions 
	http://www.oscommerce.com 
	
	Copyright (c) 2003 osCommerce 
	
	osCommRes, Services Oline 
	http://www.oscommres.com 
	Copyright (c) 2005 osCommRes 
	
	Freeway eCommerce 
	http://www.zac-ware.com/freeway 
	Copyright (c) 2007 ZacWare
	
	Released under the GNU General Public License
*/


// Set flag that this is a parent file
	define( '_FEXEC', 1 );
	
	notify_log("File is accessed first write");
	include('includes/application_top.php');
	include(DIR_WS_LANGUAGES . $language . '/' . FILENAME_CHECKOUT_PROCESS);
	
	// load paypal_ipn payment module
	$payment = 'paypalipn';
	require(DIR_WS_CLASSES . 'payment.php');
	$payment_modules = new payment($payment);
	$file_contents = "";

	if (phpversion() <= '4.0.6') {
		$_POST = $HTTP_POST_VARS;
		$file_contents = "PHP version:\n";
		$file_contents .= "-------------\n";
		$file_contents .= phpversion() . "\n";
		notify_log($file_contents);
	}

	require(DIR_WS_CLASSES . 'order.php');
	$order = new order($_POST['item_number']);
	
	$req = 'cmd=_notify-validate';
	
	$file_contents = "Post Variables:\n";
	$file_contents .= "----------------\n";
	foreach ($_POST as $key => $value) {
		$req .= '&' . $key . '=' . urlencode($value);
		$$key = $value;
		$file_contents .= $key . ":" . $value . "\n";
	}
	notify_log($file_contents);

	$response_verified = '';
	$paypal_response = '';

	if (MODULE_PAYMENT_PAYPALIPN_TEST_MODE=='True') {
		notify_log("Payment Mode(MODULE_PAYMENT_PAYPALIPN_TEST_MODE):" . MODULE_PAYMENT_PAYPALIPN_TEST_MODE . "\n");

		if ($item_number) {
		  $paypal_response = $_POST[ipnstatus];
	
		echo 'TEST IPN Processed for order #'.$item_number;
			$file_contents = "Item Number:\n";
			$file_contents .= "-------------\n";
			$file_contents .= "TEST IPN Processed for order #" . $item_number . "\n";
			notify_log($file_contents);
		} else {
	
		echo 'You need to specify an order #';
			$file_contents = "Item Number:\n";
			$file_contents .= "-------------\n";
			$file_contents .= "You need to specify an order #\n";
			notify_log($file_contents);
		};

  } elseif (MODULE_PAYMENT_PAYPALIPN_CURL=='True') { // IF CURL IS ON, SEND DATA USING CURL (SECURE MODE, TO https://)
		notify_log("Payment Mode(MODULE_PAYMENT_PAYPALIPN_CURL):" . MODULE_PAYMENT_PAYPALIPN_CURL . "\n");

    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL,"https://www.paypal.com/cgi-bin/webscr"); 
    curl_setopt($ch, CURLOPT_FAILONERROR, 1); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
    $paypal_response = curl_exec($ch);
    curl_close ($ch);
	$file_contents = "Payment Response:\n";
	$file_contents .= "--------------------\n";
	$file_contents .= $paypal_response . "\n";
	notify_log($file_contents);

  } else { // ELSE, SEND IT WITH HEADERS (STANDARD MODE, TO http://)
		notify_log("Payment Module:Else Executed.\n");

    $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
    $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $header .= "Content-Length: " . strlen ($req) . "\r\n\r\n";
    $fp = fsockopen ("www.paypal.com", 80, $errno, $errstr, 30);

    fputs ($fp, $header . $req);
    while (!feof($fp)) {
      $paypal_response .= fgets($fp, 1024);
    };
	notify_log("Paypal Response :\n" . $paypal_response . "\n");

    fclose ($fp);

  };

  if (ereg('VERIFIED',$paypal_response)) {
    $response_verified = 1;
    $ipn_result = 'VERIFIED';
	notify_log("Paypal response Verified.\n");
  } else if (ereg('INVALID',$paypal_response)) {
    $response_invalid = 1;
    $ipn_result = 'INVALID';
	notify_log("Invalid Response\n");
  } else {
    echo 'Error: no valid $paypal_response received.';
	notify_log("Error: no valid $paypal_response received.\n");
  };
  
  if ($txn_id && ($response_verified==1 || $response_invalid==1)) {

    $txn_check = tep_db_query("select txn_id from " . TABLE_PAYPALIPN_TXN . " where txn_id='".tep_db_input($txn_id)."'");
    if (tep_db_num_rows($txn_check)==0) { // If txn no previously registered, we should register it
		notify_log("Paypalipn_txn Has records.\n");

      $sql_data_array = array('txn_id' => $txn_id,
                              'ipn_result' => $ipn_result, 
                              'receiver_email' => $receiver_email, 
                              'business' => $business, 
                              'item_name' => $item_name, 
                              'item_number' => $item_number, 
                              'quantity' => $quantity, 
                              'invoice' => $invoice, 
                              'custom' => $custom, 
                              'option_name1' => $option_name1, 
                              'option_selection1' => $option_selection1, 
                              'option_name2' => $option_name2, 
                              'option_selection2' => $option_selection2, 
                              'num_cart_items' => $num_cart_items, 
                              'payment_status' => $payment_status, 
                              'pending_reason' => $pending_reason,
                              'payment_date' => $payment_date, 
                              'settle_amount' => $settle_amount, 
                              'settle_currency' => $settle_currency, 
                              'exchange_rate' => $exchange_rate, 
                              'payment_gross' => $payment_gross, 
                              'payment_fee' => $payment_fee, 
                              'mc_gross' => $mc_gross, 
                              'mc_fee' => $mc_fee, 
                              'mc_currency' => $mc_currency, 
                              'tax' => $tax, 
                              'txn_type' => $txn_type, 
                              'for_auction' => $for_auction, 
                              'memo' => $memo, 
                              'first_name' => $first_name, 
                              'last_name' => $last_name, 
                              'address_street' => $address_street, 
                              'address_city' => $address_city, 
                              'address_state' => $address_state, 
                              'address_zip' => $address_zip, 
                              'address_country' => $address_country, 
                              'address_status' => $address_status, 
                              'payer_email' => $payer_email, 
                              'payer_id' => $payer_id, 
                              'payer_status' => $payer_status,
                              'payment_type' => $payment_type,
                              'notify_version' => $notify_version,
                              'verify_sign' => $verify_sign);

      tep_db_perform(TABLE_PAYPALIPN_TXN,$sql_data_array);

    } else { // else we update it to the new status
		notify_log("Paypalipn_txn has not Records.\n");

      $sql_data_array = array('payment_status' => $payment_status,
                              'pending_reason' => $pending_reason,
                              'ipn_result' => $ipn_result,
                              'payer_email' => $payer_email, 
                              'payer_id' => $payer_id, 
                              'payer_status' => $payer_status,
                              'payment_type' => $payment_type);

      tep_db_perform(TABLE_PAYPALIPN_TXN,$sql_data_array,'update','txn_id=\''.$txn_id.'\'');

    };

  };
	$products_type="";
	
  if ($response_verified==1) {
  	notify_log("Response Verified.\n");
    if (strtolower($receiver_email)==strtolower(MODULE_PAYMENT_PAYPALIPN_ID) || strtolower($business)==strtolower(MODULE_PAYMENT_PAYPALIPN_ID)) {
		$file_contents = "MODULE_PAYMENT_PAYPALIPN_ID:" . MODULE_PAYMENT_PAYPALIPN_ID . "\n";
		$file_contents .= "received_email:" . $receiver_email . "\n";
		$file_contents .= strtolower($receiver_email) . ":" . strtolower(MODULE_PAYMENT_PAYPALIPN_ID) . "\n";
		$file_contents .= "business:" . $business . "\n";
		$file_contents .= strtolower($business) . ":" . strtolower(MODULE_PAYMENT_PAYPALIPN_ID) . "\n";
		notify_log($file_contents);
      if ($payment_status=='Completed') {
	  	notify_log("Payment Status is completed.\n");

        if (is_numeric(MODULE_PAYMENT_PAYPALIPN_ORDER_STATUS_ID) && (MODULE_PAYMENT_PAYPALIPN_ORDER_STATUS_ID > 0) ) {
          $order_status = MODULE_PAYMENT_PAYPALIPN_ORDER_STATUS_ID;
			notify_log("order_status(MODULE_PAYMENT_PAYPALIPN_ORDER_STATUS_ID):" . MODULE_PAYMENT_PAYPALIPN_ORDER_STATUS_ID . "\n");
        } else {
          $order_status = DEFAULT_ORDERS_STATUS_ID;
			notify_log("order_status(DEFAULT_ORDERS_STATUS_ID):" . DEFAULT_ORDERS_STATUS_ID . "\n");
        };

        $sql_data_array = array('orders_status' => $order_status);

        tep_db_perform(TABLE_ORDERS,$sql_data_array,'update','orders_id='.$item_number);

        $customer_notification = (SEND_EMAILS == 'true') ? '1' : '0';
		notify_log("send_emails:" . SEND_EMAILS . "\n");
        $sql_data_array = array('orders_id' => $item_number, 
                                'orders_status_id' => $order_status, 
                                'date_added' => 'now()', 
                                'customer_notified' => $customer_notification);
        tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);

		$products_ordered='';
// lets start with the email confirmation
        for ($i=0, $n=sizeof($order->products); $i<$n; $i++) {
			$products_ordered_attributes='';
			if ($order->products[$i]['element_type']=='P'){
				if (sizeof($order->products[$i]['attributes']) > 0) {
					$attributes_exist = '1';
					for ($j = 0, $k = sizeof($order->products[$i]['attributes']); $j < $k; $j++) {
						$products_ordered_attributes .= "<br>&nbsp;&nbsp;&nbsp;&nbsp;" . $order->products[$i]['attributes'][$j]['option'] . ':' . $order->products[$i]['attributes'][$j]['value'];
						if($order->products[$i]['attributes'][$j]['price'])
						$products_ordered_attributes .= " - " . $currencies->format($order->products[$i]['attributes'][$j]['price']);
					}
				}
				
				$stock_query = tep_db_query("select p.products_image_1,p.products_quantity from " . TABLE_PRODUCTS . " p where p.products_id = '" . tep_db_input(tep_get_prid($order->products[$i]['id'])) . "'");
				$stock_values=tep_db_fetch_array($stock_query);
				$products_ordered .= '<tr class="textTableContent" height="56"><td valign="top"  width="40" class="textMain">'.$order->products[$i]['qty'].' x </td>' .'<td width="55" valign="top" class="textMain">'.tep_product_email_image($stock_values["products_image_1"],$order->products[$i]['name'],'style="width:50px;height:50px"').'</td><td valign="top" class="textMain">'.$order->products[$i]['name'] . ($order->products[$i]['model']!=""?' (' . $order->products[$i]['model'] . ')':'').  '<br>' . $products_ordered_attributes . '</td>' .
										'<td valign="top" class="main"><small>' .$order->products[$i]['sku']. '</small></td><td valign="top" align="right" class="textMain">'.$currencies->display_price($order->products[$i]['final_price'], $order->products[$i]['tax'], $order->products[$i]['qty'],true).'&nbsp;</td></tr>' .
										'<tr><td colspan="4" height="1" class="textBorder">' . tep_draw_separator('pixel_trans.gif',10,1) . '</td</tr>';
			}
        }

		$products_ordered = '<table border="0" cellpadding="0" cellspacing="0" width="100%">' .
							'<tr height="30" class="main"><td width="20"><b>' . TEXT_QUANTITY .'</b></td><td colspan="2"><b>'.TEXT_PRODUCTS_NAME.'</b></td><td class="main"><b>SKU</b></td><td align="right" width="100"><b>Price</b></td></tr>' . $products_ordered;

		$products_ordered.="</table>";

		$merge_details[ORDR_NO]=$item_number;
		$merge_details[ORDR_OL]=tep_href_link(FILENAME_ACCOUNT_HISTORY_INFO, 'order_id=' . $item_number, 'SSL', false);
		$merge_details[ORDR_OP]=strftime(DATE_FORMAT_LONG);
		$merge_details[ORDR_OM]=$order->info['comments'];
		$merge_details[ORDR_PO]=$products_ordered;
		$order_totals=$order->totals;
		
		
		$order_totals_str="<table border='0' cellpadding='2' cellspacing='0' width='100%'>";
		for ($i=0, $n=sizeof($order_totals); $i<$n; $i++) {
			if ($order_totals[$i]['class']=='ot_total'){
				$class="class='textTotal'";
			} else if ($i%2==0){
				$class="class='textTableTotalE'";
			} else {
				$class="class='textTableTotalO'";
			}
			if($order_totals[$i]['class']=='ot_tax'){
				$order_totals_str.= '<tr height="21"><td ' . $class . ' align="right">' . TEXT_TAX . '</td><td ' . $class . ' align="right" width="100">' . strip_tags($order_totals[$i]['text']) . "</td>";
			}else if($order_totals[$i]['class']=='ot_shipping'){
				$order_totals_str.= '<tr height="21"><td ' . $class . ' align="right">' . TEXT_SHIPPING . '</td><td ' . $class . ' align="right" width="100">' . strip_tags($order_totals[$i]['text']) . "</td>";
			}else if($order_totals[$i]['class']=='ot_total'){
				$order_totals_str.= '<tr height="21"><td ' . $class . ' align="right">' . TEXT_TOTAL . '</td><td ' . $class . ' align="right" width="100">' . strip_tags($order_totals[$i]['text']) . "</td>";
			}else if($order_totals[$i]['class']=='ot_subtotal'){
				$order_totals_str.= '<tr height="21"><td ' . $class . ' align="right">' . TEXT_SUBTOTAL . '</td><td ' . $class . ' align="right" width="100">' . strip_tags($order_totals[$i]['text']) . "</td>";
			}
		}
		$order_totals_str.="</table>";

		$merge_details[ORDR_OT]=$order_totals_str;
		//customer details
		$merge_details[CUST_CF]=$order->customer['firstname'];
		$merge_details[CUST_CL]=$order->customer['lastname'];
		$merge_details[CUST_CM]=$order->customer['company'];
		$merge_details[TEXT_SN]=STORE_OWNER;
		$merge_details[CUST_CT]=$order->customer['street_address'];
		$merge_details[CUST_CS]=$order->customer['suburb'];
		$merge_details[CUST_CC]=$order->customer['city'];
		$merge_details[CUST_CP]=$order->customer['postcode'];
		$merge_details[CUST_CE]=$order->customer['state'];
		$merge_details[CUST_CU]=$order->customer['country'];
		$merge_details[CUST_CO]=$order->customer['telephone'];
		$merge_details[CUST_CA]=$order->customer['email_address'];
		
		
		//Billing details
		$merge_details[BILL_NA]=$order->billing['name'];
		$merge_details[BILL_CM]=$order->billing['company'];
		$merge_details[BILL_CT]=$order->billing['street_address'];
		$merge_details[BILL_CS]=$order->billing['suburb'];
		$merge_details[BILL_CC]=$order->billing['city'];
		$merge_details[BILL_CP]=$order->billing['postcode'];
		$merge_details[BILL_CE]=$order->billing['state'];
		$merge_details[BILL_CU]=$order->billing['country'];
	
		//delivery details
		$merge_details[DELI_NA]=$order->delivery['name'];
		$merge_details[DELI_CM]=$order->delivery['company'];
		$merge_details[DELI_CT]=$order->delivery['street_address'];
		$merge_details[DELI_CS]=$order->delivery['suburb'];
		$merge_details[DELI_CC]=$order->delivery['city'];
		$merge_details[DELI_CP]=$order->delivery['postcode'];
		$merge_details[DELI_CE]=$order->delivery['state'];
		$merge_details[DELI_CU]=$order->delivery['country'];

		$merge_details[ORDR_PM]=$order->info['payment_method'];
		
		$merge_details['Store_Link']='<a href="' . tep_href_link(FILENAME_DEFAULT) . '" style="font-family:Arial, Helvetica, sans-serif;font-size:13px;color:#3966B1;font-weight:bold;text-decoration:none;">' . STORE_OWNER . '</a>';
		$merge_details['Telephone']=$order->customer['telephone'];
		$merge_details['Order_Link']='<a href="' . tep_href_link(FILENAME_ACCOUNT_HISTORY_INFO, 'order_id=' . $item_number, 'SSL', false) . '" style="font-family:Arial, Helvetica, sans-serif;font-size:13px;color:#3966B1;font-weight:bold;text-decoration:none;">' . 'Click Here' . '</a>';
		//$merge_details['Store_Logo']='<img src="' . tep_href_link(DIR_WS_IMAGES . 'template_logo.png') . '" title="' . STORE_NAME . '">';
		$merge_details['Store_Logo']='<img src="' . tep_href_link(DIR_WS_TEMPLATES . TEMPLATE_NAME . '/'. DIR_WS_IMAGES . COMPANY_LOGO) . '" title="' . STORE_NAME . '">';
		
		$send_details[0]['to_name']=$order->customer['firstname'] . ' ' . $order->customer['lastname'];
		$send_details[0]['to_email']=$order->customer['email_address'];
		$send_details[0]['from_name']=STORE_OWNER;
		$send_details[0]['from_email']=STORE_OWNER_EMAIL_ADDRESS;
	
	  // send emails to other people    
		if (SEND_EXTRA_ORDER_EMAILS_TO != '') {
			$send_details[1]['to_name']="";
			$send_details[1]['to_email']=SEND_EXTRA_ORDER_EMAILS_TO;
			$send_details[1]['from_name']=STORE_OWNER;
			$send_details[1]['from_email']=STORE_OWNER_EMAIL_ADDRESS;
		}
		tep_send_default_email("PRD",$merge_details,$send_details);
      };

    };

  };
function notify_log($file_contents){
	return;
	$file = fopen("images/paypal_log.txt","a+");
	fwrite($file,$file_contents);
	fclose($file);
}
?>