<?php

//require_once ("MAILER/smtpservice.php");

class PayPal_IPN {
	
	function connect($sql){
		App::uses('ConnectionManager', 'Model');
        $dataSource = ConnectionManager::getDataSource('default');
 
        $link= mysql_connect($dataSource->config['host'],$dataSource->config['login'],$dataSource->config['password']);
		mysql_select_db( $dataSource->config['database'], $link);
		$result = mysql_query($sql);
		
		if (!$result) {
		    die('Could not query:' . mysql_error());
		}
        return $result;
	}
	
	function ipn($ipn_data) {
		
	 	header('HTTP/1.1 200 OK');
	 	 $item_name        = $_POST['item_name'];
		$item_number      = $_POST['item_number'];
		$payment_status   = $_POST['payment_status'];
		$payment_amount   = $_POST['mc_gross'];
		$payment_currency = $_POST['mc_currency'];
		$txn_id           = $_POST['txn_id'];
		$receiver_email   = $_POST['receiver_email'];
		$payer_email      = $_POST['payer_email'];
		$ctIdcustom       = $_POST['custom'];
		
		$finalctId=explode(",",trim($ctIdcustom));
		
		$req = 'cmd=_notify-validate';               // Add 'cmd=_notify-validate' to beginning of the acknowledgement
		foreach ($_POST as $key => $value) {         // Loop through the notification NV pairs
		  $value = urlencode(stripslashes($value));  // Encode these values
		  $req  .= "&$key=$value";                   // Add the NV pairs to the acknowledgement
		}
		
		$header  = "POST /cgi-bin/webscr HTTP/1.1\r\n";                    // HTTP POST request
		$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
		$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
		
		// Open a socket for the acknowledgement request
		$fp = fsockopen('https://www.sandbox.paypal.com/cgi-bin/webscr', 443, $errno, $errstr, 30);
		
		// Send the HTTP POST request back to PayPal for validation
		fputs($fp, $header . $req);
		
		while (!feof($fp)) {                     // While not EOF
			$res = fgets($fp, 1024);               // Get the acknowledgement response
			if (strcmp ($res, "VERIFIED") == 0) {
				
				if($finalctId[2]==1){
					$this->Course->query("UPDATE transactions SET `transctionStatus`=1,`txn_id`='$txn_id',`payer_email`='$payer_email' WHERE batchID='".$finalctId[1]."'" );
					$this->Course->query("UPDATE courses SET `courseStatus`=3 WHERE batchID='".$finalctId[0]."'");
				}elseif ($finalctId[2]==2){
					$this->Course->query("UPDATE transactions SET `transctionStatus`=1,`txn_id`='$txn_id',`payer_email`='$payer_email' WHERE id='".$finalctId[1]."'" );
					$this->Course->query("UPDATE courses SET `courseStatus`=3 WHERE id='".$finalctId[0]."'");
				}
			
			}else{
			}
		}
		
	}
	}
