<?php

/* @type $Params string[] */

MMUserLogin::$isLogin = true;

$module  = $Params['Module'];
$tpl     = eZTemplate::factory();
$Result  = array();
$siteINI = ezINI::instance( 'site.ini' );
$state   = MMUserLogin::loginUser();

if ( $state )
{
    $destUrl = $siteINI->variable( 'SiteAccessSettings', 'JSPUrl' );

    if( isset($_GET['context']))
    {
        $context = trim($_GET['context']);

        if( preg_match( '#^(?:https?://|/)#', $context) )
        {
            $destUrl = urldecode($_GET['context']);
        }
    }

    header('Location: '.$destUrl );
    eZExecution::cleanExit();
}
else
{
    /**
     * Creates a profile
     *
     * @return array
     */
    public function create()
    {
        if( SolrSafeOperatorHelper::featureIsActive( 'RegistrationSettings' ) && SolrSafeOperatorHelper::feature( 'RegistrationSettings', 'DisableRegistration' ) == true ) {
            return array( 'data' => array( 'errorCode'=> 9 ) ); 
        }

        // 1st step - Checks fields
        $r = $this->checkUsername();
        if ( $r !== true )
        {
            return $r;
        }

        $r = $this->checkEmail();
        if ( $r !== true )
        {
            return $r;
        }
        $isHtmlEntitiesAlowed = self::isAddressEncodeAllowedOnCluster();

        // 2nd step - Process fields
        $addressLine1 = $this->getBusinessNameMapping( 'addressLine1' );
        if ( isset( $_POST[$addressLine1] ) && !empty( $_POST[$addressLine1] ) && $isHtmlEntitiesAlowed )
        {
            $_POST[$addressLine1] = htmlentities( $_POST[$addressLine1], ENT_QUOTES, 'UTF-8' );
        }

        $addressLine2 = $this->getBusinessNameMapping( 'addressLine2' );
        if ( isset( $_POST[$addressLine2] ) && !empty( $_POST[$addressLine2] ) && $isHtmlEntitiesAlowed  )
        {
            $_POST[$addressLine2] = htmlentities( $_POST[$addressLine2], ENT_QUOTES, 'UTF-8' );
        }

        /* @type $createParams array */
        $params       = array();
        $createParams = SolrSafeOperatorHelper::clusterIni('EsbSettings', 'CreateParamsTypes', 'merck.ini' );
        foreach ( $createParams as $key => $value )
        {
            if ( isset( $_POST[$key] ) )
            {
                $params[$key] = ( trim( $value ) == 'int' ) ? intval( $_POST[$key] ) : $_POST[$key];
            }            
        }

        $actId = $this->getBusinessNameMapping( 'actId' );
        if ( isset( $_REQUEST[$actId] ) )
        {
            $params[$actId] = $_REQUEST[$actId];
        }

        if ( $this instanceof ServiceUserUUMP )
        {
            $params['privacyPolicyDate'] = date('Ymdhis');
        }

        // managing validation status cases
        // 1. Override taken from cluster settings.
        $defaultValidationStatus = SolrSafeOperatorHelper::clusterIni('DefaultValidationStatus', 'DefaultValidationStatus', 'merck.ini' );
        $defaultValidationStatus = !empty( $defaultValidationStatus ) && isset( $defaultValidationStatus ) ? $defaultValidationStatus : 'PV' ;
        if( $this instanceof ServiceUserUUMP && !empty( $defaultValidationStatus ) && isset( $defaultValidationStatus ) )
        {
            $params['validationStatus'] = $defaultValidationStatus;
        }

        // 2. Russian helpdesk-register validates user by default.
        if( isset( $_POST['register-helpdesk']) && $_POST['register-helpdesk'] == 1 && !isset( $_POST['termsOfUse'] ))
        {
            $params['validationStatus'] = 'VP';

            $params['termsOfUse'] = isset( $_POST['helpdeskTermsOfUse']) ? 1 : 0;
            $params['privacyPolicy'] = isset( $_POST['helpdeskPrivacyPolicy']) ? 1 : 0;
        }

        // 3. German "kontakt" validation result.
        if ( $this instanceof ServiceUserUUMP && isset( $params['WEB_SERVICE_AJAX_FIELD_1'] ) )
        {
            if( $params['WEB_SERVICE_AJAX_FIELD_1'] == "kontakt" )
            {
                $params['validationStatus'] = 'PV';
            }
            unset( $params['WEB_SERVICE_AJAX_FIELD_1'] );            
        }

        // 4. German "DocCheck" validation result.
        if ( $this instanceof ServiceUserUUMP && ( isset( $params['DocCheck_username'] ) && $params['DocCheck_username'] != "" ) && ( isset( $params['Password_doccheck'] ) && $params['Password_doccheck'] != "" ) )
        {
            $params['validationStatus'] = 'VP';
            unset( $params['DocCheck_username'] );
            unset( $params['Password_doccheck'] );
        }

        // 5. US 1.8 if user is validated by eshcp we have crmMemberId field stored, so we also must validate user with VP
        if ( SolrSafeOperatorHelper::featureIsActive( "Univadis18Redesign" ) && isset($params['crmMemberId']) && $params['crmMemberId'] != "" )
        {
            $params['validationStatus'] = 'VP';
        }

        // 3rd step - ESB Create
        $sl = SystemLocale::fetchByClusterAndSystem( ClusterTool::clusterIdentifier(), 'esb_language' );
        if( !is_null( $sl ) )
        {
            $language = $sl;
        }
        else
        {
            $language = eZINI::instance( 'site.ini' )->variable( 'RegionalSettings', 'ContentObjectLocale' );
            $merckIni = eZINI::instance( 'merck.ini' );
            if ( $merckIni->hasVariable( 'EsbSettings', 'Language' ) )
            {
                $language = $merckIni->variable( 'EsbSettings', 'Language' );
            }
        }

        $apps = array();
        $appsIds = CountryAppsBar::fetchAppsBarApplicationIds( $_POST[$this->getBusinessNameMapping( 'customerType' )] );
        foreach ( $appsIds as $key => $value )
        {
            $apps[] = array(
                $this->getBusinessNameMapping( 'appId' )    => $value,
                $this->getBusinessNameMapping( 'appOrder' ) => $key + 1
            );
        }

        $subsUni = $this->getUnivadisSubscriptions();
        $subsMsd = $this->getMsdSubscriptions();
        $subsSun = $this->getSunshineAct();

        $consents = array_merge( $subsUni, $subsMsd );
        if(!empty($subsSun))
        {
            $consents = array_merge( $consents, $subsSun );
        }

        if( $createParams[self::SUBSCRIPTION_PHONE_CONSENT] )
        {
            $consents[] = array(
                'consentCode'       => self::SUBSCRIPTION_PHONE_CONSENT,
                'consentStatus'     => !empty( $_POST[self::SUBSCRIPTION_PHONE_CONSENT] ) ? self::SUBSCRIPTION_STATUS_SUBSCRIBED : self::SUBSCRIPTION_STATUS_UNSUBSCRIBED,
                'consentLastUpdate' => time(),
            );
            unset( $params[self::SUBSCRIPTION_PHONE_CONSENT] );
        }

        // Add terms of use, private policies and OptIn consents
        if ( SolrSafeOperatorHelper::featureIsActive( 'ToUPPPopin' ) && ( $this instanceof ServiceUserUUMP ) )
        {
            $touVersion = SolrSafeOperatorHelper::feature( 'ToUPPPopin', 'currentToUConsentVersion' );
            $ppVersion  = SolrSafeOperatorHelper::feature( 'ToUPPPopin', 'currentPPConsentVersion' );

            $consents[] = array(
                'consentCode'       => 'termsOfUse_v' . $touVersion,
                'consentStatus'     => 'S',
                'consentLastUpdate' => time(),
            );

            $consents[] = array(
                'consentCode'       => 'privacyPolicy_v' . $ppVersion,
                'consentStatus'     => 'S',
                'consentLastUpdate' => time()
            );

            $subsOptIn = $this->getOptInSubscriptions();
            if ( !empty( $subsOptIn ) )
            {
                $consents = array_merge( $consents, $subsOptIn );
            }
        }

        $username = $this->getUsername();

        $userSpecialty = $_POST[$this->getBusinessNameMapping( 'userSpecialty' )];
        $mainSpecialty = UserSpecialityContentSpeciality::getContentSpeciality( $userSpecialty );


        $unifiedParameters = array(
            $this->getBusinessNameMapping( 'emailAddress' )          => $_POST[$this->getBusinessNameMapping( 'emailAddress' )],
            $this->getBusinessNameMapping( 'password' )              => $_POST[$this->getBusinessNameMapping( 'password' )],
            $this->getBusinessNameMapping( 'firstName' )             => $_POST[$this->getBusinessNameMapping( 'firstName' )],
            $this->getBusinessNameMapping( 'lastName' )              => $_POST[$this->getBusinessNameMapping( 'lastName' )],
            $this->getBusinessNameMapping( 'language' )              => $language,
            $this->getBusinessNameMapping( 'userSpecialty' )         => $userSpecialty,
            $this->getBusinessNameMapping( 'customerType' )          => $_POST[$this->getBusinessNameMapping( 'customerType' )],
            $this->getBusinessNameMapping( 'apps' )                  => $apps,
            $this->getBusinessNameMapping( 'consents' )              => $consents,
            $this->getBusinessNameMapping( 'additionalSpecialties' ) => MMUserLogin::getAddSpecialties( $mainSpecialty ),
            $this->getBusinessNameMapping( 'countryOfRegistration' ) => $this->getCountryOfRegistration(),
            $this->getBusinessNameMapping( 'countryOfResidence' )    => $_POST[$this->getBusinessNameMapping( 'countryOfResidence' )],
        );

        if ( isset( $_POST[$this->getBusinessNameMapping( 'secondName' )] ) )
        {
            $unifiedParameters[$this->getBusinessNameMapping( 'secondName' )] = $_POST[$this->getBusinessNameMapping( 'secondName' )];
        }

        if ( !is_null($username))
            $unifiedParameters[$this->getBusinessNameMapping( 'userName' )] = $username;

        if ( $this instanceof ServiceUserUUMP )
        {

            $parameters = array(
                'data' => array(
                    'profile' => $unifiedParameters
                )
            );

            $formatDate                 = SolrSafeOperatorHelper::clusterIni('EsbDateConvert', 'FormatDate', 'merck.ini' );
            $availableDateParams        = SolrSafeOperatorHelper::clusterIni('EsbDateConvert', 'AvailableDateParams', 'merck.ini' );
            $skipParametersIfEmptyValue = SolrSafeOperatorHelper::clusterIni('SkipParametersIfEmptyValue', 'SkipParameter', 'merck.ini' );
           
            foreach ( $params as $key => $value )
            {                
                if ( array_key_exists( $key, $parameters['data']['profile'] ) )
                {
                    unset( $params[$key] );
                }
                if( !empty( $availableDateParams ) && isset( $availableDateParams[$key] ) && !empty($value)  )
                {
                    $params[$key] = $this->convertDateforUUMP( $value, $formatDate );
                }
                if( !empty( $skipParametersIfEmptyValue ) && isset( $skipParametersIfEmptyValue[$key] ) && empty($value) )
                {
                    unset( $params[$key] );
                }
            }
            $parameters['data']['profile'] = array_merge( $parameters['data']['profile'], $params );

            $sl = SystemLocale::fetchByClusterAndSystem( ClusterTool::clusterIdentifier(), 'esb_locale' );
            if ( !is_null( $sl ) )
            {
                $parameters['data']['profile']['locale'] = $sl;
            }
        }
        else
        {
            $parameters = array(
                'Data' => array_merge( $unifiedParameters, array( 'Params' => $params ) ),
                'cr'   => $this->getCountryOfRegistration()
            );
        }

        //LOG for locale field UUMP #36428
        if ( $this instanceof ServiceUserUUMP )
        {
            if( empty( $parameters['data']['profile']['locale'] ) )
            {
                $errorLocalMsg =  "\n\nEMPTY LOCALE:\nVALUES: " . json_encode( $parameters );
                \eZLog::write( $errorLocalMsg, 'esb_uump_locale.log');
            }
        }
        $result = $this->callWSHandler( $this->getEsbInterface( 'create' ), $parameters );

        if( SolrSafeOperatorHelper::featureIsActive('RegistrationAutologin') && SolrSafeOperatorHelper::feature('RegistrationAutologin', 'DisallowPendingUsers') == true && !isset( $_POST['register-helpdesk'] ))
        {
            if( $result['data']['profile']['validationStatus'] == 'PV' )
            {
                $result['RedirectPending'] = true;
                $result['RedirectPendingHref'] = eZINI::instance( 'site.ini' )->variable( 'SiteSettings', 'PendingUserStaticPage' );
                return $result;
            }
        }

        // if the registration was successful, we need to log the user on eZ + Backend side too
        if ( $this instanceof ServiceUserUUMP )
        {
            $noErrorOnCreate = ( isset( $result['data']['errorCode'] ) && $result['data']['errorCode'] == 0 );
        }
        else
        {
            $noErrorOnCreate = ( isset( $result['Data']['ErrorCode'] ) && $result['Data']['ErrorCode'] == 0 );
        }

        if ( $noErrorOnCreate )
        {
            $allowRedirect            = false;
            $availableRedirectContext = SolrSafeOperatorHelper::feature( 'RegistrationSettings', 'AvailableContextList' );
            $context                  = $_POST['context'] != '' ? $_POST['context'] : null;

            if ( $context !== null && !empty( $availableRedirectContext ) )
            {
                if ( is_array( $availableRedirectContext ) && in_array( $context, $availableRedirectContext ) )
                {
                    $allowRedirect = true;
                }
            }

            // BUT only there is no pending validation needed
            // OR if we are on that local validation page
            if ( ( !SolrSafeOperatorHelper::featureIsActive( 'OverrideWSHandler' ) || self::verifyHash() ) && !isset( $_POST['register-helpdesk'] ))
            {
                if ( $this instanceof ServiceUserUUMP )
                {
                    $userName   = isset( $result['data']['profile']['userName'] ) ? $result['data']['profile']['userName'] : null;
                    $userId     = $result['data']['profile']['userId'];
                    $userSpecialty = isset( $result['data']['profile']['userSpecialty'] ) ? preg_replace('#^A#', '', $result['data']['profile']['userSpecialty']) : null;
                }
                else
                {
                    $readValues = $this->read( array( "User_specialty" ), $result['Data']['Username'] );
                    $parameters = $parameters['Data']['Params'];
                    $userName = isset( $result['Data']['Username'] ) ? $result['Data']['Username'] : null;
                    $userSpecialty = isset( $readValues['Data']['Params']['User_specialty'] ) ? $readValues['Data']['Params']['User_specialty'] : null;
                }

                $businessNames = $this->getBusinessNamesForTicket();
                $ticketParams  = array();
                foreach ( $businessNames as $ticketParam => $businessName )
                {
                    if ( isset( $parameters['data']['profile'][$businessName] ) )
                    {
                        $ticketParams[$ticketParam] = $parameters['data']['profile'][$businessName];
                    }
                    elseif ( isset( $_POST[$businessName] ) )
                    {
                        $ticketParams[$ticketParam] = $_POST[$businessName];
                    }
                    elseif ( $businessName == $this->getBusinessNameMapping( 'countryOfRegistration' ) )
                    {
                        $ticketParams[$ticketParam] = $this->getCountryOfRegistration();
                    }
                    else
                    {
                        eZDebug::writeError( 'Could not get registration param: ' . $businessName );
                    }
                }

                if( $this instanceof ServiceUserUUMP )
                {
                    $ticketParams['Username'] = $userId;
                }
                elseif ( !empty($userName) )
                {
                    $ticketParams['Username'] = $userName;
                }
                
                if ( !empty($userSpecialty) )
                {
                    $ticketParams['User_specialty'] = $userSpecialty;
                }
                
                // used in response to log to the php backend
                $result['AllowRedirect'] = $allowRedirect;

                $ticketParams['toUValidated'] = true;

                MMUserLogin::loginUser( $ticketParams );
                $mmUser = MMUsers::getCurrentUserObject();
                $ticketParams['mmSettings']       = $mmUser->getMMSettings();
                $ticketParams['unorderedAppList'] = $mmUser->getApplicationList();
                $ticketParams['alterboxMsgReset'] = $mmUser->hasPreference('alterboxMsgReset') ? $mmUser->getPreferences('alterboxMsgReset') : true;
                $result['Ticket'] = MMUserLogin::encryptText( json_encode( $ticketParams ) );

            }
        }
        // Consult Popin for France | mobile check disabled - it fails on STG
        if (/* ContextTool::instance()->isMobile() && */ in_array(ClusterTool::clusterIdentifier(), array('cluster_france'))) 
        {
            CookieTool::destroyCookie('displayConsultMobile');
            CookieTool::destroyCookie('displayConsultMobile', '/', null);
            CookieTool::setCookie('displayConsultMobile', $mmUser->getConsult(), time() + ( 2 * 24 * 60 * 60 ));
        }

        if( isset( $_POST['register-helpdesk'] ))
        {
            $result['helpdeskRegister'] = '1';
        }


        return $result;
    }