<?php
class Total_Kadobon_NotifyController extends Mage_Core_Controller_Front_Action {
  
	public function indexAction()
	{
	    if(empty($_GET))
	    {
	        echo 'Only Kadobon can call this page properly';
	        exit;
	    }
	    
	    $debug_email=Mage::getStoreConfig('payment/kadobon/debug_email');

        ob_start();
            echo "POST:\n";
            print_r($_POST);
            echo "GET:\n";
            print_r($_GET);
            echo "\n";
            echo "SERVER:\n";
            print_r($_SERVER);
            echo "\n\n";
            $debug_info = ob_get_contents();
        ob_clean();
        
        if($debug_email!='')
        {
            mail($debug_email, 'Kadobon notify. Initial variables.', $debug_info);
        }
        
		// If there is payment kadobon send 'amount' variable
		if(isset($_GET['amount']))
		{
			$mode="SUCCESS";
			$amount=$_GET['amount'];
		}
		// If there was no payment kadobon send 'value' variable
		elseif(isset($_GET['value']))
		{
			$mode="ERROR";
			$amount=$_GET['value'];
		}
		
		$order_id=$_GET['reference']; 
		
		switch($mode)
		{
			case 'SUCCESS':	$returned_vars =  
										  $order_id .
										  "-" .
										  $amount .
										  Mage::getStoreConfig('payment/kadobon/saltcode');
							break;

			case 'ERROR':	$returned_vars = 
										  $order_id .
										  "-" .
										  $amount .
										  Mage::getStoreConfig('payment/kadobon/saltcode');		
							break;			  		
		}
		
		$returned_vars_sha512 = hash("sha512",$returned_vars);
		
		$redirect='';
		
		if((isset($_GET["sign"])) AND (strtoupper($_GET["sign"])==strtoupper($returned_vars_sha512)))
		{
			//check the status online
			
			$kadobon_answer = "";
			$ch = curl_init();
			$timeout = 5; // set to zero for no timeout
			curl_setopt ($ch, CURLOPT_URL, "http://www.kadobon-online.nl/beheer/checkorderback.aspx?merchantId=".Mage::getStoreConfig('payment/kadobon/merchant_key')."&reference=".$order_id);
			curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
			$kadobon_answer = curl_exec($ch);
			curl_close($ch);
		
			//trim spaces
			$kadobon_answer = trim($kadobon_answer);
			
			// Updating order    
            $order=Mage::getModel('sales/order')->loadByIncrementId($order_id);
            $currentStateAndStatus=array($order->getState(), $order->getStatus());
					
			// setting status depending on the kadobon_answer
			switch($kadobon_answer)
			{
				case "awaiting":
						$setState=Mage::getStoreConfig('payment/kadobon/order_state_wachten');
						$setStatus=Mage::getStoreConfig('payment/kadobon/order_status_wachten');
						break;
				case "ok":
						$setState=Mage::getStoreConfig('payment/kadobon/order_state_betaald');
						$setStatus=Mage::getStoreConfig('payment/kadobon/order_status_betaald');

						$redirect=Mage::getStoreConfig('payment/kadobon/success_redirect');
						break;
				case "notfound":
						$setState=Mage::getStoreConfig('payment/kadobon/order_state_mislukt');
						$setStatus=Mage::getStoreConfig('payment/kadobon/order_status_mislukt');
						
                        if($kadobon_quote_id=Mage::getSingleton('checkout/session')->getKadobonQuoteId(true))
                        {
                            Mage::getSingleton('checkout/session')->setQuoteId($kadobon_quote_id);    
                        }
                        
                        $redirect=Mage::getStoreConfig('payment/kadobon/failure_redirect');
						break;
				default:
						$setState=$order->getState();	
						$setStatus=$order->getStatus();
						
                        if($kadobon_quote_id=Mage::getSingleton('checkout/session')->getKadobonQuoteId(true))
                        {
                            Mage::getSingleton('checkout/session')->setQuoteId($kadobon_quote_id);    
                        }
						break;				
			}
			
            if($currentStateAndStatus!=array($setState, $setStatus))
            {
                try
                {
                    $order->setState($setState);
                    $order->setStatus($setStatus);
                    
                    $order->addStatusHistoryComment("New state: '".$setState."'; New status: '".$setStatus."'.");
                    
                    $order->save();
                    
                    if($kadobon_answer=='ok' && !$order->getEmailSent())
                    {
                        $order->sendNewOrderEmail();
                    }
                }
                catch(Exception $ex)
                {
                    $debug_info="Exception:\n\n";
                    $debug_info=$ex->getMessage();
                    $debug_info="Time: ".date('Y-m-d H:i:s', time());
                                        
                    if($debug_email!='')
                    {
                        mail($debug_email, 'Kadobon notify. Exception.', $debug_info);
                    }
                }
            }	
		}

       return $this->_redirect($redirect?$redirect:'/');
	}
}
