<?php
class UserController extends Zend_Controller_Action
{

	public function init()
	{
		require_once 'Scores/WsScores.php';
		$this->view->headLink()->appendStylesheet('/themes/default/styles/user.css', 'all');
	}

	/**
	 * Affiche le fomulaire d'edition des paramètres utilisateur
	 */
	public function indexAction()
	{
		$user = new Scores_Utilisateur();

		if (!$user->checkPerm('MONPROFIL')){
			$this->_forward('perms', 'error');
		}

		$this->view->assign('device_type', $user->getBrowserInfo()->mobile);
		$this->view->assign('browser_info', $user->getBrowserInfo()->name.' '.$user->getBrowserInfo()->version);

		$this->view->headLink()->appendStylesheet('/themes/default/styles/form.css', 'all');
		$this->view->headScript()->appendFile('/themes/default/scripts/user.js', 'text/javascript');

		$request = $this->getRequest();

		$messages = '';
		$isProfilUpdated = false;
		$isPasswordUpdated = false;
		$updateResult = false;

		$ws = new WsScores();

		$login = $request->getParam('login', '');
		$op = $request->getParam('op');

		//Récupération des informations de l'identité
		$auth = Zend_Auth::getInstance();
		$identity = $auth->getIdentity();

		//Save data
		if ( $request->isPost() ) {
			$options = $request->getParam('frmOptions', '');
			$action = $options['action'];

			if ($login=='') $login = $options['login'];

			//Enregistrement des données new & update
	 		if (in_array($action, array('new','update'))) {

				if ($options['changepwd']!=1) {
					$options['password'] = '';
				}

				if ( in_array($options['profil'], array('Administrateur', 'SuperAdministrateur'))
				        && !in_array('monprofil', $options['droits']) ) {
					$options['droits'][] = 'monprofil';
				}

	 			if( !isset($options['profil']) ) {
	 				$options['profil'] = 'Utilisateur';
	 			}

	 			$reponse = $ws->setInfosLogin($login, $action, $options);

	 			$isProfilUpdated = true;
	 			$message = 'Erreur lors de la mise à jour du compte !';
	 			if (is_string($reponse)) {
	 			    $message = $reponse;
	 			} elseif ($reponse){
	 				$updateResult = true;
	 				$message = 'Compte mis à jour.';
	 			}
	 		}

	 		//Write change in session
	 		if ($identity->idClient == $options['idClient'] && $identity->username == $login) {
	 		    //Modification lors du changement de mot de passe
	 		    if ($options['changepwd']==1 && $updateResult) {

	 		        $identity->password = md5($login.'|'.$options['password']);
	 		        $auth->getStorage()->write($identity);

	 		    }
	 		    //Mise à jour du profil
	 		    if ($isProfilUpdated && $updateResult) {

	 		    	$InfosLogin = $ws->getInfosLogin($identity->username, $_SERVER['REMOTE_ADDR']);
	 		        $identity = $user->updateProfil($InfosLogin);
	 		        $auth->getStorage()->write($identity);

	 		    }
	 		    //Gestion mode edition en SESSION
	 		    if ($action=='update') {
	 		        $modeEdition = $request->getParam('modeEdition', false);
	 		        if ( $modeEdition ) {

	 		            $identity->modeEdition = true;
	 		            $auth->getStorage()->write($identity);

	 		        }
	 		    }
	 		}
 		}

		if ( $isProfilUpdated || $isPasswordUpdated ) {
			$this->view->assign('message', $message);
		}

		$isAdmin = false;
		if ( $identity->profil == 'Administrateur'
			|| $identity->profil == 'SuperAdministrateur' ) {
			$isAdmin = true;
		}
		$this->view->assign('isAdmin', $isAdmin);

		$isSuperAdmin = false;
		if ($identity->profil == 'SuperAdministrateur') {
			$isSuperAdmin = true;
		}
		$this->view->assign('isSuperAdmin', $isSuperAdmin);

		if ($op=='new')
		{
			$idClient = $request->getParam('idClient', '');
			if ($idClient == '') {
				$idClient = $identity->idClient;
			}
			$reponse = $ws->getNextLogin($idClient);
			$options->idClient = $idClient;
			if ($identity->idClient!=1 && $identity->profil!='SuperAdministrateur') {
				$options->profil = 'Utilisateur';
			}
			$this->view->assign('options', $options);

			$this->view->assign('loginNew', $reponse->result->racine);
			$this->view->assign('droitsClients', explode(' ', strtolower($reponse->result->droitsClients)));
			$this->view->assign('action', 'new');
			$this->view->assign('pref', array());
		}
		elseif (!empty($op) || $op!='new')
		{
			if ( !empty($login) && $identity->username != $login ) {
				Zend_Registry::get('firebug')->info('getInfosLogin');
				$reponse = $ws->getInfosLogin($login, $_SERVER['REMOTE_ADDR']);
				$this->view->assign('options', $reponse->result);
				$this->view->assign('loginVu', $reponse->result->login);
				$this->view->assign('droits', explode(' ', strtolower($reponse->result->droits)));
				$this->view->assign('droitsClients', explode(' ', strtolower($reponse->result->droitsClients)));
			} else {
				$this->view->assign('options', $identity);
				$this->view->assign('loginVu', $identity->username);
				$this->view->assign('droits', explode(' ', strtolower($identity->droits)));
				$this->view->assign('droitsClients', explode(' ', strtolower($identity->droitsClients)));
			}
			$this->view->assign('loginNew', '');
			$this->view->assign('action', 'update');
			$this->view->assign('pref', explode(' ',$identity->pref));
		}

		//Liste des catégories des accès
		$reponse = $ws->getCategory();
		$wscategory = $reponse->item;
		$this->view->assign('wscategory', $wscategory);

		//Liste de tous les droits
		$listeDroits = $ws->getListeDroits();
		$droitsLib = array();
		foreach($listeDroits->item as $droit) {
		    $droitsLib[strtoupper($droit->code)] = $droit->desc;
		}
		$this->view->assign('droitsLib', $droitsLib);

		//Liste de toutes les préférences
		$listePrefs = $ws->getListePrefs();
		$prefsLib = array();
		foreach($listePrefs->item as $pref) {
		    $prefsLib[strtoupper($pref->code)] = $pref->desc;
		}
		$this->view->assign('prefsLib', $prefsLib);
	}

