<?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
{
    protected $featureSet = 'support';

    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'          => 'smallTextarea',
                'description'   => /*T*/'Enter the message you would like entered into the ticket when it is closed.<br>Template Tags: [CLIENTNAME], [TICKETNUMBER], [TICKETSUBJECT], [TICKETFIRSTLOG], [COMPANYNAME]'/*/T*/,
                'value'         => "ATTN: [CLIENTNAME],\r\n\r\nYour Support Ticket #[TICKETNUMBER] with subject \"[TICKETSUBJECT]\" has been closed due to inactivity.\r\nIf this issue has not been resolved please reopen this ticket.\r\n\r\nThank you,\r\n[COMPANYNAME]",
            ),
            /*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 ) AND company_id=?";
        $result = $this->db->query($sql, $this->settings->get('plugin_autoclose_Days to trigger autoclose'), NE_Registry::getCompany()->getId());
        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 = $this->settings->get('plugin_autoclose_Ticket Message');
            $message = str_replace("[CLIENTNAME]", $user->getFullName(), $message);
            $message = str_replace("[TICKETNUMBER]", $ticket->getIdLabel(), $message);
            $message = str_replace("[TICKETSUBJECT]", $ticket->getSubject(), $message);
            $message = str_replace("[TICKETFIRSTLOG]", $ticket->getFirstLog(), $message);
            $message = str_replace(array("[COMPANYNAME]","%5BCOMPANYNAME%5D"), $this->settings->get("Company Name"), $message);
            
            $logSql = "INSERT INTO troubleticket_log (company_id, troubleticketid, message, userid, mydatetime, logaction) VALUES(?, ?, ?, ?, NOW(), '2')";
            $this->db->query($logSql, NE_Registry::getCompany()->getId(), $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,
                                            '',
                                            "[".$ticket->getIdLabel()."] ".$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 ) AND company_id=?";
            $result = $this->db->query($sql, $this->settings->get('plugin_autoclose_Days to trigger Pre-Notify autoclose'), NE_Registry::getCompany()->getId());
            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() { }

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

        return $this->user->lang('Number of tickets pending close: %d', $row['tickets']);
	}
	
    function pendingItems()
    {
		// Notify
        $query = "SELECT * FROM `troubleticket` WHERE `status`='3' AND autoclose='0' AND `lastlog_datetime` <= DATE_SUB( NOW() , INTERVAL ? DAY ) AND company_id=?";
        $result = $this->db->query($query, $this->settings->get('plugin_autoclose_Days to trigger Pre-Notify autoclose'), NE_Registry::getCompany()->getId());
        $queueEmpty = true;
		$tickets = array();
        while ($row = $result->fetch()) {
            $user = new User($row['userid']);
			
			$group = $user->getCustomerGroups();
			$color = '';
			if(count($group)>0){
				$group=$group[0];
				if($group->getGroupColor() != NULL) {
					$color = $group->getGroupColor();
				}
			}

            $tmp = array (
                'customer'     => $user->getFullName(),
                'customerid'   => $user->getId(),
                'ticketid'       => $row['id'],
				'status'		=> 'notifying',
				'subject' 	=> $row['subject'],
				'userstatus' => $user->getStatus(),
				'isguest'	=> $user->isGuest(),
				'usergroupcolor'	=> $color
            );  
			$tickets[] = $tmp;
        }

		// Closed
		$query = "SELECT * FROM `troubleticket` WHERE `status`='3' AND autoclose='1' AND `lastlog_datetime` <= DATE_SUB( NOW() , INTERVAL ? DAY ) AND company_id=?";
        $result = $this->db->query($query, $this->settings->get('plugin_autoclose_Days to trigger autoclose'), NE_Registry::getCompany()->getId());
		while ($row = $result->fetch()) {
            $user = new User($row['userid']);

			$group = $user->getCustomerGroups();
			$color = '';
			if(count($group)>0){
				$group=$group[0];
				if($group->getGroupColor() != NULL) {
					$color = $group->getGroupColor();
				}
			}

            $tmp = array (
                'customer'     => $user->getFullName(),
                'customerid'   => $user->getId(),
                'ticketid'       => $row['id'],
				'status'		=> 'closing',
				'subject' 	=> $row['subject'],
				'userstatus' => $user->getStatus(),
				'isguest'	=> $user->isGuest(),
				'usergroupcolor'	=> $color
            );
			$tickets[] = $tmp;
        }
		
		$returnArray = array();
		$returnArray["totalcount"] = count($tickets);
		$returnArray["data"] = $tickets;
		return $returnArray;
    }
}
?>
