<?php

namespace CGClientTickets\Actor;

class TicketEmailNotifyActor extends NotifyActor
{
    public function notify(\CGClientTickets\DataObject $message)
    {
        if( !is_a($message,'\CGClientTickets\message') ) throw new \RuntimeException('supplied object is not a valid message');

        // get email addresses to send to from message->dest
        if( $message->sent > 0 ) return; // nothing to do.
        $mod = \cms_utils::get_module(MOD_CGCLIENTTICKETS);
        $smarty = cmsms()->GetSmarty();
        $mailer = \cms_utils::get_module('CMSMailer');
        try {
            if( !is_object($mailer) ) throw new \Exception('Could not get CMSMailer module');
            if( $message->id < 1 ) throw new \Exception('Cannot send an unsaved message');

            $email_list = \CGClientTickets\utils::get_email_list($message->dest);
            if( !is_array($email_list) || count($email_list) == 0 ) return; // nothing to do. but not an error.

            $ticket = \CGClientTickets\ticket::load_by_id($message->ticket_id);

            $smarty->assign('ticket',$ticket);
            $smarty->assign('message',$message);
            foreach( $email_list as $row ) {
                $smarty->assign('username',$row['username']);
                $smarty->assign('email',$row['email']);

                $subject = $mod->ProcessTemplateFromData($mod->GetPreference('notify_subject'));
                $body = $mod->ProcessTemplateFromDataBase('notify_template');
                if( !$body ) throw new \Exception('No message body after processing notify template');

                $mailer->reset();
                $mailer->AddAddress($row['email']);
                $mailer->IsHTML(TRUE);
                $mailer->SetSubject($subject);
                $mailer->SetBody($body);
                if( $mod->GetPreference('notify_attachments') ) {
                    // attach files to the message
                    $attachments = $message->get_attachments();
                    if( is_array($attachments) && count($attachments) ) {
                        foreach( $attachments as $filename ) {
                            $path = $message->get_attachment_path().'/'.$filename;
                            if( file_exists($path) && is_readable($path) ) {
                                $mimetype = \cge_utils::get_mime_type($path);
                                $mailer->AddAttachment($path,$filename,'base64',$mimetype);
                            }
                        }
                    }
                }
                $mailer->Send();

                audit($message->ticket_id,$mod->GetName(),'Notification sent for ticket '.$message->ticket_id.' to '.$row['email']);
            }
        }
        catch( \Exception $e ) {
            debug_display($e); die();
            audit($msg->id,$mod->GetName(),'Error sending: '.$e->GetMessage());
        }
    }
}
?>
