<?php
class AuthController extends Zend_Controller_Action
{
    protected $theme;

    protected $partnerConfig = array(
        'inextenso' => array(
            'logo' => 'logo-in-extenso.gif',
            'clientId' => 195,
            'serviceCode' => 'SSO',
            'authType' => 'userSSO',
            'login' => 'mail',
            'token' => 'token',
        )
    );

    public function init()
    {
        // --- Theme
        $this->theme = Zend_Registry::get('theme');
    }

    /**
     * Point d'entrée pour les connexions partenaires.
     * L'utilisateur s'identifie sur son portail habituel.
     */
    public function indexAction()
    {
        // --- Désactiver le layout
        $this->_helper->layout()->disableLayout();

        $this->view->headLink()
            ->appendStylesheet($this->theme->pathStyle.'/inexweb.css', 'all')
            ->appendStylesheet($this->theme->pathStyle.'/user.css', 'all');

        $request = $this->getRequest();

        /**
         * Get partner name - see route in bootstrap
         */
        $partner = $request->getParam('partner');
        if ( array_key_exists($partner, $this->partnerConfig) ) {
            $config = $this->partnerConfig[$partner];
            $this->view->logo = $config['logo'];
            $params = $request->getParams();
            $objectParams = array();
            foreach ($params as $label => $value) {
				if (in_array($label, array('controller', 'action'))) continue;
				$object = new stdClass();
				$object->label = $label;
				$object->value = $value;
				$objectParams[] = $object;
            }
            $this->view->Params = $objectParams;

            $login = $params[$config['login']];
            $part = strstr($login, '@', true);
            if ($part !== false) {
                $login = $part;
            }
            $token = $params[$config['token']];

            try {
                $ws = new Scores_Ws_Client('gestion', '0.4');
                $parameters = new stdClass();
                $parameters->client = $config['clientId'];
                $parameters->login = $login;
                $parameters->token = $token;
                $parameters->params = $objectParams;
                $hash = $ws->ssoAuthenticate($parameters);
                // --- Utilisateur inexistant
                if ( $hash === 'false' || $hash === false ) {
                    $this->view->NoUser = true;
                    $urlParams = array('controller'=>'auth', 'action'=>'userssoform');
                    $urlParams = array_merge($params, $urlParams);
                    $this->view->FormUrlParams = $urlParams;
                }
                // --- Redirection
                else {

                	$auth = Zend_Auth::getInstance();

                    // --- Set partial identity
                    $identity = new stdClass();
                    $identity->username = $login;
                    $identity->password = $hash;
                    $auth->getStorage()->write($identity);
                    // --- End Set partial identity

                    // --- Get InfosLogin
                    $adressIp = $_SERVER['REMOTE_ADDR'];
                    $parameters = new stdClass();
                    $parameters->login = $login;
                    $parameters->ipUtilisateur = $adressIp;
                    $parameters->from = 'auth';
                    try {
                        $ws = new Scores_Ws_Client('gestion', '0.3');
                        $InfosLogin = $ws->getInfosLogin($parameters);
                        Zend_Registry::get('firebug')->info($InfosLogin);
                        if ( is_string($InfosLogin) || $InfosLogin->error->errnum != 0 ) {
                            $this->view->Error = true;
                        } else {
                            $user = new Scores_Utilisateur();
                            $identity = $user->updateProfil($InfosLogin);
                            $auth->getStorage()->write($identity);
                            // --- Redirect
                            $this->redirect('/');
                        }
                    } catch ( Exception $e ) {
                        switch ( $e->getCode() ) {
                            case 'MSG':
                                $this->view->Message = $e->getMessage();
                                break;
                            default:
                                $this->view->Error = true;
                                break;
                        }
                    }
                    // --- End Get InfosLogin
                }
            } catch ( Exception $e ) {
                switch ( $e->getCode() ) {
                    case 'MSG':
                        $this->view->Message = $e->getMessage();
                        break;
                    default:
                        $this->view->Error = true;
                        break;
                }
            }
        } else {
            $this->view->Message = "Erreur dans les paramètres.";
        }
    }

