<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of admin_bizLayer
 *
 * @author dghai
 */

require_once 'admin_dao.php';
require_once 'admin_config.php';

class admin_bizLayer
{
    private $admin_dao;
    private $config;
    
    function __construct()
    {
        $this->admin_dao = new admin_dao();
        $this->config = new admin_config();
    }
    
    function IsUserAuthorized($username, $password)
    {
        $retval = $this->admin_dao->IsUserAuthorized($username, $password);
        if($retval === true)
        {
            $_SESSION['username'] = $username;
        }
        return $retval;
    }
    
    function IsUsernameAvailable($username)
    {
        $retval = $this->admin_dao->IsUsernameAvailable($username);
        return $retval;
    }
    
    function AddAdmin($username, $password, $email)
    {
        if($this->admin_dao->AddAdmin($username, $password, $email, true, $_SESSION['username']))
        {
            $this->EmailNewUser($username, $email, $password);
            return true;
        }
        return false;
    }
    
    function IsSurveyNameAvailable($surveyName)
    {
        $retval = $this->admin_dao->IsSurveyNameAvailable($surveyName);
        return $retval;
    }
    
    function AddNewSurvey($surveyName, $isActive, array $questions)
    {
        //Add data to questions_set so as to register the survey
        //This will get us the survey id which will be used to establish
        //1:n relation with questions later on.
        $questionSetId = $this->admin_dao->AddQuestionSet($surveyName, $isActive, $_SESSION['username']);
        //This will store the ids of the questions that we get once they are
        //inserted in the table.
        $questionIds = array();
        if(!is_int($questionSetId))
            return $questionSetId;
            
        //UI will always send questions displayed on the page. We need to empty
        //values and send only valid data to Dao.
        
        $validQuestions = array();
        for($i=1; $i<=count($questions); $i++)
        {
            if(strlen($questions[$i]['text']) > 0 && 
                    (strlen($questions[$i]['x']) > 0) && 
                    (strlen($questions[$i]['y']) > 0) && 
                    (strlen($questions[$i]['z']) > 0)
                )
                $validQuestions []= $questions[$i];
        }
        $questionIds = $this->admin_dao->AddQuestions($validQuestions);
        
        if(!is_array($questionIds))
            return $questionIds; //return false in case we could not add the question_set.
        
        return $this->admin_dao->AddQuestionsInSet($questionSetId, $questionIds);
    }
    
    function SetSurveyAvailability($surveysToHide, $surveysToUnhide)
    {
        $surveysStatuses = array();
        
        for($i=0; $i<count($surveysToHide); $i++)
        {
            if(intval($surveysToHide[$i]) > 0)
                $surveysStatuses[$surveysToHide[$i]] = 0;
        }
        for($i=0; $i<count($surveysToUnhide); $i++)
        {
            if(intval($surveysToUnhide[$i]) > 0)
                $surveysStatuses[$surveysToUnhide[$i]] = 1;
        }
        
        //hit database only if there is something to update
        if(count($surveysStatuses) > 0)
        {
            return $this->admin_dao->SetSurveyAvailability($surveysStatuses, $_SESSION['username']);
        }
        
        return false;
    }
    
    function UpdateSurvey($surveyName, $surveyId, $isActive, array $editedQuestions, array $deletedQuestions, array $newQuestions)
    {
        $retVal = $this->admin_dao->UpdateQuestions($editedQuestions);
        if($retVal instanceof Admin_ErrorObject)
            return $retVal;
        
        if(count($deletedQuestions > 0))
        {
            $retVal = $this->admin_dao->DeleteQuestionsInSet($surveyId, $deletedQuestions);
            if($retVal instanceof Admin_ErrorObject)
                return $retVal;
        }
        
        return $this->admin_dao->UpdateQuestionSet($surveyName, $surveyId, $isActive, $_SESSION['username']);;
    }
    
    function GetQuestions($surveyId)
    {
        return $this->admin_dao->GetQuestions($surveyId);
    }
    
    function SearchSurvey($searchString, $isActive)
    {
        return $this->admin_dao->SearchSurvey($searchString, $isActive);
    }
    
    function CloseDatabaseConnection()
    {
        $this->admin_dao->CloseConnection();
    }
    
    private function EmailNewUser($username, $toEmailId, $newPassword)
    {
        $webmaster_email = $this->config->GetWebmasterEmail();
        $htmlEmail = strtr($this->config->GetNewAdminEmailTemplate() , array(
                            '{username}'        => $username,
                            '{password}'        => $newPassword,
                            '{webmaster_email}' => $webmaster_email,
                        )
                      );
        $plaintextEmail = strtr($this->config->GetNewAdminEmailPlaintextTemplate() , array(
                            '{username}'        => $username,
                            '{password}'        => $newPassword,
                            '{webmaster_email}' => $webmaster_email,
                        )
                      );
                
        require_once 'Base/src/ezc_bootstrap.php';
        // Create a new mail composer object
        $mail = new ezcMailComposer();
        // Specify the "from" mail address
        $mail->from = new ezcMailAddress( $this->config->GetWebmasterEmail(), $this->config->GetWebmasterName() );
        // Add one "to" mail address (multiple can be added)
        $mail->addTo( new ezcMailAddress( $toEmailId, $username ) );
        // Specify the subject of the mail
        $mail->subject = $this->config->GetNewAdminEmailSubject();
        // Specify the body text of the mail
        $mail->plainText = $plaintextEmail;
        $mail->htmlText = $htmlEmail;
        // Generate the mail
        $mail->build();
        // Create a new SMTP transport object with an SSLv3 connection.
        // The port will be 465 by default, use the 4th argument to change it.
        // Username and password (2nd and 3rd arguments) are left blank, which means
        // the mail host does not need authentication.
        // The 5th parameter is the $options object which specifies a SSLV3 connection
        // (default is ezcMailSmtpTransport::CONNECTION_PLAIN).
        $options = new ezcMailSmtpTransportOptions();
        $options->connectionType = ezcMailSmtpTransport::CONNECTION_SSLV3;
        $transport = new ezcMailSmtpTransport( $this->config->GetSMTPServer(),
                                               $this->config->GetSMTPUsername(), 
                                               $this->config->GetSMTPPassword(), 
                                               $this->config->GetSMTPPort(), 
                                               $options );
        // The option can also be specified via the option property:
        $transport->options->connectionType = ezcMailSmtpTransport::CONNECTION_SSLV3;
        // Use the SMTP transport to send the created mail object
        try
        {
            $transport->send( $mail );
            return true;
        }
        catch (ezcMailTransportException $e)
        {
            return false;
        }
    }
}

?>
