<?php
/********************************************************************************
 * (c)1337 aheadware.com - All rights reserved
 ********************************************************************************/

/**
 * Class TB_Server_Control_Account
 */
class TB_Server_Control_Account
{

    /**
     * @param TB_Server_Core_RequestData $params
     * @return TB_Server_Core_Response
     */
    public static function getAccountRelatedData( TB_Server_Core_RequestData $params )
    {
        $resp = new TB_Server_Core_Response();

        $session = TB_Server_Core_Session::get();

        $resp->addData( 'account', $session->getAccount() );
        $resp->addData( 'profile', $session->getProfile() );
        $resp->addData( 'own_teams', TB_Shared_Ent_TeamData_Team::getByProfile( $session->getProfile() ) );

        return $resp;
    }

    public static function delete( TB_Server_Core_RequestData $params )
    {

        throw new \Exception( 'Does not work anymore.' );

        /*
        $resp = new TB_Server_Core_Response();

        $session = TB_Server_Core_Session::get();

        $account = $session->getAccount();
        if ( is_null( $account ) ) throw new Exception( "No account in session. Deletion failed." );

        $profile = $session->getProfile();

        $appointmentsToUpdate = TB_Shared_Ent_TeamData_Appointment::getAcceptedByProfile( $profile->id );

        $dbCore = TB_Shared_Db_Core::get();
        $dbTeam = TB_Shared_Db_TeamData::get();

        if ( $profile->ownsATeam() )
        {
            throw new \Exception( 'Cannot delete a profile who owns a team' );
        }

        try
        {
            $dbCore->beginTransaction();
            $dbTeam->beginTransaction();

            $account->delete();
            $profile->delete();

            $dbCore->commit();
            $dbTeam->commit();
        }
        catch( Exception $e )
        {
            $dbCore->rollBack();
            $dbTeam->rollBack();
            throw $e;
        }

        if ( $appointmentsToUpdate && count( $appointmentsToUpdate ) > 0 )
        {

            foreach( $appointmentsToUpdate as $app )
            {
                TB_Server_Control_Appointment::processWaitingList( $app );
            }
        }

        return $resp;
        */
    }

    /**
     * @param TB_Server_Core_RequestData $params
     * @return TB_Server_Core_Response
     */
    static public function registerDevice( TB_Server_Core_RequestData $params )
    {
        $resp = new TB_Server_Core_Response();

        $platform = $params->get( 'platform' );
        $platform = is_string( $platform ) ? strtoupper( $platform ) : NULL;
        $regId = $params->get( 'reg_id' );

        if ( isset( $regId ) && isset( $platform ) && in_array( $platform, TB_Shared_Ent_Core_DeviceReg::getPlatforms() ) )
        {
            $ss = TB_Server_Core_Session::get();
            $acc = $ss->getAccount();

            /** @var TB_Shared_Ent_Core_DeviceReg $deviceReg */
            $deviceReg = TB_Shared_Ent_Core_DeviceReg::getByAccountIdAndRegId( $acc->id, $regId );
            if ( is_null( $deviceReg ) )
            {
                $deviceReg = new TB_Shared_Ent_Core_DeviceReg();
                $deviceReg->account_id = $acc->id;
                $deviceReg->reg_id = $regId;
            }
            $deviceReg->platform = $platform;
            $deviceReg->save();
        }

        return $resp;
    }

    /**
     * Change password of currently logged in account
     *
     * @param TB_Server_Core_RequestData $params
     * @return TB_Server_Core_Response
     * @throws Exception
     */
    public static function changePassword( TB_Server_Core_RequestData $params ) {
        $resp = new TB_Server_Core_Response();


        $oldpw = $params->get( 'currentPassword' );
        $newpw = $params->get( 'newPassword' );

        if ( !TB_Shared_Utils_Validator::isValidPassword( $newpw ) ) {
            throw new Exception( 'New passwords do not match or are invalid!' );
        }

        /** @var TB_Shared_Ent_Core_Account $acc */
        $acc = TB_Server_Core_Session::get()->getAccount();

        if ( TB_Shared_Utils_Security::getSaltedPassword( $oldpw ) != $acc->pass )
        {
            $resp->addData( 'oldpasswordnok', true );
        }
        else
        {

            $newpw = TB_Shared_Utils_Security::getSaltedPassword( $newpw );
            $acc->pass = $newpw;
            $acc->save();

            // @todo Send mail

            $resp->addData( 'ok', true );
        }

        return $resp;

    }

    /**
     * Get the email change entry
     * @param TB_Server_Core_RequestData $params
     * @return TB_Server_Core_Response
     */
    public static function getEmailChange( TB_Server_Core_RequestData $params ) {
        $resp = new TB_Server_Core_Response();

        $acc = TB_Server_Core_Session::get()->getAccount();
        if ( isset( $acc ) ) {

            $resp->addData( 'acc', $acc->asArray() );

            /** @var TB_Shared_Ent_Core_EmailChange $ec */
            $ec = TB_Shared_Ent_Core_EmailChange::getByAccountId( $acc->id );
            if ( isset( $ec ) ) {
                $resp->addData( 'ec', $ec->asArray() );
            }
        }

        return $resp;
    }

    /**
     * Trigger email change opt in
     * @param TB_Server_Core_RequestData $params
     * @return TB_Server_Core_Response
     * @throws Exception
     */
    public static function changeEmail( TB_Server_Core_RequestData $params )
    {
        $resp = new TB_Server_Core_Response();

        $newEmail = $params->get( 'input-new-email' );
        $verifyPw = $params->get( 'verify-password' );

        /** @var TB_Shared_Ent_Core_Account $acc */
        $acc = TB_Server_Core_Session::get()->getAccount();

        if ( $acc->email == $newEmail ) {
            $resp->addData( 'nochange', true );
        } else if ( !TB_Shared_Utils_Validator::isValidEmail( $newEmail ) ) {
            throw new Exception( 'Invalid new email adresse: ' . $newEmail );
        } else if ( TB_Shared_Utils_Security::getSaltedPassword( $verifyPw ) != $acc->pass  ) {
            $resp->addData( 'invalidpw', true );
        } else {

            $accDuplicateEmail = TB_Shared_Ent_Core_Account::getByEmail( $newEmail );
            $emailChangeDuplicate = TB_Shared_Ent_Core_EmailChange::getByEmail( $newEmail );
            if ( isset( $accDuplicateEmail ) || isset( $emailChangeDuplicate ) )  {
                $resp->addData( 'emailexists', true );
            } else {
                $token = uniqid( 'ec' );
                $now = time();
                $until_dt = new DateTime( date( 'Y-m-d H:i:s', strtotime( '+2 day', $now ) ) );
                /** @var TB_Shared_Ent_Core_EmailChange $ec */
                $ec = new TB_Shared_Ent_Core_EmailChange();
                $ec->account_id = $acc->id;
                $ec->new_email = $newEmail;
                $ec->token = $token;
                $ec->valid_until_dt = $until_dt;
                $ec->save();

                TB_Server_Utils_Mail::sendEmailChange( array(
                    'token' => $token,
                    'email' => $newEmail
                ));

                $resp->addData( 'ok', true );
            }
        }

        return $resp;
    }
}