<?php
require_once 'modules/admin/models/ServicePlugin.php';
require_once'newedge/classes/NE_MailGateway.php';
require_once 'modules/support/models/Ticket.php';

/**
* @package Plugins
*/
class PluginAutoclose extends ServicePlugin
{
    function getVariables()
    {
	$enabledType="";
	if (!isset($this->configuration['modules']['support']['installedVersion'])) {
		$enabledType="hidden";
	}else{
		$enabledType="yesno";
	}
        $variables = array(
            /*T*/'Plugin Name'/*/T*/   => array(
                'type'          => 'hidden',
                'description'   => /*T*/''/*/T*/,
                'value'         => /*T*/'Ticket Auto Close'/*/T*/,
            ),
			
	    /*T*/'Enabled'/*/T*/       => array(
                'type'          => $enabledType,
                'description'   => /*T*/'When enabled, tickets remaining unresponded to by customers for x amount of days will automatically be closed.'/*/T*/,
                'value'         => '0',
            ),

            /*T*/'Days to trigger autoclose'/*/T*/       => array(
                'type'          => 'text',
                'description'   => /*T*/'Enter number of days to wait before autoclosing a ticket that is in the waiting on customer status.'/*/T*/,
                'value'         => '3',
            ),
            /*T*/'Ticket Message'/*/T*/       => array(
                'type'          => 'text',
                'description'   => /*T*/'Enter the message you would like entered into the ticket when it is closed.  NOTE: the customer name and company name will automatically be added to the message header and footer.'/*/T*/,
                'value'         => 'Your ticket has been closed due to inactivity.  If this issue has not been resolved please reopen this ticket.',
            ),
            /*T*/'Pre-Notify Customer'/*/T*/       => array(
                'type'          => 'yesno',
                'description'   => /*T*/'When enabled the customer will be notified before close a ticket. Use the AutoClose Ticket Service Template'/*/T*/,
                'value'         => '1',
            ),
            /*T*/'Days to trigger Pre-Notify autoclose'/*/T*/       => array(
                'type'          => 'text',
                'description'   => /*T*/'Enter number of days to notify before autoclosing a ticket that is in the waiting on customer status.'/*/T*/,
                'value'         => '1',
            ),
            /*T*/'Notify Customer'/*/T*/       => array(
                'type'          => 'yesno',
                'description'   => /*T*/'When enabled the customer will be notified when a ticket is closed.'/*/T*/,
                'value'         => '1',
            ),
            /*T*/'Run schedule - Minute'/*/T*/  => array(
                'type'          => 'text',
                'description'   => /*T*/'Enter number, range, list or steps'/*/T*/,
                'value'         => '30',
                'helpid'        => '8',
            ),
            /*T*/'Run schedule - Hour'/*/T*/  => array(
                'type'          => 'text',
                'description'   => /*T*/'Enter number, range, list or steps'/*/T*/,
                'value'         => '*',
            ),
            /*T*/'Run schedule - Day'/*/T*/  => array(
                'type'          => 'text',
                'description'   => /*T*/'Enter number, range, list or steps'/*/T*/,
                'value'         => '*',
            ),
            /*T*/'Run schedule - Month'/*/T*/  => array(
                'type'          => 'text',
                'description'   => /*T*/'Enter number, range, list or steps'/*/T*/,
                'value'         => '*',
            ),
            /*T*/'Run schedule - Day of the week'/*/T*/  => array(
                'type'          => 'text',
                'description'   => /*T*/'Enter number in range 0-6 (0 is Sunday) or a 3 letter shortcut (e.g. sun)'/*/T*/,
                'value'         => '*',
            ),
        );

        return $variables;
    }

