<?php
	
class AppController extends Controller{
		var $components = Array('SwiftMailer', 'Auth', 'Email', 'Session', 'Facebook.Connect', 'Uploader.Uploader', 'FormKeeper.FormKeeper', 'Recaptcha.Captcha' => array( 
		'private_key' => '6LcDt8sSAAAAAEnkcMKDiFX1QtIovebWAH9lUDEm',
		'public_key' => '6LcDt8sSAAAAAHggUKIrTj6zNQx4jkNU0raWlO_Y'),'Cookie');
		var $helpers = array('Html','Form','PaypalIpn.Paypal', 'Session', 'Facebook.Facebook', 'FormKeeper.FormKeeper', 'Recaptcha.CaptchaTool'); 
		var $uses = array('Reservation', 'Topic');
		
		function beforeFilter(){
		   
		  //$this->set('facebook_user', $this->Connect->user());
	
			define('RESERVATION_FEE','.12');
			$this->Auth->allow('signup','validateform','create','display');// controller actions unauthenticated users have access too, which then renders the view
			$this->Auth->authError = 'You must have an account to view this page. Please sign in or sign up for an account';
			$this->Auth->loginError = 'Incorrect username/password combination';
			//debug($this->Auth->user());
			$this->set('searchbar',0);
			if($this->Auth->isAuthorized())
			{
				$this->set('auth','1');
				$messages = $this->Topic->find('count', array('conditions' => array('Topic.viewed' => '0', 'Topic.to_user'=>$this->Auth->user('id'))));
				$bookings = $this->Reservation->find('count', array('conditions' => array('Reservation.status' => '1', 'Reservation.host_id'=>$this->Auth->user('id'))));
				$this->set('messagesCount', $messages);
				$this->set('reservationsCount', $bookings);
				
			}
			else{
				$this->set('auth','0');
			}
				$this->Auth->loginRedirect = array('controller' => 'messages', 'action' => 'mymessages');
		
			
			}
		
		
		  function afterPaypalNotification($txnId){ 
    //Here is where you can implement code to apply the transaction to your app. 
    //for example, you could now mark an order as paid, a subscription, or give the user premium access. 
    //retrieve the transaction using the txnId passed and apply whatever logic your site needs. 
     
    $transaction = ClassRegistry::init('PaypalIpn.InstantPaymentNotification')->findById($txnId); 
    $this->log($transaction['InstantPaymentNotification']['id'], 'paypal'); 

    //Tip: be sure to check the payment_status is complete because failure transactions  
    //     are also saved to our database for review. 

    if($transaction['InstantPaymentNotification']['payment_status'] == 'Pending' && $transaction['InstantPaymentNotification']['pending_reason'] == 'authorization'){ 
        $reservationId = $transaction['InstantPaymentNotification']['item_number'];	
		 $this->log($reservationId, 'paypal'); 
		$this->Reservation->id = $reservationId;
		
		$reservation = $this->Reservation->find('first', array('Reservation.id' => $reservationId));
		
		if($transaction['InstantPaymentNotification']['mc_gross'] == $reservation['Reservation']['total_amount']){
			$this->Reservation->saveField('status', 1, array('callbacks' => 'false', 'validate' => 'false'));
		}else{
			$this->Reservation->saveField('status', 4, array('callbacks' => 'false', 'validate' => 'false'));
			$this->sendEmail("support@reservationresources.com", "ID# ".$reservationId." Payment amounts don't match!", "payment");
		}
		$this->sendEmail("harry@reservationresources.com", "PAYMENT NOTIFICATION ".$reservationId, "payment");
    } 
    else { 
      //Oh no, better look at this transaction to determine what to do; like email a decline letter. 
    } 
  } 
  