	/**
	 * Display box to enter emails
	 * One main email and two secondary
	 * Email length 80 * 3 = 240
	 * 255 chars is the length to store emails (email1;email2;email3)
	 */
	public function emailsAction()
	{
	    $this->_helper->layout()->disableLayout();

	    $nbEmails = 3;

	    $request = $this->getRequest();
	    $emails = $request->getParam('q');

	    if (null !== $emails) {
	        $emailList = explode(';', $emails);
	        if ( count($emailList)>0 ) {
	            $i = 1;
	            foreach ( $emailList as $email ) {
	                $this->view->assign('email'.$i, $email);
	                $i++;
	            }
	        }
	    }
	}

	/**
	 * Validate email
	 */
	public function emailvalidAction()
	{
	    $this->_helper->layout()->disableLayout();

	    $request = $this->getRequest();
	    $email = $request->getParam('q');

	    $valid = false;

	    if (null !== $email) {
	        $validateur = new Zend_Validate_EmailAddress();
	        $valid = $validateur->isValid($email);
	    }

	    $result = array(
	        'valid' => $valid,
	    );

	    $this->view->assign('result', $result);
	}

	/**
	 * Téléchargement de la consommation au format CSV
	 */
	public function consoAction()
	{
		$this->view->headScript()->appendFile('/themes/default/scripts/conso.js', 'text/javascript');

		$user = new Scores_Utilisateur();

		$request = $this->getRequest();
		$idClient = $request->getParam('idClient', $user->getIdClient());
		$login = $request->getParam('login', '');

		$this->view->assign('idClient', $idClient);
		$this->view->assign('login', $login);
		$this->view->assign('profil', $user->getProfil());
	}

	/**
	 * Renvoi vers le formulaire utilisateur avec les paramètres de la requete
	 */
	public function editAction()
	{
		$params = $this->getRequest()->getParams();
		$this->_forward('index', 'user', null, $params);
	}

