<?php
namespace NMS;
use \nms_job;

class FinishJob_CmsJob extends \CMSMS\Async\Job
{
    private $nms_jobid;

    public function __construct( $nms_jobid )
    {
        parent::__construct();
        $this->module = 'NMS';
        $this->name = 'Finish job '.$nms_jobid;

        $nms_jobid = (int) $nms_jobid;
        if( $nms_jobid < 1 ) throw new \LogicException('Invalid jobid passed to '.__METHOD__);
        $this->nms_jobid = (int) $nms_jobid;
    }

    public function execute()
    {
        $nms_jobid = $this->nms_jobid;
        $db = cmsms()->GetDb();
        $nms = \cms_utils::get_module('NMS');

        // test the job
        $nms_job = nms_job::load($nms_jobid);
        if( $nms_job['status'] != NMS_JOBSTATUS_FINISHING ) {
            if( $nms_job['STATUS'] == NMS_JOBSTATUS_PAUSED || $nms_job['status'] == NMS_JOBSTATUS_ABORTED ) return;
            audit($nms_jobid,'NMS','nms job has invalid status');
            throw new \RuntimeException("Job $nms_jobid has invalid status, cannot initialize");
        }
        unset( $nms_job );

        // now update the job in the db
        $query = 'UPDATE '.NMS_JOBS_TABLE.' SET status = ?, finished = NOW() WHERE jobid = ?';
        $db->Execute($query,array(NMS_JOBSTATUS_FINISHED,$nms_jobid));

        $tmp = $nms->GetPreference('send_jobcomplete_groups');
        if( $tmp > 0 ) {
            $emaillist = \cge_userops::expand_group_emails();
            if( !count($emaillist) ) return;

            // load the job again.
            $nms_job = nms_job::load($nms_jobid);
            if( $nms_job['status'] != NMS_JOBSTATUS_FINISHED ) {
                audit($nms_jobid,'NMS','nms job has invalid status');
                throw new \RuntimeException("Job $nms_jobid has invalid status, cannot initialize");
            }

            // give stuff to smarty.
            $smarty = cmsms()->GetSmarty();

            // gather statistics
            // - total rows
            $query = 'SELECT count(messageid) FROM '.NMS_MAILS_TABLE.' WHERE jobid = ?';
            $nrows = $db->GetOne($query,array($nms_jobid));
            $smarty->assign('numrows',$nrows);

            // update errors.
            // - total errors
            $query = 'SELECT email,username,status FROM '.NMS_MAILS_TABLE.' WHERE jobid = ? AND (status =  ? OR status = ?)';
            $nerrors = 0;
            $errors = $db->GetArray($query,array($nms_jobid,'error','sending'));
            if( is_array($errors) && count($errors) ) {
                $nerrors = count($errors);
                $smarty->assign('errors',$errors);
            }
            $smarty->assign('nerrors',$nerrors);

            $stime = $db->UnixTimeStamp($nms_job['started']);
            $smarty->assign('stime',$stime);
            $etime = $db->UnixTimeStamp($nms_job['finished']);
            $smarty->assign('etime',$etime);
            $dtime = $etime - $stime;
            $smarty->assign('dtime',$dtime);
            $smarty->assign('job',$nms_job);

            // get the parts for the job.'
            $query = 'SELECT DISTINCT M.subject FROM '.NMS_MESSAGES_TABLE.' M LEFT JOIN '.NMS_JOB_PARTS_TABLE.' P ON M.messageid = P.messageid
                  WHERE P.jobid = ?';
            $subject = $db->GetOne($query,array($nms_jobid));
            $smarty->assign('subject',$subject);

            $query = 'SELECT DISTINCT L.name FROM '.NMS_LIST_TABLE.' L LEFT JOIN '.NMS_JOB_PARTS_TABLE.' P ON L.listid = P.listid
                  WHERE P.jobid = ?';
            $lists = $db->GetCol($query,array($nms_jobid));
            $smarty->assign('lists',$lists);

            // send mails
            $mailer = new \cms_mailer;
            $mailer->SetCharSet($nms->GetPreference('message_charset'));
            $mailer->SetFromName($nms->GetPreference('admin_name'));
            $mailer->SetFrom($nms->GetPreference('admin_email'));
            $replyto = $nms->GetPreference('admin_replyto');
            if( !empty($replyto) ) $mailer->AddReplyTo($replyto);

            $mailer->AddCustomHeader("X-Mailer: CMS Made Simple ".CMS_VERSION.' ('.$nms->GetName()." ".$nms->GetVersion().' )');
            $mailer->SetSubject($nms->GetPreference('send_jobcomplete_subject'));
            $mailer->IsHTML(true);
            foreach( $emaillist as $one ) {
                $mailer->AddAddress($one);
            }
            $body = $nms->ProcessTemplateFromDatabase('send_jobcomplete_template');
            $mailer->SetBody($body);
            $mailer->Send();
        }

        // cleanup mails table
        $sql = 'DELETE FROM '.NMS_MAILS_TABLE.' WHERE jobid = ?';
        $db->Execute( $sql, [ $nms_jobid ] );

        audit($nms_jobid,$nms->GetName(),'Job Finished: '.$nms_job['title']);
    }
} // end of class