  	function _PPHttpPost($methodName_, $nvpStr_) {
		$this->autoRender = false;
		$environment = 'sandbox';	// or 'beta-sandbox' or 'live'
		// Set up your API credentials, PayPal end point, and API version.
		$API_UserName = urlencode('invoice_api1.reservationresources.com');
		$API_Password = urlencode('REQ6BD9BD3BHEZB3');
		$API_Signature = urlencode('A9Ewuf-6vQ6w3KC6MRDfkJjmvTFgAeDiXfKaIz4nBx1D5tDvq1cSyvCs');
	
		$API_UserName = urlencode('shahru_1322843474_biz_api1.gmail.com');
		$API_Password = urlencode('1322843520');
		$API_Signature = urlencode('AafdLz1r6EWooI64eLNUccpog7G0AxeVDUzI.vjZ.0BI5Ch0mGLGkfBp');
		
		$API_Endpoint = "https://a...content-available-to-author-only...l.com/nvp";
		if("sandbox" === $environment || "beta-sandbox" === $environment) {
			$API_Endpoint = "https://api-3t.$environment.paypal.com/nvp";
		}
		$version = urlencode('51.0');

		// Set the curl parameters.
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
		curl_setopt($ch, CURLOPT_VERBOSE, 1);

		// Turn off the server and peer verification (TrustManager Concept).
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);

		// Set the API operation, version, and API signature in the request.
		$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";

		// Set the request as a POST FIELD for curl.
		curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);

		// Get response from the server.
		$httpResponse = curl_exec($ch);

		if(!$httpResponse) {
			exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
		}

		// Extract the response details.
		$httpResponseAr = explode("&", $httpResponse);

		$httpParsedResponseAr = array();
		foreach ($httpResponseAr as $i => $value) {
			$tmpAr = explode("=", $value);
			if(sizeof($tmpAr) > 1) {
				$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
			}
		}

		if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
			exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
		}

		return $httpParsedResponseAr;
		
		/* Set request-specific fields.
			$authorizationID = urlencode('example_authorization_id');
			$amount = urlencode('example_amount');
			$currency = urlencode('USD');							// or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
			$completeCodeType = urlencode('Complete');				// or 'NotComplete'
			$invoiceID = urlencode('example_invoice_id');
			$note = urlencode('example_note');

			// Add request-specific fields to the request string.
			$nvpStr="&AUTHORIZATIONID=$authorizationID&AMT=$amount&COMPLETETYPE=$completeCodeType&CURRENCYCODE=$currency&NOTE=$note";

			// Execute the API operation; see the PPHttpPost function above.
			$httpParsedResponseAr = PPHttpPost('DoCapture', $nvpStr);

			if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
				exit('Capture Completed Successfully: '.print_r($httpParsedResponseAr, true));
			} else  {
				exit('DoCapture failed: ' . print_r($httpParsedResponseAr, true));
			}
		*/
	}
  
  		
		function deleteimage($name = null, $property  = null){//pick up here image handling 11/29/11
			$this->autoRender = false;
			
			if($this->Uploader->delete('user_photos/'.$this->Auth->user('id').'/'.$property.'/'.$name)&&$this->Uploader->delete('user_photos/'.$this->Auth->user('id').'/'.$property.'/resized/'.$name)){
				return  true;
			
			}
			else{
				return false;
			}
			
		
		}