	/**
	 * Suppression d'un utilisateur
	 */
	public function deleteAction()
	{
		$request = $this->getRequest();
		$login = $request->getParam('login');
		$action = 'delete';
		$ws = new WsScores();
		$ws->setInfosLogin($login, $action);
		//Redirect
		$this->_forward('liste');
	}

	/**
	 * Activation d'un utilisateur
	 */
	public function enableAction()
	{
		$request = $this->getRequest();
		$login = $request->getParam('login');
		$action = 'enable';
		$ws = new WsScores();
		$ws->setInfosLogin($login, $action);
		//Redirect
		$this->_forward('liste');
	}

	/**
	 * Désactivation d'un utilisateur
	 */
	public function disableAction()
	{
		$request = $this->getRequest();
		$login = $request->getParam('login');
		$action = 'disable';
		$ws = new WsScores();
		$ws->setInfosLogin($login, $action);
		//Redirect
		$this->_forward('liste');
	}

	/**
	 * Méthode AJAX pour modifier le password d'un utilisateur
	 */
    public function changepwdAction()
    {
    	//Redirect
    }

	/**
	 * Affiche la liste des utiliateurs
	 */
    public function listeAction()
	{
		$user = new Scores_Utilisateur();

		$request = $this->getRequest();
		$idClient = $request->getParam('idClient', $user->getIdClient());

		if (!$user->isSuperAdmin() && !$user->isAdmin()) {
			$this->renderScript('error/perms.phtml');
		}
		if ($user->isAdmin()){
			$idClient = $user->getIdClient();
		}
		$ws = new WsScores();
		$infos = $ws->getListeUtilisateurs($user->getLogin(), $idClient);
		$utilisateurs = $infos->result->item;
		$this->view->assign('utilisateurs', $utilisateurs);
		$this->view->assign('idClient', $idClient);
	}

	/**
	 * Gestion de l'authentification
	 */
    public function loginAction()
    {
    	$this->view->headScript()
    		->appendFile('/libs/jquery/jquery.infieldlabel.min.js');

    	//@todo : gestion des affichages particuliers pour les clients
    	$this->view->headTitle()->append('Connexion');
    	$form = new Application_Form_Login();
    	$this->view->form = $form;
    	$request = $this->getRequest();
    	if ( $request->isPost() ) {
    		$formData = $request->getPost();
    		if ($form->isValid($formData)) {
    			$login = $form->getValue('login');
    			$pass = $form->getValue('pass');

    			$auth = Zend_Auth::getInstance();
				$authAdapter = new Scores_AuthAdapter($login, md5($login.'|'.$pass));
    			$result = $auth->authenticate($authAdapter);

    			//Auth is valid
    			if ( $result->isValid() ) {

    			    //Save browser information
    			    $screenSize = $request->getParam('screenSize', 'unknow');
    			    $user = new Scores_Utilisateur();
    			    $info = get_browser();
    			    $isMobile = ($info->ismobiledevice==1) ? 1 : 0;
    			    $user->setBrowserInfo($info->platform, $info->browser, $info->version, $isMobile, $screenSize);

    			    //Get previous url if user has been disconnected
    			    $url = '';
    			    if (Zend_Session::namespaceIsset('login')){
    			        $session = new Zend_Session_Namespace('login');
    			        if (isset($session->url)) {
    			            $url = $session->url;
    			        }
    			    }
    			    if (!empty($url) && $url!='/user/login' && $url!='/user/logout' && $url!='/localauth'){
    			        $this->_redirect($url);
    			    }
    			    $this->_redirect('/');
    			}
    			//Auth error
    			else {

    			    $this->view->message = '';
    			    Zend_Registry::get('firebug')->info($result);
    			    foreach ($result->getMessages() as $message) {
    			        $this->view->message.= $message."<br/>";
    			    }
      			}
    		}
    	}
    	$this->_helper->layout()->disableLayout();
    }

