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

/**
 * Class TB_Server_Core_Events
 */
class TB_Server_Core_Events {

    /**
     * Add all global event listener
     */
    public static function init() {
        $eh = Francis_Core_EventHandler::get();
        // Appointments
        $eh->addListener( 'appointment_created',  'TB_Server_Core_Events::onAppointmentCreated' );
        $eh->addListener( 'appointment_updated',  'TB_Server_Core_Events::onAppointmentUpdated' );
        $eh->addListener( 'appointment_deleted',  'TB_Server_Core_Events::onAppointmentDeleted' );
        $eh->addListener( 'profile_created',  'TB_Server_Core_Events::onProfileCreated' );
        $eh->addListener( 'profile_picture_updated',  'TB_Server_Core_Events::onProfilePicutreUpdated' );
        $eh->addListener( 'team_emblem_updated',  'TB_Server_Core_Events::onTeamEmblemUpdated' );
        $eh->addListener( 'attendee_created', 'TB_Server_Core_Events::onAttendeeCreated' );
        $eh->addListener( 'attendee_updated', 'TB_Server_Core_Events::onAttendeeUpdated' );
        $eh->addListener( 'chat_created', 'TB_Server_Core_Events::onChatCreated' );
        $eh->addListener( 'news_custom_created', 'TB_Server_Core_Events::onCustomNewsCreated' );
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Global event handlers
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////

    // Appointment
    public static function onAppointmentCreated( array $data ) {
        if ( !isset( $data[ 'entity' ] ) ) return;

        // Create appropriate news entry

        /** @var TB_Shared_Ent_TeamData_Appointment $entity */
        $entity = $data[ 'entity' ];

        // Only perform actions on single appointment to avoid spamming
        if ( is_null( $entity->serial_id ) ) {
            $user = TB_Server_Core_Session::get()->getProfile();
            $news = new TB_Shared_Ent_TeamData_News();
            $news->team_id = $entity->team_id;
            $news->author_profile_id = $user->id;
            $news->txt_key = 'txt_appointment_created';
            $news->txt_key_params_sr = $entity->asArray();
            $news->ref_content_type = TB_Shared_Ent_TeamData_News::REF_CONTENT_TYPE_APPOINTMENT;
            $news->ref_content_type_id = $entity->id;
            $news->created = time();
            $news->save();

            // Send push notification
            $team = TB_Server_Core_Session::get()->getTeam();
            $subject = is_null( $entity->subject ) ? $entity->home . ':' . $entity->guest : $entity->subject;
            $pn = array(
                'title' => $team->display_name . ' - Neuer Termin',
                'message' => 'Der Termin ' . $subject . ' wurde erstellt.'
            );
            TB_Server_Core_PushNotification::get()->sendTeam( $pn );
        } else if ( 0 == $entity->serial_id ) {
            $user = TB_Server_Core_Session::get()->getProfile();
            $news = new TB_Shared_Ent_TeamData_News();
            $news->team_id = $entity->team_id;
            $news->author_profile_id = $user->id;
            $news->txt_key = 'txt_serial_appointment_created';
            $news->txt_key_params_sr = $entity->asArray();
            $news->ref_content_type = TB_Shared_Ent_TeamData_News::REF_CONTENT_TYPE_APPOINTMENT;
            $news->ref_content_type_id = $entity->id;
            $news->created = time();
            $news->save();

            // Send push notification
            $team = TB_Server_Core_Session::get()->getTeam();
            $subject = is_null( $entity->subject ) ? $entity->home . ':' . $entity->guest : $entity->subject;
            $pn = array(
                'title' => $team->display_name . ' - Neuer Serientermin',
                'message' => 'Der Serientermin ' . $subject . ' wurde erstellt.'
            );
            TB_Server_Core_PushNotification::get()->sendTeam( $pn );
        }


    }

    public static function onAppointmentUpdated( array $data ) {
        if ( !isset( $data[ 'entity' ] ) ) return;

        /** @var TB_Shared_Ent_TeamData_Appointment $entity */
        $entity = $data[ 'entity' ];

        // Note:
        // Special case when updating the serial_id on a serial appointment
        if ( isset( $entity ) && $entity->isTouched( 'serial_id' ) ) return;

        $user = TB_Server_Core_Session::get()->getProfile();
        $news = new TB_Shared_Ent_TeamData_News();
        $news->team_id = $entity->team_id;
        $news->author_profile_id = $user->id;
        $news->txt_key = 'txt_appointment_updated';
        $news->txt_key_params_sr = $entity->asArray();
        $news->ref_content_type = TB_Shared_Ent_TeamData_News::REF_CONTENT_TYPE_APPOINTMENT;
        $news->ref_content_type_id = $entity->id;
        $news->created = time();
        $news->save();

        // Send push notification
        $team = TB_Server_Core_Session::get()->getTeam();
        $subject = is_null( $entity->subject ) ? $entity->home . ':' . $entity->guest : $entity->subject;
        $pn = array(
            'title' => $team->display_name . ' - Terminänderung',
            'message' => 'Termin ' . $subject . ' wurde aktualisiert.'
        );
        TB_Server_Core_PushNotification::get()->sendTeam( $pn );
    }

    public static function onAppointmentDeleted( array $data ) {
        if ( !isset( $data[ 'entity' ] ) ) return;

        /** @var TB_Shared_Ent_TeamData_Appointment $entity */
        $entity = $data[ 'entity' ];
        $user = TB_Server_Core_Session::get()->getProfile();
        $news = new TB_Shared_Ent_TeamData_News();
        $news->team_id = $entity->team_id;
        $news->author_profile_id = $user->id;
        $news->txt_key = 'txt_appointment_deleted';
        $news->txt_key_params_sr = $entity->asArray();
        $news->ref_content_type = TB_Shared_Ent_TeamData_News::REF_CONTENT_TYPE_APPOINTMENT;
        $news->created = time();
        $news->save();

        // Send push notification
        $team = TB_Server_Core_Session::get()->getTeam();
        $subject = is_null( $entity->subject ) ? $entity->home . ':' . $entity->guest : $entity->subject;
        $pn = array(
            'title' => $team->display_name . ' - Termin gelöscht.',
            'message' => 'Termin ' . $subject . ' wurde entfernt.'
        );
        TB_Server_Core_PushNotification::get()->sendTeam( $pn );

        // Send email
        $tpl = new TB_Server_Utils_Template( 'mail/appointmentdeleted2' );
        $tplVars = $entity->asArray();
        $tplVars[ 'appointment_link' ] = TB_Server_Core_Request::createClientUrl( 'Appointment' );
        $mail = new TB_Shared_Ent_Core_EmailNotification();
        $mail->sender_profile_id = $user->id;
        $mail->receiver_type = TB_Shared_Ent_Core_EmailNotification::RECEIVER_TYPE_TEAM;
        $mail->receiver_id = $team->id;
        $mail->subject = 'TBuddy - Termin gelöscht';
        $mail->content = $tpl->get( $tplVars );
        //$mail->save();
    }

    // Profile
    public static function onProfileCreated( array $data ) {
        if ( !isset( $data[ 'entity' ] ) ) return;

        /** @var TB_Shared_Ent_TeamData_Profile $entity */
        $entity = $data[ 'entity' ];
        $team = NULL;
        $txtKey = 'txt_profile_created';
        $params = $entity->asArray();
        if ( $entity->isTrainer() ) {
            /** @var TB_Shared_Ent_TeamData_Team $team */
            $team = TB_Shared_Ent_TeamData_Team::get( $entity->team_id );
            $txtKey = 'txt_trainer_profile_created';
            $params[ 'team_name' ] = $team->display_name;
        }

        $news = new TB_Shared_Ent_TeamData_News();
        $news->team_id = $entity->team_id;
        $news->author_profile_id = $entity->id;
        $news->txt_key = $txtKey;
        $news->txt_key_params_sr = $params;
        $news->ref_content_type = TB_Shared_Ent_TeamData_News::REF_CONTENT_TYPE_PROFILE;
        $news->created = time();

        $news->save();
    }

    /**
     * @param array $data
     */
    public static function onProfilePicutreUpdated( array $data ) {

        if ( !isset( $data[ 'profile' ] ) ) return;

        /** @var TB_Shared_Ent_TeamData_Profile profile */
        $profile = $data[ 'profile' ];
        $team = NULL;
        $txtKey = 'txt_profile_picture_updated';
        $params = $profile->asArray();

        $news = new TB_Shared_Ent_TeamData_News();
        $news->team_id = $profile->team_id;
        $news->author_profile_id = $profile->id;
        $news->txt_key = $txtKey;
        $news->txt_key_params_sr = $params;
        $news->ref_content_type = TB_Shared_Ent_TeamData_News::REF_CONTENT_TYPE_PROFILE;
        $news->created = time();
        $news->save();

        // Send push notification
        $team = TB_Server_Core_Session::get()->getTeam();
        $buddyName = $profile->getName();
        $pn = array(
            'title' => $team->display_name . ' - Neues Profilbild',
            'message' => $buddyName . ' hat sein Profilbild aktualisiert.'
        );
        TB_Server_Core_PushNotification::get()->sendTeam( $pn );

    }

    public static function onTeamEmblemUpdated( array $data ) {

        if ( !isset( $data[ 'profile' ] ) || !isset( $data[ 'team' ] ) ) return;

        /** @var TB_Shared_Ent_TeamData_Profile profile */
        $profile = $data[ 'profile' ];
        /** @var TB_Shared_Ent_TeamData_Team $team */
        $team = $data[ 'team' ];
        $txtKey = 'txt_team_emblem_updated';
        $params = array_merge( $profile->asArray(), $team->asArray() );

        $news = new TB_Shared_Ent_TeamData_News();
        $news->team_id = $profile->team_id;
        $news->author_profile_id = $profile->id;
        $news->txt_key = $txtKey;
        $news->txt_key_params_sr = $params;
        $news->ref_content_type = TB_Shared_Ent_TeamData_News::REF_CONTENT_TYPE_TEAM;
        $news->created = time();
        $news->save();

        // Send push notification
        $team = TB_Server_Core_Session::get()->getTeam();
        $buddyName = $profile->getName();
        $pn = array(
            'title' => $team->display_name . ' - Neues Teamemblem',
            'message' => $buddyName . ' hat das Teamemblem aktualisiert.'
        );
        TB_Server_Core_PushNotification::get()->sendTeam( $pn );


    }

    public static function onAttendeeCreated( array $data ) {
        if ( !isset( $data[ 'entity' ] ) ) return;

        /** @var TB_Shared_Ent_TeamData_Attendee $entity */
        $entity = $data[ 'entity' ];
        /** @var TB_Shared_Ent_TeamData_Profile $profile */
        $profile = TB_Shared_Ent_TeamData_Profile::get( $entity->profile_id );
        /** @var TB_Shared_Ent_TeamData_Appointment $appointment */
        $appointment = TB_Shared_Ent_TeamData_Appointment::get( $entity->appointment_id );

        if ( isset( $entity ) && isset( $profile ) && isset( $appointment ) ) {
            $params = array();
            $params[ 'appointment' ] = $appointment->asArray();
            $params[ 'new_status' ] = $entity->status;

            $news = new TB_Shared_Ent_TeamData_News();
            $news->team_id = $profile->team_id;
            $news->author_profile_id = $profile->id;
            $news->txt_key = ( $params[ 'new_status' ] == TB_Shared_Ent_TeamData_Attendee::STATUS_ACCEPTED ) ? 'txt_attendee_created_accepted' : 'txt_attendee_created_declined';
            $news->txt_key_params_sr = $params;
            $news->ref_content_type = TB_Shared_Ent_TeamData_News::REF_CONTENT_TYPE_ATTENDEE;
            $news->ref_content_type_id = $appointment->id;
            $news->created = time();

            $news->save();
        } else {
            TB_Server_Utils_Log::get()->log( 'Could not log onAttendeeCreated' );
        }
    }

    public static function onAttendeeUpdated( array $data ) {
        if ( !isset( $data[ 'entity' ] ) ) return;

        /** @var TB_Shared_Ent_TeamData_Attendee $entity */
        $entity = $data[ 'entity' ];
        /** @var TB_Shared_Ent_TeamData_Profile $profile */
        $profile = TB_Shared_Ent_TeamData_Profile::get( $entity->profile_id );
        /** @var TB_Shared_Ent_TeamData_Appointment $appointment */
        $appointment = TB_Shared_Ent_TeamData_Appointment::get( $entity->appointment_id );

        if ( isset( $entity ) && isset( $profile ) && isset( $appointment ) ) {
            $touched = $entity->getTouched();
            $params = array();
            $params[ 'appointment' ] = $appointment->asArray();
            $params[ 'new_status' ] = array_key_exists( 'status', $touched ) ? $touched[ 'status' ] : NULL;
            $params[ 'new_comment' ] = array_key_exists( 'comment', $touched ) ? $touched[ 'comment' ] : NULL;

            $txtKey = NULL;
            if ( array_key_exists( 'status', $touched ) ) {
                $txtKey = 'txt_attendee_updated_';
                if ( $params[ 'new_status' ] == TB_Shared_Ent_TeamData_Attendee::STATUS_ACCEPTED ) {
                    $txtKey .= 'to_accepted';
                } else {
                    $txtKey .= 'to_declined';
                }

                if ( is_string( $params[ 'new_comment' ] ) ) {
                    $txtKey .= '_with_comment';
                }
            } else if ( is_string( $params[ 'new_comment' ] ) ) {
                $txtKey = 'txt_attendee_updated_comment';
            }

            if ( !is_null( $txtKey ) ) {
                $news = new TB_Shared_Ent_TeamData_News();
                $news->team_id = $profile->team_id;
                $news->author_profile_id = $profile->id;
                $news->txt_key = $txtKey;
                $news->txt_key_params_sr = $params;
                $news->ref_content_type = TB_Shared_Ent_TeamData_News::REF_CONTENT_TYPE_ATTENDEE;
                $news->ref_content_type_id = $appointment->id;
                $news->created = time();
                $news->save();
            }
        } else {
            TB_Server_Utils_Log::get()->log( 'Could not log onAttendeeCreated' );
        }
    }

    /**
     * Sends notification when a new chat message has been created
     * @param array $data
     */
    public static function onChatCreated( array $data ) {
        $teamName = isset( $data[ 'team_name' ] ) ? $data[ 'team_name' ] : NULL;
        $authorName = isset( $data[ 'creator_name' ] ) ? $data[ 'creator_name' ] : NULL;

        if ( isset( $teamName ) && isset( $authorName ) ) {
            $pn = array(
                'title' => $teamName . ' - Chat',
                'message' => 'Nachricht von ' . $authorName
            );
            TB_Server_Core_PushNotification::get()->sendTeam( $pn );
        }
    }

    /**
     * @param array $data
     */
    public static function onCustomNewsCreated( array $data ) {
        $teamName = isset( $data[ 'team_name' ] ) ? $data[ 'team_name' ] : NULL;
        $authorName = isset( $data[ 'creator_name' ] ) ? $data[ 'creator_name' ] : NULL;

        if ( isset( $teamName ) && isset( $authorName ) ) {
            $pn = array(
                'title' => $teamName . ' - Meldung vom Coach',
                'message' => 'Coach Nachricht von ' . $authorName
            );
            TB_Server_Core_PushNotification::get()->sendTeam( $pn );
        }
    }

}