/*
the following 2 functions adds images to a property.
the reason why i had to create 2 functions is becuase they array come in diffrently
based upon if there adding images for the first time or just adding new images to an already
existing property
*/
	function uploadpropertypics($id = null){
				
				$this->autoRender  = false;
				$folder = new Folder('user_photos/'.DS.$this->Auth->user('id').DS.$id,true);
				$resized  = new Folder('user_photos/'.DS.$this->Auth->user('id').DS.$id.DS.'resized',true);
				$this->Uploader->uploadDir = '/user_photos'.DS.$this->Auth->user('id').DS.$id.'/';
					
				for($i = 1; $i < count($this->data['Images']);$i++){
				//debug(count($this->data['Images']));
				 //debug($this->Uploader->tempDir);
						if ($data = $this->Uploader->upload('Images.file'.$i)){
							
							$scale = $this->Uploader->resize(array('width' => 890, 'append' => 'scaled','quality'=>100));
							$this->Uploader->move($scale, 'user_photos/'.$this->Auth->user('id').'/'.$id.'/resized/'.$data['name'],false);
							}
					
					}
				
				}
				
		$this->redirect(array('controller' => 'properties', 'action' => 'viewproperty',$id));	
	
		function addphotos($id = null,$path = null){
		
				$this->autoRender  = false;
				$folder = new Folder('user_photos/'.DS.$this->Auth->user('id').DS.$id,true);
				$resized  = new Folder('user_photos/'.DS.$this->Auth->user('id').DS.$id.DS.'resized',true);
				$this->Uploader->uploadDir = $path;
				
			
				
				for($i = 1; $i < count($this->data['Images']);$i++){
						
						
						if ($data = $this->Uploader->upload('file'.$i)) {
						$scale = $this->Uploader->scale(array('width' => 890, 'append' => 'scaled'));
					
						$this->Uploader->move($scale, 'user_photos/'.DS.$this->Auth->user('id').DS.$id.'/resized/'.$data['name'],false);
				
						}
						
				}
			
	}
	
	function cleanString($msg = NULL)
	{
		preg_match("/[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})/i", $msg, $matches);
		if(!empty($matches))
			return false;
		$msg =  preg_replace( "/[^a-zA-Z0-9]/i", "", $msg);
		$msg = strip_tags($msg);
		$unclean = "";

		$k = 0;
		for($i = 0; $i < strlen($msg); $i++)
		{
			if($k<7)
			{
				$k = 0;
				if(is_numeric(substr($msg, $i, 1)))
				{
					for($j = $i; $j < strlen($msg); $j++)
					{
						if(is_numeric(substr($msg, $j, 1)))
						{
							$k++;
						}
						else
							$k = 0;
						
						$i = $j;
						//Pushes the larger for loop to continue where this one left off after checking numbers in a row
					}
					
				}
			}
			else
				$i = strlen($msg);
			
		}
		
		if($k<7)
			return true;
		else
			return false; //UNCLEAN STRING
	}

 
	function sendEmail($email, $subject, $layout) {
	/*$this->Email->reset();
    $this->Email->to = $email;
    $this->Email->subject = $subject;
    $this->Email->replyTo = 'support@reservationresources.com';
    $this->Email->from = 'Reservation Resources <noreply@reservationresources.com>';
	//debug($this->Email);
    $this->Email->template = $layout; // note no '.ctp'
    //Send as 'html', 'text' or 'both' (default is 'text')
    $this->Email->sendAs = 'html'; // because we like to send pretty mail
    //Do not pass any args to send()
    $this->Email->send(); 
	
	ONLY WORKS FOR ONE EMAIL FOR SOME REASON
	*/
		//Function is copy + pasted in Profiles / verify && Users / forgotpassword && Harries/sendEmail
		$this->SwiftMailer->smtpType = 'tls'; 
        $this->SwiftMailer->smtpHost = 'smtp.gmail.com'; 
        $this->SwiftMailer->smtpPort = 587; 
        $this->SwiftMailer->smtpUsername = 'support@reservationresources.com'; 
        $this->SwiftMailer->smtpPassword = 'hARRY1234%^'; 

        $this->SwiftMailer->sendAs = 'html'; 
        $this->SwiftMailer->from = 'support@reservationresources.com'; 
        $this->SwiftMailer->fromName = 'Support Team'; 
        $this->SwiftMailer->to = $email; 
        //set variables to template as usual 
        try { 
            if(!$this->SwiftMailer->send($layout, $subject)) { 
                $this->log("Error sending email"); 
            } 
        } 
        catch(Exception $e) { 
              $this->log("Failed to send email: ".$e->getMessage()); 
        } 

	 }	
	
}
?>