<?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_SendEmailNotification extends TB_Server_Core_CronBase {
    /**
     * @throws Exception
     * @throws phpmailerException
     */
    protected function run() {
        $cnt = 0;
        $ens = TB_Shared_Ent_Core_EmailNotification::getAll();
        /** @var TB_Shared_Ent_Core_EmailNotification $en */
        foreach( $ens as $en ) {
            $this->processEmailNotification( $en );
            $en->delete();
        }
    }

    /**
     * @param TB_Shared_Ent_Core_EmailNotification $en
     */
    private function processEmailNotification( TB_Shared_Ent_Core_EmailNotification $en ) {
        $addresses = array();
        /** @var TB_Shared_Ent_TeamData_Profile $sender */
        $sender = NULL;
        /** @var TB_Shared_Ent_TeamData_Profile $profile */
        $profile = NULL;
        /** @var TB_Shared_Ent_Core_Account $account */
        $account = NULL;

        // Template data
        $data = array(
            'email' => NULL,
            'subject' => $en->subject,
            'content' => $en->content
        );

        // If receiver is a complete team
        if( TB_Shared_Ent_Core_EmailNotification::RECEIVER_TYPE_TEAM == $en->receiver_type ) {

            // Resolve email addresses
            $sender = TB_Shared_Ent_TeamData_Profile::get( $en->sender_profile_id );
            $profiles = TB_Shared_Ent_TeamData_Profile::getProfilesByTeamId( $sender->team_id );
            foreach( $profiles as $profile ) {
                $account = TB_Shared_Ent_Core_Account::get( $profile->account_id );
                array_push( $addresses, $account->email );
            }

        } else if ( TB_Shared_Ent_Core_EmailNotification::RECEIVER_TYPE_PROFILE == $en->receiver_type ) {

            // Resolvle email address of receiver profile
            $profile = TB_Shared_Ent_TeamData_Profile::get( $en->receiver_id );
            $account = TB_Shared_Ent_Core_Account::get( $profile->account_id );
            if ( isset( $profile ) && isset( $account ) ) {
                array_push( $addresses, $account->email );
            } else {
                TB_Server_Utils_Log::get()->log( "Cannot find account for profile id: " . $en->receiver_id );
            }
        }

        // Send each mail individually
        foreach( $addresses as $address ) {
            try {
                $data[ 'email' ] = $address;
                TB_Server_Utils_Mail::sendEmailNotification( $data );
            } catch ( Exception $e ) {
                TB_Server_Utils_Log::get()->log( $e );
            }
        }
    }
}

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