<?php

require_once 'common/mailfunctions.php';
require_once 'classes/troubleticket.php';
require_once 'classes/user.php';

function plugin_autoclose_variables()
{
    $variables = array(
        'Plugin Name'   => array(
            'type'          => 'hidden',
            'description'   => '',
            'value'         => 'Ticket Auto Close',
        ),
        'Enabled'       => array(
            'type'          => 'yesno',
            'description'   => 'When enabled, tickets remaining unresponded to by customers for x amount of days will automatically be closed.',
            'value'         => '0',
        ),
        'Days to trigger autoclose'       => array(
            'type'          => 'text',
            'description'   => 'Enter number of days to wait before autoclosing a ticket that is in the waiting on customer status.',
            'value'         => '3',
        ),
        'Ticket Message'       => array(
            'type'          => 'text',
            'description'   => '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.',
            'value'         => 'Your ticket has been closed due to inactivity.  If this issue has not been resolved please reopen this ticket.',
        ),
        'Notify Customer'       => array(
            'type'          => 'yesno',
            'description'   => 'When enabled the customer will be notified when a ticket is closed.',
            'value'         => '1',
        ),
        'Run schedule - Minute'  => array(
            'type'          => 'text',
            'description'   => 'Enter number, range, list or steps',
            'value'         => '30',
            'helpid'        => '8',
        ),
        'Run schedule - Hour'  => array(
            'type'          => 'text',
            'description'   => 'Enter number, range, list or steps',
            'value'         => '*',
        ),
        'Run schedule - Day'  => array(
            'type'          => 'text',
            'description'   => 'Enter number, range, list or steps',
            'value'         => '*',
        ),
        'Run schedule - Month'  => array(
            'type'          => 'text',
            'description'   => 'Enter number, range, list or steps',
            'value'         => '*',
        ),
        'Run schedule - Day of the week'  => array(
            'type'          => 'text',
            'description'   => 'Enter number in range 0-7 (0 is Sunday) or a 3 letter shortcut (e.g. sun)',
            'value'         => '*',
        ),
    );

    return $variables;
}

function plugin_autoclose_execute()
{
    global $gSettingsArray;
    $messages = array();
    $numTicketsClosed = 0;
    $sql = "SELECT * FROM `troubleticket` WHERE `status`='3' AND `lastlog_datetime` <= DATE_SUB( NOW() , INTERVAL ? DAY )";
    $result = $GLOBALS['db']->query($sql, $gSettingsArray['plugin_autoclose_Days to trigger autoclose']);
    while ($row = $result->fetch()) {
        $ticket = new TroubleTicket($row['id']);
        $ticket->setStatus(-1);
        $ticket->SetLastLogDateTime(date('Y-m-d H-i-s'));
        $ticket->update();
        $userid = $ticket->getUserID();
        $user =& new User($userid);
        $user->PopulateCustomFields();
        $message = $user->getFullName().",\r\n\r\n".$gSettingsArray['plugin_autoclose_Ticket Message']."\r\n\r\n".$gSettingsArray['Company Name'];
        $logSql = "INSERT INTO troubleticket_log VALUES ('', ?, ?, ?, NOW(), '2')";
        $GLOBALS['db']->query($logSql, $row['id'], $message, $ticket->GetAssignedToID());
        if ($gSettingsArray['plugin_autoclose_Notify Customer']) {
            mailMessage($message,$gSettingsArray['Support E-mail'],$gSettingsArray['Support E-mail'],$userid,$bcc,"[ce-".$row['id']."] ".lang("Support ticket has been closed"),3,0);
        }
        $numTicketsClosed++;
    }
    array_unshift($messages, lang('%s ticket(s) closed', $numTicketsClosed));
    return $messages;
}

function plugin_autoclose_output()
{
    global $tpl;
    global $gSettingsArray;

    $tpl->define(array('autoclose_table' => 'views/admin/autoclose_table.tpl'));
    $tpl->define_dynamic('autoclose', 'autoclose_table');
    $rowclass="odd";

    $query = "SELECT * FROM `troubleticket` WHERE `status`='3' AND `lastlog_datetime` <= DATE_SUB( NOW() , INTERVAL ? DAY )";
    $result = $GLOBALS['db']->query($query, $gSettingsArray['plugin_autoclose_Days to trigger autoclose']);
    $queueEmpty = true;
    while ($row = $result->fetch()) {
        $user =& new User($row['userid']);
        $user->populateCustomFields();

        $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";

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

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

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

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

function plugin_autoclose_dashboard()
{
    global $gSettingsArray;
    
    $query = "SELECT COUNT(*) as tickets FROM `troubleticket` WHERE `status`='3' AND `lastlog_datetime` <= DATE_SUB( NOW() , INTERVAL ? DAY )";
    $result = $GLOBALS['db']->query($query, $gSettingsArray['plugin_autoclose_Days to trigger autoclose']);
    $row = $result->fetch();
    if (!$row) {
        $row['tickets'] = 0;
    }
    return lang('Number of tickets pending close: %d', $row['tickets']);
}

?>