    /**
     * Affichage du formulaire pour l'inscription des utilisateurs
     */
    public function userssoformAction()
    {
        // --- Désactiver le layout
        $this->_helper->layout()->disableLayout();
        $this->view->headLink()->appendStylesheet($this->theme->pathStyle.'/user.css', 'all');
        $request = $this->getRequest();

        /**
         * Get partner name - see route in bootstrap
         */
        $partner = $request->getParam('partner');
        if ( array_key_exists($partner, $this->partnerConfig) ) {
            $config = $this->partnerConfig[$partner];
            $this->view->logo = $config['logo'];
            $params = $request->getParams();
            $objectParams = array();
            foreach ($params as $label => $value) {
                if (in_array($label, array('controller', 'action'))) continue;
                $object = new stdClass();
                $object->label = $label;
                $object->value = $value;
                $objectParams[] = $object;
            }
            $this->view->Params = $objectParams;

            $login = $params[$config['login']];
            $part = strstr($login, '@', true);
            if ($part !== false) {
                $login = $part;
            }
            $token = $params[$config['token']];

            $this->view->NoUser = true;
            // --- Set form value
            $this->view->FormPartner = $partner;
            $this->view->FormIdentifiant = $login;
            $this->view->FormCourriel = $request->getParam('mail');
            $this->view->FormSiret = $request->getParam('siret');
            $this->view->FormNom = $request->getParam('lastname');
            $this->view->FormPrenom = $request->getParam('name');
        }
        else {
            $this->view->Message = "Erreur dans les paramètres.";
        }
    }

    /**
     * Creation d'un utilisateur en SSO
     */
    public function userssocreateAction()
    {
        $this->_helper->layout()->disableLayout();

        $request = $this->getRequest();

        $partner = $request->getParam('partner');
        if ( array_key_exists($partner, $this->partnerConfig) ) {
            $config = $this->partnerConfig[$partner];
            $this->view->logo = $config['logo'];
            $data = array(
                'idClient' => $config['clientId'],
                'login' => $request->getParam('login'),
                'email' => $request->getParam('email', ''),
                'actif' => 1,
                'nom' => $request->getParam('nom', ''),
                'prenom' => $request->getParam('prenom', ''),
                'siret' => str_replace(' ', '', $request->getParam('siret', '')),
                'tel' => str_replace(array(' ','.'), array('',''), $request->getParam('tel', '')),
                'Service' => $config['serviceCode'],
            );

            try {
                $ws = new Scores_Ws_Client('gestion', '0.4');
                $parameters = new stdClass();
                $parameters->data = json_encode($data);
                $created = $ws->setUserSSO($parameters);
                if ($created === false ) {
                    $this->view->Message = "Erreur lors de la création de votre compte.";
                } else {
                    $this->view->UserCreated = true;
                    // --- Data to go back
                    $params = $request->getParams();
                    $urlArgs = array();
                    foreach ($params as $label => $value) {
						if (in_array($label, array('controller', 'action'))) continue;
						if (substr($label, 0, 2) == 'P-') {
							$urlArgs[substr($label, 2)] = $value;
						}
                    }
                    $urlArgs['partner'] = 'inextenso';
                    $this->view->UrlArgs = $urlArgs;
                }
            } catch ( Exception $e ) {
                switch ( $e->getCode() ) {
                    case 'MSG':
                        $this->view->Message = $e->getMessage();
                        break;
                    default:
                        $this->view->Error = true;
                        break;
                }
            }

        } else {
            $this->view->Message = "Erreur dans les paramètres.";
        }
    }

    /**
     * Lien de validation depuis email
     * Paramètres
     * - login ou email
     * - key
     * L'action renvoi sur un affichage spécifique suivant le type de client
     */
    public function validateAction()
    {
        $request = $this->getRequest();

        //Validation en erreur

        //Validation invalide

        //Validation Ok => Comment afficher les particularités

    }

}