<?php
require_once 'modules/admin/models/ServicePlugin.php';
require_once 'modules/admin/models/EscalationGateway.php';
require_once 'modules/support/models/TicketGateway.php';
require_once 'modules/support/models/Ticket_EventLog.php';

/**
* @package Plugins
*/
class PluginEscalation extends ServicePlugin
{
    var $ticketNotifications;

    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'   => '',
                'value'         => 'Ticket Escalation',
            ),
            /*T*/'Enabled'/*/T*/       => array(
                'type'          => $enabledType,
                'description'   => 'Checks if any tickets verify any escalation condition, and executes the apropiate actions on them',
                'value'         => '0',
            ),
            /*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.');
        }

	$eventLogs = array();
        $ticketGateway = new TicketGateway();
        $escalationGateway = new EscalationGateway();
        $escalations = $escalationGateway->getEscalations();
        $messages = array();
        while ($escalation = $escalations->fetch()) {
            $tickets = $ticketGateway->getTicketsForEscalation($escalation);
            while ($ticket = $tickets->fetch()) {
                $ticketsEscalated[] = $ticket->getId();
                if ($escalation->getNewPriority()) {
                    $ticket->setPriority($escalation->getNewPriority());
                }

                if ($escalation->getNewTag()) {
                    $ticket->setTag($escalation->getNewTag());
                }                
                
                if ($newDept = $escalation->getReassignDept()) {
                    require_once 'modules/support/models/Department.php';
                    $dep = new Department($newDept);

                    /*
                    if ($newStaff = $escalation->getReassignStaff()) {
                        $staff = new User($newStaff);
                    } elseif ($dep->getAssignToLead()) {
                        $staff = $dep->getLead();
                    } else {
                        $staff = null;
                    }*/

                    if ($newStaff = $escalation->getReassignStaff()) {
                        $staff = new User($newStaff);
                    } elseif ($dep->getAssignToMember()) {
                        $staff = $dep->getMember();
                    } else {
                        $staff = null;
                    }

                    $ticket->assign($dep, $staff);
                }

                if ($escalation->getOnlyApplyOnce()) {
                    $ticket->addEscalationRecord($escalation->getId());
                }

                foreach ($escalation->getTranscriptionDestinataries() as $email) {
                    $this->_sendTranscription($ticket, $escalation, $email);
                }

                $ticket->save();
                $ticket->notifyAssignation($this->user);
                $messages[] = $this->user->lang('Ticket #%s was escalated using the rule "%s"', $ticket->getId(), $escalation->getName());

                $eventLogs[] = Ticket_EventLog::newInstance($ticket->getUserId(),
                                                            $ticket->getId(),
                                                            TICKET_EVENTLOG_ESCALATED,
                                                            '-2');
                // TODO: send transcription
            }
        }

        if (!$messages) {
            return array($this->user->lang('No tickets were escalated'));
        }

        // Log the messages
        foreach ($eventLogs as $eventLog) {
            $this->logger->addEventLog($eventLog);
        }
        
        return $messages;
    }

    function _sendTranscription(&$ticket, &$escalation, $email)
    {
        if (!isset($this->ticketNotifications)) {
            require_once 'modules/support/models/TicketNotifications.php';
            $this->ticketNotifications = new TicketNotifications();
        }
	$dep = '';
        $this->ticketNotifications->sendTranscription(  $ticket,
                                                        $this->user,
                                                        $dep,
                                                        $this->user->lang('Ticket #%s has been escalated through the rule "%s"', $ticket->getId(), $escalation->getName()),
														$email);
    }
}

?>
