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


class TB_Server_Job_DailyNotifications extends TB_Server_Job_Base
{
    public function __construct( TB_Shared_Ent_TeamData_Job $jobEntity )
    {
        $this->entity = $jobEntity;
    }

    public function execute()
    {
        $birthdayProfiles = TB_Shared_Ent_TeamData_Profile::getTodaysBirthdayProfiles();

        /** @var TB_Shared_Ent_TeamData_Profile $bp */
        foreach( $birthdayProfiles as $bp )
        {
            $bpTeamIds = $bp->getTeamIds();
            $receiverIds = array();

            foreach( $bpTeamIds as $teamId )
            {
                $adminsOfTeam = TB_Shared_Ent_TeamData_Profile::getAdminsOfTeamId( $teamId );
                /** @var TB_Shared_Ent_TeamData_Profile $teamAdmin */
                foreach( $adminsOfTeam as $teamAdmin )
                {
                    if ( !in_array( $teamAdmin->id, $receiverIds ) )
                    {
                        array_push( $receiverIds, $teamAdmin->id );
                    }
                }

                unset( $adminsOfTeam );
            }

            TB_Server_Core_Notification::notifyBirthday( $receiverIds, $bp );

            unset( $receiverIds );
        }
    }

    public function onDone()
    {
        // Reset event to start the next day
        $nowDt = new DateTime( 'now',  new \DateTimeZone( "UTC" )  );
        $nowDt->setTime( 5, 0, 0 );
        $nowDt->modify( '+1 day' );
        $this->entity->trigger_dt = $nowDt;
        $this->entity->job_status = TB_Shared_Ent_TeamData_Job::JOB_STATUS_READY;
        $this->entity->touch( 'job_status' );
        $this->entity->save();
    }

    public static function getRefId()
    {
        return 'system-daily-notifications';
    }
}