<?php
/**
 * ****************************************************************
 * Project:      table-booking
 * Copyright:    Copyright (c) 2007
 * Company:      Thomas Niemann
 * ****************************************************************
 * Workfile:     ReservationManager.php
 * ****************************************************************
 * Description:  
 *                
 * ***************************************************************/
class ReservationManager extends BasicManager
{
    private $messageInstance 	= null;
    private $configInstance 	= null;
    private $validate 			= null;
    private $wsdl_file 			= null;
    private $username 			= null;
    private $password 			= null;
    /**
     * default Constructor
     */
    public function __construct()
    {
        $this->messageInstance 	= MessageLoader::getInstance();
        $this->configInstance 	= ConfigLoader::getInstance();
        $this->validate 		= new Validate();
        $this->wsdl_file 		= (string)$this->configInstance->getConfigPath("sopaServer");
        $this->username 		= (string)$this->configInstance->getAppSettings("soapLoginUsername");
        $this->password 		= Util::encode((string)$this->configInstance->getAppSettings("soapLoginPassword"));
    }
    public function insertReservation($_post, $_company_id)
    {
        //POST DATEN
        $postData = array();
        $postData['reservationHour'] 	= $_post['reservationHour'];
        $postData['reservationMinute'] 	= $_post['reservationMinute'];
        $postData['reservationdate'] 	= $_post['reservationdate'];
        $postData['lastname'] 			= ucfirst($_post['lastname']);
        $postData['firstname'] 			= ucfirst($_post['firstname']);
        $postData['menu_id'] 			= $_post['menu_id'];
        $postData['eat'] 				= $_post['eat'];
        $postData['numberofperson'] 	= $_post['numberofperson'];
        $postData['company'] 			= $_post['company'];
        $postData['telefon'] 			= $_post['telefon'];
        $postData['handy'] 				= $_post['handy'];
        $postData['email'] 				= $_post['email'];
        $postData['zipcode'] 			= $_post['zipcode'];
        $postData['street'] 			= ucfirst($_post['street']);
        $postData['city'] 				= ucfirst($_post['city']);
        $postData['info'] 				= $_post['info'];
        $postData['newsletter'] 		= $_post['newsletter'];
        $postData['sex'] 				= $_post['sex'];
        $postData['reasonId'] 			= $_post['reasonId'];
        $postData['watelist'] 			= isset($_post['watelist'])? 1 : 0;
        $birtday = "0000-00-00";
        if(is_array($_post['birthday']) && count($_post['birthday']) == 3)
		{			  
	        //birthday
	        $year	= is_numeric($_post['birthday']['Date_Year'])? $_post['birthday']['Date_Year'] : "0000";
	        $month	= is_numeric($_post['birthday']['Date_Month'])? $_post['birthday']['Date_Month'] : "00";
	        $day	= is_numeric($_post['birthday']['Date_Day'])? ((strlen($_post['birthday']['Date_Day']) < 2)? "0".$_post['birthday']['Date_Day'] : $_post['birthday']['Date_Day']) : "00";
			$birtday = $year."-".$month."-".$day;
		}
		$postData['birthday'] 			= $birtday;
		$postData['reservationArea'] 	= $_post['reservationArea'];
        $soapclient = new SoapClient($this->wsdl_file, array("trace" => 1, "exceptions" => 0));
        $result = $soapclient->insertReservation($this->username, $this->password, Util::encodeUtf8($postData));
        //exceptions abfangen
        if (is_soap_fault($result)) {
            $errorMsg = "FehlerCode: " . $result->faultcode . "\n";
            $errorMsg .= "Beschreibung: " . $result->faultstring . "\n";
            $errorMsg .= "Sender: " . $result->faultactor . "\n";
            $errorMsg .= "Fehler: " . $result->faultname . "\n";
            ErrorLogLoader::getInstance()->logError($errorMsg, __CLASS__." --> ".__METHOD__." Zeile ".__LINE__, true);
            return false;
        } else
        	return $result;
    }
    public function getReseravtionReasons()
    {
        $soapclient = new SoapClient($this->wsdl_file, array("trace" => 1, "exceptions" => 0));
        $result = $soapclient->getReseravtionReasons($this->username, $this->password);
        //exceptions abfangen
        if (is_soap_fault($result)) {
            $errorMsg = "FehlerCode: " . $result->faultcode . "\n";
            $errorMsg .= "Beschreibung: " . $result->faultstring . "\n";
            $errorMsg .= "Sender: " . $result->faultactor . "\n";
            $errorMsg .= "Fehler: " . $result->faultname . "\n";
            ErrorLogLoader::getInstance()->logError($errorMsg, __CLASS__." --> ".__METHOD__." Zeile ".__LINE__, true);
            return false;
        } else
        	return $this->fillObjectDataList('ReservationReasonsModell', $result);
    }
    public function getReservationPlaceArea()
    {
        $soapclient = new SoapClient($this->wsdl_file, array("trace" => 1, "exceptions" => 0));
        $result = $soapclient->getReservationPlaceArea($this->username, $this->password);
        //exceptions abfangen
        if (is_soap_fault($result)) {
            $errorMsg = "FehlerCode: " . $result->faultcode . "\n";
            $errorMsg .= "Beschreibung: " . $result->faultstring . "\n";
            $errorMsg .= "Sender: " . $result->faultactor . "\n";
            $errorMsg .= "Fehler: " . $result->faultname . "\n";
            ErrorLogLoader::getInstance()->logError($errorMsg, __CLASS__." --> ".__METHOD__." Zeile ".__LINE__, true);
            return false;
        } else
        	return $this->fillObjectDataList('ReservationPlaceAreaModell', $result);
    }
    public function checkReservationDate($_reservationDate, $_companyId)
    {
        $expiredTime = (int)$this->configInstance->getConstant('expiredTime');
        //check dateformat
        $errorMessage = null;
        if (Util::convertToDBDate($_reservationDate) == date('Y-m-d', time()) && date('H', time()) >= $expiredTime){
            $msg = (string)$this->messageInstance->getErrorMsg('expiredTime', 'reservation');
            $errorMessage = str_replace('##expiredTime##',$expiredTime,$msg);
        }            
        else {
            $soapclient = new SoapClient($this->wsdl_file, array("trace" => 1, "exceptions" =>
                0));
            $result = $soapclient->blockedDates($this->username, $this->password, $_reservationDate);
            //exceptions abfangen
            if (is_soap_fault($result)) {
                $errorMsg = "FehlerCode: " . $result->faultcode . "\n";
                $errorMsg .= "Beschreibung: " . $result->faultstring . "\n";
                $errorMsg .= "Sender: " . $result->faultactor . "\n";
                $errorMsg .= "Fehler: " . $result->faultname . "\n";
                ErrorLogLoader::getInstance()->logError($errorMsg, __CLASS__." --> ".__METHOD__." Zeile ".__LINE__, true);
                return false;
            } elseif (!empty($result))
                $errorMessage = $result;
        }
        return $errorMessage;
    }
    public function checkReservationPersonNumber($_numberOfPerson, $_areaId, $_reservationDate)
    {
        $errorMessage = null;        
        if(!empty($_reservationDate)) {
            $soapclient = new SoapClient($this->wsdl_file, array("trace" => 1, "exceptions" => 0));
            $result = $soapclient->numberOfPerson($this->username, $this->password, $_reservationDate);
            //exceptions abfangen
            if (is_soap_fault($result)) {
                $errorMsg = "FehlerCode: " . $result->faultcode . "\n";
                $errorMsg .= "Beschreibung: " . $result->faultstring . "\n";
                $errorMsg .= "Sender: " . $result->faultactor . "\n";
                $errorMsg .= "Fehler: " . $result->faultname . "\n";
                ErrorLogLoader::getInstance()->logError($errorMsg, __CLASS__." --> ".__METHOD__." Zeile ".__LINE__, true);
                return false;
            } elseif (is_array($result) && !empty($result)) {
                $result = $this->checkeReservationPlace($result,$_areaId, $_numberOfPerson);
                if (!empty($result))
                    $errorMessage = $result;
            }
        }
        return $errorMessage;
    }
    public function checkeReservationPlace($_result,$_areaId, $_numberOfPerson)
    {
        $msg = null;
        $ok = true;
		foreach($_result as $reservationPlace){			
        	if($reservationPlace['id'] == $_areaId){
        		$available = $reservationPlace['maxReservationNumber'] - $reservationPlace['currentReservationNumber'];
        		if($available < $_numberOfPerson){
        			$ok = false;
        			if($available == 1)
        				$msg = "Wir haben für diesen Tag nur noch " . $available ." freien ".$reservationPlace['description']."-Platz zur Auswahl.<br />";
       				elseif($available > 1)
        				$msg = "Wir haben für diesen Tag nur noch " . $available ." freie ".$reservationPlace['description']."-Plätze zur Auswahl.<br />";
        			else
						$msg = $this->messageInstance->getErrorMsg('full_area', 'reservation')."<br />";
        			break;
       			}
        	}
        }
        //in case of not enough empty palces
        if(!$ok){
	        $msg_place = "Sie können aber in folgenden Bereichen noch einen Platz reservieren:";
			$msg_place .="<ol style='margin-left:6em'>";				
			foreach($_result as $reservationPlace){
        		$available = $reservationPlace['maxReservationNumber'] - $reservationPlace['currentReservationNumber'];
                if($available >= $_numberOfPerson && $_areaId != $reservationPlace['id']){
        			$ok =true;
					$msg_place .= "<li>".$reservationPlace['description'].": ".$available." Plätze</li>";
        		}
	        }
	        if($ok)
        		$msg_place .="</ol>";
        }
        if($ok)
        	$msg .= $msg_place;
        return $msg;
    }
    public function checkReservation($_companyId, $_post) {
		$_errorMessage = array();
		$validate = new Validate();
		foreach($_post as $key => $value){;
			switch ($key) {
				case 'reservationdate':
					$error = $this->checkReservationDate($value,$_companyId,$_currentReservationDetails);
					if(!empty($error))
						array_push($_errorMessage ,trim($error));
					break;
					
				case 'reservationHour':
					if(!empty($value) && ($value > 23 || $value < 1)){
						array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('invalid_hour','reservation')));
					}
					break;
					
				case 'reservationMinute':
					if(!empty($value) && ($value > 45 || $value < 0)){
						array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('invalid_minute','reservation')));
					}
					break;
				
				case 'eat':
					if($value != 1 && $value != 0){
						array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('invalid_eat','reservation')));
					}
					break;
					
				case 'sex':
					if($value != "Herr" && $value != "Frau"){
						array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('invalid_sex','reservation')));
					}
					break;
									
				case 'numberofperson':
                    if(!is_numeric($value) || $value < 1 || $value > 200)
                    	array_push($_errorMessage, trim($this->messageInstance->getErrorMsg('invalid_personnumber','reservation')));
					elseif(empty($_errorMessage)){
						$errorMesage = $this->checkReservationPersonNumber($value,$_post['reservationArea'],$_post['reservationdate']);
	                     if(!empty($errorMesage))
	                    	array_push($_errorMessage, trim($errorMesage));
     				}
                    break;
					
				case 'menu_id':
					if($value == -1)
						array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('invalid_menu','reservation')));
					break;
				
				case 'reservationArea':
					$result = $this->getReservationPlaceArea();
					$match = false;
					foreach($result as $area){
						if($area->getId() == $value){
							$match = true;
							break;
						}
					}
					if(!$match){
						$_POST['reservationArea'] = 1;
						array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('invalid_reservationarea','reservation')));
					}
					break;
				
				case 'reasonId':
					if($value == -1)
						array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('invalid_reason','reservation')));
					break;
					
				case 'firstname':
					if(empty($value) && !$_insert)
						array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('empty_firstname','form')));
					elseif(strlen($value) > 30 && !$_insert)
						array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('invalid_firstname','form')));
					break;
						
				case 'lastname':
					if(empty($value))
						array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('empty_lastname','form')));
					elseif(strlen($value) > 25)
						array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('invalid_lastname','form')));
					break;
					
				case 'birthday':					
					if(is_array($value)){
						$day 	= $value['Date_Day'];
						$month 	= $value['Date_Month'];
						$year 	= $value['Date_Year'];
						
						if((!is_numeric($day) || $day > 31 || $day < 1))
							array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('invalid_birthday_day','form')));
						elseif(!is_numeric($month) || $month > 12 || $month < 1)
							array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('invalid_birthday_month','form')));
						elseif(!is_numeric($year) || $year > date('Y', time()) || $year < 1900)
							array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('invalid_birthday_year','form')));
					}else{						
						$regex = '|^\d{4}\-\d{2}\-(\d{2})$|';
						preg_match($regex,$value, $regs);
						if(empty($regs))
							array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('invalid_birthday_day','form')));
					}        
					break;
					
				case 'telefon':
					if(!empty($value) && !ValidateHelper::validatePhonenumber($value))
						array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('invalid_telefon','form')));
					break;
				
				case 'handy':
					if(!ValidateHelper::validatePhonenumber($value))
						array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('invalid_handy','form')));
					break;
					
				case 'email':
					if(empty($value))
						array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('empty_email','form')));
					elseif(false === $this->validate->email($value,true))
						array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('invalid_email','form')));
					break;
				
				case 'sendSMS':
					if(empty($_post['handy']) || !ValidateHelper::validatePhonenumber($_post['handy']))
						array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('invalid_sendSms','form')));
					break;
					
				case 'captchastring':
					include_once './extensions/_securimage/securimage.php';
					$securimage = new Securimage();
					if (empty ($value)) {
						array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('empty_captcha')));
					}
					elseif ($securimage->check($value) == false) {
						array_push($_errorMessage ,trim($this->messageInstance->getErrorMsg('wrong_captcha')));
					}
				break;
			}
		}
		return $_errorMessage;
	}
}
?>