   	/**
   	 * Gestion de la déconnexion
   	 */
    public function logoutAction()
    {
    	Zend_Auth::getInstance()->clearIdentity();
    	$session = new Zend_Session_Namespace('wcheck');
    	$session->unsetAll();
    	$this->_helper->layout()->disableLayout();

    	$request = $this->getRequest();
    	$message = $request->getParam('message');
    	$this->view->assign('message', $message);

    	$ajax = $request->getParam('ajax', 0);
    	$this->view->assign('ajax', $ajax);

    	$refresh = 5;

		$url = 'http://'.$_SERVER['SERVER_NAME'].$this->view->url(array(
			'controller' => 'user',
			'action' => 'login',
		), null, true);

    	$this->view->assign('url', $url);

    	if (!$ajax) {
    	    $this->view->assign('refresh', $refresh);
    	    $this->view->headMeta()->appendHttpEquiv('refresh', $refresh.'; url='.$url);
    	}
    }

    /**
     * Mettre à jour le mode edition en session sans refresh de la page
     */
    public function editionsessionAction()
    {
    	$this->_helper->layout()->disableLayout();
    	$this->_helper->viewRenderer->setNoRender(true);
    	$request = $this->getRequest();
		$mode = $request->getParam('mode', 'false');
		$auth = Zend_Auth::getInstance();
    	$identity = $auth->getIdentity();
    	if ($identity->idClient == 1) {
	    	if ($mode == 'false') {
	    		$identity->modeEdition = false;
	    		echo 0;
	    	} else {
	    		$identity->modeEdition = true;
	    		echo 1;
	    	}
	    	$auth->getStorage()->write($identity);
    	} else {
    		echo 0;
    	}
    }

    /**
     * Override email in surveillance portfolio
     */
    public function emailsurveillanceAction()
    {
        $this->_helper->layout()->disableLayout();
        $request = $this->getRequest();

        $user = new Scores_Utilisateur();

        //Execute webservice operation
        if ( $request->isPost() ) {
            $email = trim($request->getParam('email'));
            if ($user->isAdmin() || $user->isSuperAdmin()) {
                $login = $request->getParam('login');
            }

            if (empty($email)) {
                $result = "Aucun email défini!";
            } else if (empty($login)) {
                $result = "Aucun utilisateur défini!";
            } else {
                $ws = new WsScores();
                $result = $ws->setSurveillancesMail($login, $email);
            }

            $this->view->assign('result', $result);
        }
        //Display form in dialog
        else {
            if ($user->isAdmin() || $user->isSuperAdmin()) {
                $login = $request->getParam('login');
            } else {
                $login = $user->getLogin();
            }
            $this->view->assign('login', $login);
            $this->view->assign('dialog',true);
        }
    }

	/**
	 * Changer la langue de l'utilisateur
	 */
    public function langAction()
    {
    	$this->_helper->layout()->disableLayout();
    	$this->_helper->viewRenderer->setNoRender(true);

    	$lang = $this->getRequest()->getParam('lang', null);

    	$auth = Zend_Auth::getInstance();
    	$identity = $auth->getIdentity();

    	$identity->langtmp = $lang;

    	$auth->getStorage()->write($identity);
    }

    /**
     * Changer le theme de l'utilisateur
     */
    public function changethemeAction()
    {
    	$this->_helper->layout()->disableLayout();
    	$this->_helper->viewRenderer->setNoRender(true);

    	$request = $this->getRequest();
    	$nom = $request->getParam('nom', 'default');

    	$auth = Zend_Auth::getInstance();
    	$identity = $auth->getIdentity();

    	$identity->theme = $nom;

    	$auth->getStorage()->write($identity);

    	//Rediriger vers l'écran de recherche
    	$this->_redirect('/');

    }

    /**
     * Display browser informations on a simple page
     */
    public function browserAction()
    {
        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        //Load bootstrap
        $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');

        //Get useragent and device informations
        $userAgent = $bootstrap->getResource('useragent');
        $device = $userAgent->getDevice();

        //Display
        echo "<pre>";
        print_r(get_browser());
        print_r($device->getAllFeatures());
        echo "</pre>";
    }

