<?php
/*
ipn.php - example code used for the tutorial:

PayPal IPN with PHP
How To Implement an Instant Payment Notification listener script in PHP
http://www.micahcarrick.com/paypal-ipn-with-php.html

(c) 2011 - Micah Carrick
*/

//Define file lavel constant
define('ADMIN_EMAIL','info@trakvan.com');
define('TEST_CLIENT_EMAIL',true);


// tell PHP to log errors to ipn_errors.log in this directory
ini_set('log_errors', true);
ini_set('error_log', dirname(__FILE__).'/ipn_errors.log');

// intantiate the IPN listener
include('ipnlistener.php');
$listener = new IpnListener();

  // 5. Ensure the transaction is not a duplicate.
    mysql_connect('localhost', 'tv2012a_mohandba', 'k9im-~C?H9xMqStED') or exit(0);
    mysql_select_db('tv2012a_radhedb01') or exit(0);
	
// tell the IPN listener to use the PayPal test sandbox
$listener->use_sandbox = false;

// try to process the IPN POST
try {
    $listener->requirePostMethod();
    $verified = $listener->processIpn();
} catch (Exception $e) {
    error_log($e->getMessage());
    exit(0);
}
	   
if ($verified) {
    $errmsg = '';   // stores errors from fraud checks
    
    //Make sure the payment status is "Completed" 
    if ($_POST['payment_status'] == 'Completed' || $_POST['payment_status']=='In progress' || $_POST['payment_status']=='Processing') { 
        $status=1; 
    }else{
	    $status=0;
	}
	
	if($status==1 && $_GET['oid']==$_POST['invoice']){
    $txn_id = mysql_real_escape_string($_POST['txn_id']);
    $sql = "SELECT COUNT(*) FROM tbl_master_orders WHERE payment_tran_id = '$txn_id'";
    $r = mysql_query($sql);
    
    if (!$r) {
        error_log(mysql_error());
        exit(0);
    }
    
    $exists = mysql_result($r, 0);
    mysql_free_result($r);
    
    if ($exists) {
        $errmsg .= "'txn_id' has already been processed: ".$_POST['txn_id']."\n";
    }
    
    if (!empty($errmsg)) {
    
        // manually investigate errors from the fraud checking
        $body = "IPN failed fraud checks: \n$errmsg\n\n";
        $body .= $listener->getTextReport();
        mail('usha.kalura@efst.in', 'IPN Fraud Warning', $body);
        
    } else {
        // add this order to a table of completed orders
        $payment_status = mysql_real_escape_string($_POST['payment_status']);
        $mc_gross = mysql_real_escape_string($_POST['mc_gross']);
		$order_id = mysql_real_escape_string($_POST['invoice']);
        $sql = "UPDATE tbl_master_orders set payment_tran_id='$txn_id', subtotal='$mc_gross', payment_status='$payment_status' where id='$order_id'";
        if (!mysql_query($sql)) {
            error_log(mysql_error());
            exit(0);
        }else{
	   sendOrderEmail($order_id);
		}
    }
    
} else {
   sendOrderEmail(mysql_real_escape_string($_GET['oid']));
}
}

