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


class TB_Server_Control_Message
{

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

        $recipientData = self::getAllowedRecipientData();

        $resp->addData( 'recipients', $recipientData[ 'recipient_profiles' ] );
        $resp->addData( 'recipients_team_profiles', $recipientData[ 'recipient_team_profiles' ] );

        return $resp;
    }

    /**
     * @param TB_Server_Core_RequestData $params
     * @return TB_Server_Core_Response
     */
    public static function getList( TB_Server_Core_RequestData $params )
    {
        $resp = new TB_Server_Core_Response();
        $currentProfile = TB_Server_Core_Session::get()->getProfile();
        $messageData = TB_Shared_Ent_TeamData_Message::getForProfileId( $currentProfile->id );
        $resp->addData( 'message_data', $messageData );
        return $resp;
    }

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

        $messageId = $params->get( 'messageId' );
        $currentProfile = TB_Server_Core_Session::get()->getProfile();
        $messageData = TB_Shared_Ent_TeamData_Message::getForProfileIdById(
            $currentProfile->id,
            $messageId
        );

        if ( is_null( $messageData ) || 0 === count( $messageData ) )
        {
            throw new \Exception( 'Message not found.' );
        }

        $resp->addData( 'message_data', $messageData );

        return $resp;
    }

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

        $messageIds = $params->get( 'messageIds' );
        if ( is_string( $messageIds ) )
        {
            $messageIds = explode( ",", $messageIds );
        }

        if ( !is_array( $messageIds ) ||  0 === count( $messageIds ) )
        {
            throw new \Exception( 'Invalid message ids to delete.' );
        }

        $currentProfileId = TB_Server_Core_Session::get()->getProfileId();

        /**
         * Delete all messages
         */
        foreach( $messageIds as $messageId )
        {
            $message = TB_Shared_Ent_TeamData_Message::get( $messageId );
            if ( isset( $message ) && $message->recipient_id == $currentProfileId )
            {
                $message->delete();
            }
        }

        return $resp;
    }

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

        /** @var TB_Shared_Ent_TeamData_Profile $currentProfile */
        $currentProfile = TB_Server_Core_Session::get()->getProfile();

        $recipientIds = $params->get( 'recipientIds' );
        if ( !is_null( $recipientIds ) )
        {
            $recipientIds = explode( ",", $recipientIds );
        }

        if ( !is_array( $recipientIds ) || 0 === count( $recipientIds ) )
        {
            throw new \Exception( "No recipients found." );
        }

        // Perform security check
        $allowedRecipientData = self::getAllowedRecipientData();
        foreach( $recipientIds as $recipientId )
        {
            $canSend = false;
            /** @var TB_Shared_Ent_TeamData_Profile $arp */
            foreach( $allowedRecipientData[ 'recipient_profiles' ] as $arp )
            {
                if ( $recipientId == $arp->id )
                {
                    $canSend = true;
                    break;
                }
            }

            if ( false == $canSend )
            {
                throw new Exception( 'Not allowed recipient profile id found.' );
            }
        }

        $subject = $params->get( 'subject' );
        $message = $params->get( 'message' );

        if ( is_null( $subject ) || is_null( $message ) )
        {
            throw new \Exception( 'No subject and/or message found. Message creation failed.');
        }

        // All done
        // Create message - each per profile
        $notificationHeadline = 'Nachricht von ' . $currentProfile->getName();
        $notificationSubject = 'Betreff: ' . _xss( $subject );

        $dtNow = TB_Server_Utils_Helper::getUTCNowDateTime();

        $entMessage = new TB_Shared_Ent_TeamData_Message();
        foreach( $recipientIds as $recipientId )
        {
            $entMessage->id = NULL;
            $entMessage->recipient_id = $recipientId;
            $entMessage->creator_id = $currentProfile->id;
            $entMessage->subject = _xss( $subject );
            $entMessage->message = _xss( $message );
            $entMessage->last_updated_dt = $dtNow;
            $entMessage->created_dt = $dtNow;

            $entMessage->save();

            TB_Server_Core_Notification::sendToProfiles(
                $notificationHeadline,
                $notificationSubject,
                array( $recipientId ),
                TB_Server_Core_Notification::createAdditionalData( '#/message/'  . $entMessage->id )
            );
        }

        return $resp;
    }

    /**
     * @return array
     */
    private static function getAllowedRecipientData()
    {
        $recipientsProfiles = [];
        $recipientsTeamProfiles = [];
        $recipientsProfilesIds = [];
        $recipientsTeamProfilesIds = [];

        $currentProfile = TB_Server_Core_Session::get()->getProfile();
        $currentProfileTeamIds = $currentProfile->getTeamIds();
        foreach ( $currentProfileTeamIds  as $tId )
        {
            $rtps = TB_Shared_Ent_TeamData_Profile::getProfilesByTeamId( $tId );
            /** @var TB_Shared_Ent_TeamData_Profile $rtp */
            foreach( $rtps as $rtp )
            {
                if ( $rtp->id == $currentProfile->id )
                {
                    continue;
                }

                if ( in_array( $rtp->id, $recipientsTeamProfilesIds ) )
                {
                    continue;
                }

                if ( false === $currentProfile->canAccessProfile( $rtp ) )
                {
                    continue;
                }

                array_push( $recipientsTeamProfilesIds, $rtp->id );
                array_push( $recipientsTeamProfiles, $rtp );

                if ( in_array( $rtp->id, $recipientsProfilesIds ) )
                {
                    continue;
                }

                array_push( $recipientsProfilesIds, $rtp->id );
                array_push( $recipientsProfiles, $rtp );
            }
        }

        return array(
            'recipient_profiles' => $recipientsProfiles,
            'recipient_team_profiles' => $recipientsTeamProfiles
        );
    }
}