    /**
     * Sends email to the specific client, who requests for forgotten password
     */
    public function motpasseAction()
    {
    	$request = $this->getRequest();
    	$name = 'Identifiants oubliés ?';
    	$params = array(
    			'identifiant' => '',
    			'telephone' => '',
    			'email' => '',
    			'nom' => '',
    			'prenom' => '',
    			'fonction' => '',
    			'service' => '',
    			'rsociale' => '',
    			);

		$this->_helper->layout()->disableLayout();
		if ( $request->isPost() ) {
			$params = $request->getParams();
			$message = '';

			$paramlist = array(
					'telephone' => 'Numéro de téléphone direct',
					'email' => 'Adresse email',
					'nom' => 'Nom',
					'prenom' => 'Prénom',
					'fonction' => 'Fonction',
					'service' => 'Service',
					'rsociale' => 'Sociale',
			);

			foreach ($paramlist as $item => $val) {
				if (!isset($params[$item])) {
					$message .= "Champs $val vide !<br/>";
				}
			}

			$validator = new Zend_Validate_EmailAddress();
			if (isset($params['email'])){
    			if (!$validator->isValid($params['email'])) {
    				$message .="Adresse email invalide ! <br/>";
    				}
			}

			if ($message == '') {

				$mailbody = '<style type="text/css">table {font-family:Arial, Helvetica, sans-serif; font-size: 12px; width: 550px;	border: none;}table td{padding: 4px 8px;}</style>';
				$mailbody .= "Demande d'envoi des identifiants.<br /><br />";
				$mailbody .= "L'un de nos clients a égaré son(ses) identifiant(s).<br />";
				$mailbody .= "Via notre lien -identifiants oubliés- il a effectué une demande de transmission de ces codes.<br />";
				$mailbody .= "<p>A l'aide des informations ci-dessous, merci de retrouver ces codes et les lui envoyer par email.</p>";
				$mailbody .= "<table><tr bgcolor='#eeeeee'><td width='200px'><strong>Identifiant :</strong></td><td>".$params['identifiant']."</td></tr>";
				$mailbody .= "<tr><td><strong>Adresse email:</strong></td><td>".$params['email']."</td></tr>";
				$mailbody .= "<tr bgcolor='#eeeeee'><td><strong>Numéro de téléphone direct:</strong></td><td>".$params['telephone']."</td></tr>";
				$mailbody .= "<tr><td><strong>Nom:</strong></td><td>".$params['nom']."</td></tr>";
				$mailbody .= "<tr bgcolor='#eeeeee'><td><strong>Prénom:</strong></td><td>".$params['prenom']."</td></tr>";
				$mailbody .= "<tr><td><strong>Fonction:</strong></td><td>".$params['fonction']."</td></tr>";
				$mailbody .= "<tr bgcolor='#eeeeee'><td><strong>Service:</strong></td><td>".$params['service']."</td></tr>";
				$mailbody .= "<tr><td><strong>Raison Sociale:</strong></td><td>".$params['rsociale']."</td></tr></table>";
				$mailbody .= "<p>Si les informations fournies ne permettent pas d'identifier correctement l'utilisateur, ";
				$mailbody .= "merci d'émettre un message sur le mail communiquer en précisant que \"Les éléments confiés ne permettent pas d'identifier l'utilisateur ";
				$mailbody .= "et par conséquence de vous délivrer les codes d'accès demandés\".<br />";
				$mailbody .= "Aussi nous vous invitons à vous rapprocher de votre interlocuteur commercial habituel ";
				$mailbody .= "ou de votre responsable suivi relations Scores & Décisions au sein de votre société.</p>";

				$mail = new Scores_Mail();
				$mail->setSubject("Demande d'envoi des identifiants");
				$mail->setBodyHTML($mailbody);
				$mail->setFrom('support');
				$mail->addToKey('support');
				$mail->setReplyTo($params['email']);
				try {
					$mail->send();
					$this->view->assign('sendEmail' , true);
				}
				catch ( Zend_Mail_Transport_Exception $e ){
					$message = $e->getMessage();
				}

			}
			$this->view->assign('message', $message);
		}
    	$this->view->assign('params', $params);
    }
}