<?php
namespace NMS;
use \nms_job;

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

    public function __construct( $nms_jobid )
    {
        parent::__construct();
        $this->module = 'NMS';
        $this->name = 'Initialize Sending of 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;
    }

    private function insert_job_email(\CMSMS\Database\Connection $db, $jobid, $messageid, $userid, $email, $uniqueid, $username)
    {
        $iquery = 'INSERT INTO '.NMS_MAILS_TABLE.' (jobid, messageid, userid, email, uniqueid, username) VALUES (?,?,?,?,?,?)';
        $dbr = $db->Execute($iquery,array($jobid,$messageid,$userid, $email,$uniqueid,$username));
        if( !$dbr ) return FALSE;
        return TRUE;
    }

    public function execute()
    {
        $nms_jobid = $this->nms_jobid;
        $db = cmsms()->GetDb();

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


        // get the lists
        $nms = \cms_utils::get_module(MOD_NMS);
        $lists = $nms->GetLists();

        $nms->SendEvent('OnStartJob', [ 'jobid'=>$nms_jobid, 'jobname'=>$nms_job['name'] ] );

        // loop through the parts
        $num_mails = 0;
        foreach( $nms_job['parts'] as $one_part ) {

            // get the list for the part
            if( !isset($lists[$one_part['listid']]) ) {
                audit($nms_jobid,'NMS','nms list '.$one_part['listid'].' not found');
                continue;
            }

            if( $lists[$one_part['listid']]['dynamic'] ) {
                $list = $lists[$one_part['listid']];
                // it's a dynamic list
                $parms = array();
                $res = UserTagOperations::get_instance()->CallUserTag($list['dynamic'],$parms);
                if( is_array($res) && count($res) ) {
                    $n = 0;
                    foreach( $res as $one_result ) {
                        $userid = null;
                        $username = null;
                        if( is_string($one_result) ) {
                            $email = $one_result;
                        }
                        else if( is_array($one_result) ) {
                            if( !isset($one_result['email']) ) continue;
                            $username = '';
                            $email = trim($one_result['email']);
                            if( isset($one_result['userid']) ) $userid = (int)$one_result['userid'];
                            if( isset($one_result['username']) ) $username = trim($one_result['username']);
                        }
                        if( !$email ) continue;
                        if( !is_email($email) ) continue; // a little pre-emptive striking.
                        $x = $this->insert_job_email($db, $nms_jobid, $one_part['messageid'], '', $email, '', $username);
                        if( $x ) $n++;
                    }

                    $num_mails += $n;
                    audit($nms_jobid,'NMS','Added '.$n.' emails from udt '.$list['dynamic'].' to job ');
                }
            }
            else {
                // its a static list....
                $q = "SELECT DISTINCT jobid,email,username,C.userid,C.uniqueid,messageid FROM ".
                    NMS_LISTUSER_TABLE." A left join ".
                    NMS_JOB_PARTS_TABLE." B on A.listid = B.listid left join ".
                    NMS_USERS_TABLE." C on A.userid = C.userid
                      WHERE C.disabled = 0 AND C.confirmed = 1
                      AND COALESCE(C.error_count,0) < ?
                      AND B.jobid = ? AND B.listid = ? AND B.messageid = ?";
                $dbr = $db->Execute( $q,
                                     array( (int) $nms->GetPreference('max_error_count',10),
                                            (int)$nms_jobid, (int)$one_part['listid'], (int)$one_part['messageid'] ));
                if( !$dbr || $dbr->RecordCount() == 0 ) {
                    audit($nms_jobid,'NMS'.' process job','no emails found in specified job part');
                    continue;
                }

                $n = 0;
                while( $dbr && !$dbr->EOF ) {
                    $row = $dbr->fields;
                    $x = $this->insert_job_email($db, $row['jobid'],$row['messageid'], $row['userid'],$row['email'],$row['uniqueid'], $row['username']);
                    if( $x ) $n++;
                    $dbr->MoveNext();
                }

                if( $n == 0 ) {
                    audit($nms_jobid,'NMS'.' process job','no emails found in specified job part');
                }
                $num_mails += $n;
                audit($nms_jobid,'NMS',sprintf('Added %d emails to the mails table for job %d',$n,$nms_jobid));
                continue;
            }
        } // for each part

        if( $num_mails == 0 ) {
            audit($nms_jobid,'NMS','no emails found for this job');
            throw new \RuntimeException('No Emails found for entire job');
            return cgjobmgr_task::STATUS_ERROR;
        }

        // and create a new job
        $process_job = new ProcessJob_CmsJob( $nms_jobid );
        $process_job->save();

        // set the nms job status to RUNNING
        $nms_job['status'] = NMS_JOBSTATUS_RUNNING;
        $nms_job['async_id'] = $process_job->id;
        $nms_job->save();

    }
} // end of class