    function execute()
    {
	if (!isset($this->configuration['modules']['support']['installedVersion'])) {
		die('Sorry!To perform this action, you need to install support module.');
	}
        require_once 'newedge/classes/NE_MailGateway.php';
        require_once 'modules/support/models/TicketNotifications.php';
        $mailGateway = new NE_MailGateway();
        $messages = array();
        $numTicketsClosed = 0;

        if($this->settings->get('plugin_autoclose_Pre-Notify Customer')){
            $autocloseCondition = 'AND autoclose=1';
        } else {
            $autocloseCondition = '';
        }

        $sql = "SELECT * FROM `troubleticket` WHERE `status`='3' $autocloseCondition AND `lastlog_datetime` <= DATE_SUB( NOW() , INTERVAL ? DAY )";
        $result = $this->db->query($sql, $this->settings->get('plugin_autoclose_Days to trigger autoclose'));
        while ($row = $result->fetch()) {
            $ticket = new Ticket($row['id']);             
            $ticket->setStatus(-1);
            $ticket->SetLastLogDateTime(date('Y-m-d H-i-s'));
            $ticket->save();
            $userid = $ticket->getUserID();
            $user = new User($userid);
            $message = $user->getFullName().",\r\n\r\n".$this->settings->get('plugin_autoclose_Ticket Message')."\r\n\r\n".$this->settings->get('Company Name');
            $logSql = "INSERT INTO troubleticket_log (troubleticketid, message, userid, mydatetime, logaction) VALUES(?, ?, ?, NOW(), '2')";
            $this->db->query($logSql, $row['id'], $message, $ticket->getAssignedToId());
            if ($this->settings->get('plugin_autoclose_Notify Customer')) {
                $mailGateway->mailMessage(  $message,
                                            $this->settings->get('Support E-mail'),
                                            $this->settings->get('Support E-mail'),
                                            $userid,
                                            '',
                                            "[".$this->settings->get('Ticket Number Prefix')."-".$row['id']."] ".$this->user->lang("Support ticket has been closed"),
                                            3,
                                            0,
                                            'notifications',
                                            '',
                                            '',
                                            MAILGATEWAY_CONTENTTYPE_PLAINTEXT);
            }
            $numTicketsClosed++;
        }
        array_unshift($messages, $this->user->lang('%s ticket(s) closed', $numTicketsClosed));
        
        $numNotified=0;
        if($this->settings->get('plugin_autoclose_Pre-Notify Customer')){
            $sql = "SELECT * FROM `troubleticket` WHERE `status`='3' AND autoclose='0' AND `lastlog_datetime` <= DATE_SUB( NOW() , INTERVAL ? DAY )";
            $result = $this->db->query($sql, $this->settings->get('plugin_autoclose_Days to trigger Pre-Notify autoclose'));
            while ($row = $result->fetch()) {
                $ticket = new Ticket($row['id']);
                $ticketNotifications= new TicketNotifications();
                $ticketNotifications->PreNotifyAutoClose($ticket);
                $ticket->setAutoClose(1);
                $ticket->save();
                $numNotified++;
            }
        }
        array_unshift($messages, $this->user->lang('%s ticket(s) notified', $numNotified));
        return $messages;
    }

    function output()
    {
	if (!isset($this->configuration['modules']['support']['installedVersion'])) {
	        return "";
	//	$this->tpl->parse('output', 'autoclose_table');
	//        return $this->tpl->fetch('output');
	}
        $this->tpl->define(array('autoclose_table' => 'views/admin/autoclose_table.tpl'));
        $this->tpl->define_dynamic('autoclose', 'autoclose_table');
        $rowclass="odd";
        //Will be Notify
        $query = "SELECT * FROM `troubleticket` WHERE `status`='3' AND autoclose='0' AND `lastlog_datetime` <= DATE_SUB( NOW() , INTERVAL ? DAY )";
        $result = $this->db->query($query, $this->settings->get('plugin_autoclose_Days to trigger Pre-Notify autoclose'));
        $queueEmpty = true;
        while ($row = $result->fetch()) {
            $user = new User($row['userid']);

            $this->tpl->setkey(array(
                'trClass'                => $rowclass,
                'notify_customer'     => $user->getFullName(),
                'notify_customerid'   => $user->getId(),
                'notify_ticket'       => $row['id'],
                'notify_subject'      => $row['subject'],
            ));

            $queueEmpty = false;

            //alternate row color
            if ($rowclass=="odd") $rowclass="even";
            else $rowclass="odd";

            $this->tpl->subst('trash', '.notify');
        }

        if ($queueEmpty) {
            $this->tpl->setkey('NOTY_NOTICKETS', "<tr><td colspan=\"5\" align=\"center\" style=\"font-style:italic\">".$this->user->lang('There are no tickets to notify close')."</td></tr>");
        } else {
            $this->tpl->setkey('NOTY_NOTICKETS', '');
        }
        
        //Will be Closed
        $query = "SELECT * FROM `troubleticket` WHERE `status`='3' AND autoclose='1' AND `lastlog_datetime` <= DATE_SUB( NOW() , INTERVAL ? DAY )";
        $result = $this->db->query($query, $this->settings->get('plugin_autoclose_Days to trigger autoclose'));
        $queueEmpty = true;
        while ($row = $result->fetch()) {
            $user = new User($row['userid']);

            $this->tpl->setkey(array(
                'trClass'                => $rowclass,
                'autoclose_customer'     => $user->getFullName(),
                'autoclose_customerid'   => $user->getId(),
                'autoclose_ticket'       => $row['id'],
                'autoclose_subject'      => $row['subject'],
            ));

            $queueEmpty = false;

            //alternate row color
            if ($rowclass=="odd") $rowclass="even";
            else $rowclass="odd";

            $this->tpl->subst('trash', '.autoclose');
        }

        if ($queueEmpty) {
            $this->tpl->setkey('NOTICKETS', "<tr><td colspan=\"5\" align=\"center\" style=\"font-style:italic\">".$this->user->lang('There are no tickets to be closed')."</td></tr>");
        } else {
            $this->tpl->setkey('NOTICKETS', '');
        }

        $this->tpl->parse('output', 'autoclose_table');

        return $this->tpl->fetch('output');
    }

    function dashboard()
    {
        $query = "SELECT COUNT(*) AS tickets FROM `troubleticket` WHERE `status`='3' AND `lastlog_datetime` <= DATE_SUB( NOW() , INTERVAL ? DAY )";
        $result = $this->db->query($query, $this->settings->get('plugin_autoclose_Days to trigger autoclose'));
        $row = $result->fetch();
        if (!$row) {
            $row['tickets'] = 0;
        }

        return $this->user->lang('Number of tickets pending close: %d', $row['tickets']);
    }
}

?>