function sendOrderEmail($order_id){
$sql="SELECT u.name, u.email, mo.id as moid, mo.payment_status as payment_status,mo.subtotal,mo.customer_id,mo.created_date, mo.discount_coupon_id, mo.payment_tran_id, mo.payment_method_id, od.order_id, od.buy_id, od.buy_title, od.price,od.quantity, od.buy_type FROM ((`tbl_master_orders` as mo left join tbl_order_details as od on mo.id=od.order_id) inner join tbl_user_masters as u on u.id=mo.customer_id) WHERE od.order_id='$order_id'";
$query=mysql_query($sql);
$count="SELECT count(*) as c FROM ((`tbl_master_orders` as mo left join tbl_order_details as od on mo.id=od.order_id) inner join tbl_user_masters as u on u.id=mo.customer_id) WHERE od.order_id='$order_id'";
$queryC=mysql_query($count);
$c=mysql_fetch_object($queryC);
$artisthtml='<div style="font-family: arial; font-size:12px;">';
$i=1;
$j=$c->c;
$html='<div style="font-family: arial; font-size:12px;">';
$i=1;
$j=$c->c;
while($order=mysql_fetch_object($query)){
if($i==1){
$to=$order->email;
$subject="TrakVan Order #".$order->order_id;
$html.='<img src="http://www.trakvan.com/trakvanapp/img/site/logo-trackvan.png" border="0" width="253" height="54" alt="TrakVan" title="TrakVan">';
$html.='<h1 style="font-size:22px; font-weight:normal;">Hello, '.$order->name.'&nbsp;('.$order->email.')</h1>';
$html.='Thank you for your order from TrakVan. If you have any questions about your order please contact us at support@trakvan.com.<br/>Your order confirmation is below. Thank you again for your business.';
$html.='<h2 style="font-size:20px; font-weight:normal;">Your Order #'.$order->order_id.'&nbsp;(placed on '.@date('M d,Y',strtotime($order->created_date)).')</h2>
			 <table class="tbl-listing" width="96%" cellspacing="0" cellpadding="0" id="payment-order" border="0" style="border: 1px solid #CCC; margin-bottom: 20px;">
			 <tr>
			  <th colspan="2" style="padding: 8px 8px 8px 8px; font-size:14px; background:#f7f7f7;border-bottom: 1px solid #CCC;"><h4 style="margin:0px 0px; text-align:left; font-size:15px;">Payment Information:</h4></th>
			 </tr>
			 <tr>
			  <td style="padding: 8px 8px 8px 8px; font-size:14px;">Payment Method:</td>
			  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.(($order->payment_method_id==1) ? "Paypal":"").'</td>
			 </tr>
			  <tr>
			  <td style="padding: 8px 8px 8px 8px; font-size:14px;">Transaction Id:</td>
			  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.(($order->payment_tran_id>0) ? $order->payment_tran_id:0).'</b></td>
			 </tr>
			 </table>
			 
			 <table class="tbl-listing" width="96%" cellspacing="0" cellpadding="0" id="payment-order" border="0" style="border: 1px solid #CCC; margin-bottom: 20px;">
			 <tr>
			  <th style="padding: 8px 8px 8px 8px; font-size:14px;background:#f7f7f7;border-bottom: 1px solid #CCC;"><h4 style="margin:0px 0px; text-align:left; font-size:15px;">Order Status:</h4></th>
			  <th style="padding: 8px 8px 8px 8px; font-size:14px;background:#f7f7f7;border-bottom: 1px solid #CCC;">'.ucfirst($order->payment_status).'</th>
			 </tr>
			 
			 </table>
 
			  <table class="tbl-listing" width="96%" cellspacing="0" cellpadding="0" id="payment-order" border="0" style="border: 1px solid #CCC; margin-bottom: 20px;">
			 <tr>
			  <td class="heading" style="padding: 8px 8px 8px 8px; font-size:14px; background:#e4e4e4;"><b>Sr. No</b></td>
			  <td class="heading" style="padding: 8px 8px 8px 8px; font-size:14px; background:#e4e4e4;"><b>Item Name</b></td>
			  <td class="heading" style="padding: 8px 8px 8px 8px; font-size:14px; background:#e4e4e4;"><b>Type</b></td>
			  <td class="heading" style="padding: 8px 8px 8px 8px; font-size:14px; background:#e4e4e4;"><b>Qty.</b></td>
			  <td class="heading" style="padding: 8px 8px 8px 8px; font-size:14px; background:#e4e4e4;"><b>Price</b></td>
			  <td class="heading" style="padding: 8px 8px 8px 8px; font-size:14px; background:#e4e4e4;"></td>
			 </tr>';
			 
$returnString = artistInfo($order->buy_type,$order->buy_id);
$returnArray = explode('|',$returnString); 

$artistName = $returnArray[1];
$to1=$returnArray[0];
$subject1="TrakVan Order For Artist #".$order->order_id;
$artisthtml.='<img src="http://www.trakvan.com/trakvanapp/img/site/logo-trackvan.png" border="0" width="253" height="54" alt="TrakVan" title="TrakVan">';
$artisthtml.='<h1 style="font-size:22px; font-weight:normal;">Hello '.$artistName.',</h1>';
$artisthtml.='A new order has been placed. Following are the order details related to that order.';
$artisthtml.='<h2 style="font-size:20px; font-weight:normal;">Your Order #'.$order->order_id.'&nbsp;(placed on '.@date('M d,Y',strtotime($order->created_date)).')</h2>
			<table class="tbl-listing" width="96%" cellspacing="0" cellpadding="0" id="payment-order" border="0" style="border: 1px solid #CCC; margin-bottom: 20px;">
			 <tr>
			  <th colspan="2" style="padding: 8px 8px 8px 8px; font-size:14px; background:#f7f7f7;border-bottom: 1px solid #CCC;"><h4 style="margin:0px 0px; text-align:left; font-size:15px;">Cutomer Information:</h4></th>
			 </tr>
			 <tr>
			  <td style="padding: 8px 8px 8px 8px; font-size:14px;">Cutsomer Name:</td>
			  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.$order->name.'</td>
			 </tr>
			  <tr>
			  <td style="padding: 8px 8px 8px 8px; font-size:14px;">Cutsomer Email:</td>
			  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.$order->email.'</b></td>
			 </tr>
			 </table>
			 <table class="tbl-listing" width="96%" cellspacing="0" cellpadding="0" id="payment-order" border="0" style="border: 1px solid #CCC; margin-bottom: 20px;">
			 <tr>
			  <th colspan="2" style="padding: 8px 8px 8px 8px; font-size:14px; background:#f7f7f7;border-bottom: 1px solid #CCC;"><h4 style="margin:0px 0px; text-align:left; font-size:15px;">Payment Information:</h4></th>
			 </tr>
			 <tr>
			  <td style="padding: 8px 8px 8px 8px; font-size:14px;">Payment Method:</td>
			  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.(($order->payment_method_id==1) ? "Paypal":"").'</td>
			 </tr>
			  <tr>
			  <td style="padding: 8px 8px 8px 8px; font-size:14px;">Transaction Id:</td>
			  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.(($order->payment_tran_id>0) ? $order->payment_tran_id:0).'</b></td>
			 </tr>
			 </table>
			 
			 <table class="tbl-listing" width="96%" cellspacing="0" cellpadding="0" id="payment-order" border="0" style="border: 1px solid #CCC; margin-bottom: 20px;">
			 <tr>
			  <th style="padding: 8px 8px 8px 8px; font-size:14px;background:#f7f7f7;border-bottom: 1px solid #CCC;"><h4 style="margin:0px 0px; text-align:left; font-size:15px;">Order Status:</h4></th>
			  <th style="padding: 8px 8px 8px 8px; font-size:14px;background:#f7f7f7;border-bottom: 1px solid #CCC;">'.ucfirst($order->payment_status).'</th>
			 </tr>
			 
			 </table>
 
			  <table class="tbl-listing" width="96%" cellspacing="0" cellpadding="0" id="payment-order" border="0" style="border: 1px solid #CCC; margin-bottom: 20px;">
			 <tr>
			  <td class="heading" style="padding: 8px 8px 8px 8px; font-size:14px; background:#e4e4e4;"><b>Sr. No</b></td>
			  <td class="heading" style="padding: 8px 8px 8px 8px; font-size:14px; background:#e4e4e4;"><b>Item Name</b></td>
			  <td class="heading" style="padding: 8px 8px 8px 8px; font-size:14px; background:#e4e4e4;"><b>Type</b></td>
			  <td class="heading" style="padding: 8px 8px 8px 8px; font-size:14px; background:#e4e4e4;"><b>Qty.</b></td>
			  <td class="heading" style="padding: 8px 8px 8px 8px; font-size:14px; background:#e4e4e4;"><b>Price</b></td>
			  <td class="heading" style="padding: 8px 8px 8px 8px; font-size:14px; background:#e4e4e4;"></td>
			 </tr>';
			 
 }
  $html.='<tr>
  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.$i.'</b></td>
  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.$order->buy_title.'</td>
  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.$order->buy_type.'</td>
  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.$order->quantity.'</td>
  <td style="padding: 8px 8px 8px 8px; font-size:14px;">$'.$order->price.'</td>
  <td style="padding: 8px 8px 8px 8px; font-size:14px;"></td>
 </tr>';
 
 $artisthtml.='<tr>
  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.$i.'</b></td>
  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.$order->buy_title.'</td>
  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.$order->buy_type.'</td>
  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.$order->quantity.'</td>
  <td style="padding: 8px 8px 8px 8px; font-size:14px;">$'.$order->price.'</td>
  <td style="padding: 8px 8px 8px 8px; font-size:14px;"></td>
 </tr>';
 
 if($i==$j){
 $html.='<tr>
  <td colspan="4" align="right" style="text-align:right;padding: 8px 8px 8px 8px"><b>Total:</b></td>
  <td style="padding: 8px 8px 8px 8px">$'.$order->subtotal.'</td>
    <td></td>
 </tr>
  <tr>
  <td colspan="6" style="text-align:center;padding: 8px 8px 8px 8px; background:#f7f7f7;border-top: 1px solid #CCC;" class="thank-you">Thank you, TrakVan</td>
 </tr>';
 
  $artisthtml.='<tr>
  <td colspan="4" align="right" style="text-align:right;padding: 8px 8px 8px 8px"><b>Total:</b></td>
  <td style="padding: 8px 8px 8px 8px">$'.$order->subtotal.'</td>
    <td></td>
 </tr>
  <tr>
  <td colspan="6" style="text-align:center;padding: 8px 8px 8px 8px; background:#f7f7f7;border-top: 1px solid #CCC;" class="thank-you">Thank you, TrakVan</td>
 </tr>';
 
  } 
 $i++;
} 
$html.='</table></div>';
$artisthtml.='</table></div>';

 // Mail it
	
	$ipnText = '';
	if(!socketmail($to, $subject, $html)){
		$ipnText .= "Mail has been sent to user";
	  } else {
		$ipnText .= "Mail could not sent to user email";
	  }
	  
	  //This email goes to artist
	  
	  if(!socketmail($to1, $subject1, $artisthtml)){
		$ipnText .= "Mail has been sent to artist";
	  } else {
		$ipnText .= "Mail could not sent to artist email";
	  }

	//Send artist email copy to admin of trakvan
    
	if(!socketmail(ADMIN_EMAIL, $subject1, $artisthtml)){
		$ipnText .= "Mail has been sent to admin";
	  } else {
		$ipnText .= "Mail could not sent to admin email";
	  }
	
	
	//For Testing send email copy to client as well
	 
	 if (TEST_CLIENT_EMAIL) {
		if (!socketmail('me@masonfok.com', $subject1, $artisthtml)) {
			$ipnText .= "Mail has been sent to client email";
		} else {
			$ipnText .= "Mail could not sent to client email";
		} 
	 }

	//Notify me in email failure case
	if(!empty($ipnText)){
	error_log($ipnText, 1, "r.sengar@efst.in");
    }
/*while($order=mysql_fetch_object($query)){
if($i==1){
$email=artistInfo($order->buy_type,$order->buy_id);
$to1=$email;
$subject1="TrakVan Order For Artist #".$order->order_id;
$artisthtml.='<img src="http://www.trakvan.com/trakvanapp/img/site/logo-trackvan.png" border="0" width="253" height="54" alt="TrakVan" title="TrakVan">';
$artisthtml.='<h1 style="font-size:22px; font-weight:normal;">Hello, Artist</h1>';
$artisthtml.='A new order has been placed. Following are the order details related to that order.';
$artisthtml.='<h2 style="font-size:20px; font-weight:normal;">Your Order #'.$order->order_id.'&nbsp;(placed on '.@date('M d,Y',strtotime($order->created_date)).')</h2>
			<table class="tbl-listing" width="96%" cellspacing="0" cellpadding="0" id="payment-order" border="0" style="border: 1px solid #CCC; margin-bottom: 20px;">
			 <tr>
			  <th colspan="2" style="padding: 8px 8px 8px 8px; font-size:14px; background:#f7f7f7;border-bottom: 1px solid #CCC;"><h4 style="margin:0px 0px; text-align:left; font-size:15px;">Cutomer Information:</h4></th>
			 </tr>
			 <tr>
			  <td style="padding: 8px 8px 8px 8px; font-size:14px;">Cutsomer Name:</td>
			  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.$order->name.'</td>
			 </tr>
			  <tr>
			  <td style="padding: 8px 8px 8px 8px; font-size:14px;">Cutsomer Email:</td>
			  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.$order->email.'</b></td>
			 </tr>
			 </table>
			 <table class="tbl-listing" width="96%" cellspacing="0" cellpadding="0" id="payment-order" border="0" style="border: 1px solid #CCC; margin-bottom: 20px;">
			 <tr>
			  <th colspan="2" style="padding: 8px 8px 8px 8px; font-size:14px; background:#f7f7f7;border-bottom: 1px solid #CCC;"><h4 style="margin:0px 0px; text-align:left; font-size:15px;">Payment Information:</h4></th>
			 </tr>
			 <tr>
			  <td style="padding: 8px 8px 8px 8px; font-size:14px;">Payment Method:</td>
			  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.(($order->payment_method_id==1) ? "Paypal":"").'</td>
			 </tr>
			  <tr>
			  <td style="padding: 8px 8px 8px 8px; font-size:14px;">Transaction Id:</td>
			  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.(($order->payment_tran_id>0) ? $order->payment_tran_id:0).'</b></td>
			 </tr>
			 </table>
			 
			 <table class="tbl-listing" width="96%" cellspacing="0" cellpadding="0" id="payment-order" border="0" style="border: 1px solid #CCC; margin-bottom: 20px;">
			 <tr>
			  <th style="padding: 8px 8px 8px 8px; font-size:14px;background:#f7f7f7;border-bottom: 1px solid #CCC;"><h4 style="margin:0px 0px; text-align:left; font-size:15px;">Order Status:</h4></th>
			  <th style="padding: 8px 8px 8px 8px; font-size:14px;background:#f7f7f7;border-bottom: 1px solid #CCC;">'.ucfirst($order->payment_status).'</th>
			 </tr>
			 
			 </table>
 
			  <table class="tbl-listing" width="96%" cellspacing="0" cellpadding="0" id="payment-order" border="0" style="border: 1px solid #CCC; margin-bottom: 20px;">
			 <tr>
			  <td class="heading" style="padding: 8px 8px 8px 8px; font-size:14px; background:#e4e4e4;"><b>Sr. No</b></td>
			  <td class="heading" style="padding: 8px 8px 8px 8px; font-size:14px; background:#e4e4e4;"><b>Item Name</b></td>
			  <td class="heading" style="padding: 8px 8px 8px 8px; font-size:14px; background:#e4e4e4;"><b>Type</b></td>
			  <td class="heading" style="padding: 8px 8px 8px 8px; font-size:14px; background:#e4e4e4;"><b>Qty.</b></td>
			  <td class="heading" style="padding: 8px 8px 8px 8px; font-size:14px; background:#e4e4e4;"><b>Price</b></td>
			  <td class="heading" style="padding: 8px 8px 8px 8px; font-size:14px; background:#e4e4e4;"></td>
			 </tr>';
 }
  $artisthtml.='<tr>
  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.$i.'</b></td>
  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.$order->buy_title.'</td>
  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.$order->buy_type.'</td>
  <td style="padding: 8px 8px 8px 8px; font-size:14px;">'.$order->quantity.'</td>
  <td style="padding: 8px 8px 8px 8px; font-size:14px;">$'.$order->price.'</td>
  <td style="padding: 8px 8px 8px 8px; font-size:14px;"></td>
 </tr>';
 if($i==$j){
 $artisthtml.='<tr>
  <td colspan="4" align="right" style="text-align:right;padding: 8px 8px 8px 8px"><b>Total:</b></td>
  <td style="padding: 8px 8px 8px 8px">$'.$order->subtotal.'</td>
    <td></td>
 </tr>
  <tr>
  <td colspan="6" style="text-align:center;padding: 8px 8px 8px 8px; background:#f7f7f7;border-top: 1px solid #CCC;" class="thank-you">Thank you, TrakVan</td>
 </tr>';
  } 
 $i++;
} 
$artisthtml.='</table></div>';
	  if(!socketmail($to1, $subject1, $artisthtml)){
	  $ipnText = "Mail sent" ;
	  }else{
	  $ipnText = "Mail not sent" ;
	  }	*/
}

 function artistInfo($item_type, $item_id){
		 if($item_type=="album"){
				$q="select u.email as email from tbl_user_masters as u inner join tbl_albums as a ON a.user_id=u.id  where a.id='$item_id'";
				$r=mysql_query($q);
		}else{
				$q="select u.email as email from ((tbl_album_tracks as t inner join tbl_albums as a ON a.id=t.album_id) inner join tbl_user_masters as u on u.id=a.user_id) where t.id='$item_id'";
				$r=mysql_query($q);
		}
		while($result=mysql_fetch_object($r)){
		     
			 $artistName = $result->name;
			 $email= $result->email;
		
		}
		
		$returnResult = $email.'|'.$artistName;
		return $returnResult;
 }

 function socketmail($to, $subject, $message) {

	$headers  = 'MIME-Version: 1.0' . "\r\n";
	$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
	// Additional headers
	$headers .= 'From: Support <support@trakvan.com>';
	//$headers .= 'Cc: me@masonfok.com' . "\r\n";
	//$headers .= 'Bcc: info@e-fusionsoft.com' . "\r\n";
	// Mail it
	$h = fopen(dirname(__FILE__)."/ipn.txt",'w');
	fwrite($h,"$headers \n $to \n $subject \n $message") or die("Could not write to the file...");
	mail($to, $subject, $message, $headers);
} 
?>