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

require_once __DIR__ . '/../../config/boot_global.php';
require_once __DIR__ . '/../../config/boot_local.php';


class TB_Server_Cron_SendPlayerInvitation extends TB_Server_Core_CronBase {
    /**
     * @throws Exception
     * @throws phpmailerException
     */
    protected function run() {
        $cnt = 0;
        $invites = TB_Shared_Ent_Core_Invitation::getForSending();
        /** @var TB_Shared_Ent_Core_Invitation $invite */
        foreach( $invites as $invite ) {
            /** @var TB_Shared_Ent_TeamData_Team $team */
            $team = TB_Shared_Ent_TeamData_Team::get( $invite->team_id );
            /** @var TB_Shared_Ent_TeamData_Profile $inviter */
            $inviter = TB_Shared_Ent_TeamData_Profile::get( $invite->inviter_profile_id );
            $data = array(
                'email' => $invite->email,
                'name' => $invite->first_name . ' ' . $invite->last_name,
                'inviter_display_name' => isset( $inviter ) ? $inviter->first_name . ' ' . $inviter->last_name : 'Unbekannt',
                'team_display_name' => isset( $team ) ? $team->display_name : 'Unbekanntes Team',
                'invite_link' => TB_Server_Core_Request::createClientUrl( 'Auth', 'registerplayer', array( 't' => $invite->token ) ),
                'help_link' => Francis_Utils_Config::get( 'url.client' ) . '/dl/TBuddy-NeuesTeammitgliedWerden.pdf',
                'help_link2' => Francis_Utils_Config::get( 'url.client' ) . '/dl/TBuddy-TerminZuOderAbsage.pdf'
            );

            // Check if sending was possible
            $success = false;
            try {
                $success = TB_Server_Utils_Mail::sendInvitationMail( $data );
            } catch( Exception $e ) {
                TB_Server_Utils_Log::get()->log( $e );
                $success = false;
            }

            // Handle cases
            if ( true === $success ) {
                $invite->state = TB_Shared_Ent_Core_Invitation::STATE_DELIVERED;
                $invite->save();
            } else {
                TB_Server_Utils_Log::get()->log( "Invitation for " . $invite->email . " could not be sent." );
            }
        }

    }
}

$cron = new TB_Server_Cron_SendPlayerInvitation();
$cron->execute();