<?php

require_once 'classes/MailGateway.php';
require_once 'classes/user.php';
require_once 'classes/domain.php';
require_once 'classes/invoice.php';
require_once 'classes/invoiceentry.php';
require_once 'classes/ServicePlugin.php';

/**
 * All plugin variables/settings to be used for this particular service.
 *
 * @return array The plugin variables.
 */

/**
* @package Plugins
*/
class PluginAutosuspend extends ServicePlugin
{
    function getVariables()
    {
        $variables = array(
            /*T*/'Plugin Name'/*/T*/   => array(
                'type'          => 'hidden',
                'description'   => /*T*/''/*/T*/,
                'value'         => /*T*/'Auto Suspender'/*/T*/,
            ),
            /*T*/'Enabled'/*/T*/       => array(
                'type'          => 'yesno',
                'description'   => /*T*/'When enabled, overdue packages will be suspended when this service is run.'/*/T*/,
                'value'         => '0',
            ),
            /*T*/'E-mail Notifications'/*/T*/       => array(
                'type'          => 'text',
                'description'   => /*T*/'When a package requires manual suspension you will be notified at this E-mail address.  If packages are suspended when this service is run, a summary E-mail will be sent to this address.'/*/T*/,
                'value'         => '',
            ),
            /*T*/'Days Overdue Before Suspending'/*/T*/    => array(
                'type'          => 'text',
                'description'   => /*T*/'Only suspend packages that are this many days overdue.'/*/T*/,
                'value'         => '7',
            ),
            /*T*/'Run schedule - Minute'/*/T*/  => array(
                'type'          => 'text',
                'description'   => /*T*/'Enter number, range, list or steps'/*/T*/,
                'value'         => '0',
                'helpid'        => '8',
            ),
            /*T*/'Run schedule - Hour'/*/T*/  => array(
                'type'          => 'text',
                'description'   => /*T*/'Enter number, range, list or steps'/*/T*/,
                'value'         => '0',
            ),
            /*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-7 (0 is Sunday) or a 3 letter shortcut (e.g. sun)'/*/T*/,
                'value'         => '*',
            ),
            /*T*/'Notified Package List'/*/T*/ => array(
                'type'          => 'hidden',
                'description'   => /*T*/'Used to store package IDs of manually suspended packages whose E-mail has already been sent.'/*/T*/,
                'value'         => ''
            )
        );
    
        return $variables;
    }
    
    
    /**
     * Execute the order processor.  We'll activate any pending users an then their packages
     * if they are paid and used the signup form.  Manually added packages will be left
     * untouched.
     *
     * @return NE_Error an error if one occurs
     */
    function execute()
    {
        $messages = array();
        $autoSuspend = array();
        $manualSuspend = array();
    
        $preEmailed = $this->settings->get('plugin_autosuspend_Notified Package List');
        $newPreEmailed = array();
    
        $overdueArray = $this->_getOverduePackages();
    
        for ($i = 0; $i < sizeof($overdueArray['package']); $i++) {
            $domain = new Domain($overdueArray['package'][$i], $this->user);
            if ($domain->HasPlugin()) {
                $domain->suspend(true, true);
                $autoSuspend[] = $domain->getID();
            } elseif (is_array($preEmailed) && !in_array($domain->getID(), $preEmailed)) {
                $manualSuspend[] = $domain->getID();
                $newPreEmailed[] = $domain->getID();
            } else {
                $newPreEmailed[] = $domain->getID();
            }
        }
        $sendSummary = false;
        $body = $this->user->lang("Autosuspend Service Summary")."\n\n";
        if (sizeof($autoSuspend) > 0) {
            $sendSummary = true;
            $body .= $this->user->lang("Suspended").":\n\n";
            foreach ($autoSuspend as $id) {
                $domain = new Domain($id, $this->user);
                $user =& new User($domain->getCustomerID());
                $user->populateCustomFields();
                $body .= $user->getFullName()." => ".$domain->getReference(true)."\n";
            }
            $body .= "\n";
        }
        if (sizeof($manualSuspend) > 0) {
            $sendSummary = true;
            $body .= $this->user->lang("Requires Manual Suspension").":\n\n";
            foreach ($manualSuspend as $id) {
                $domain = new Domain($id, $this->user);
                $user =& new User($domain->getCustomerID());
                $user->populateCustomFields();
                $body .= $user->getFullName()." => ".$domain->getReference(true)."\n";
            }
        }
    
        if ($sendSummary && $this->settings->get('plugin_autosuspend_E-mail Notifications') != "") {
            $mailGateway = new MailGateway();
            $mailGateway->mailMessageEmail( $body,
                                            $this->settings->get('Support E-mail'),
                                            $this->settings->get('Support E-mail'),
                                            $this->settings->get('plugin_autosuspend_E-mail Notifications'),
                                            false,
                                            $this->user->lang("AutoSuspend Service Summary"));
        }
    
        // Store the new notified list
        $query = "UPDATE setting SET value=? WHERE name='plugin_autosuspend_Notified Package List'";
        $result = $this->db->query($query, serialize($newPreEmailed));
    
        array_unshift($messages, $this->user->lang('%s package(s) suspended', sizeof($autoSuspend)));
        return $messages;
    }
    
    /**
     * The output shown in the admin->plugins->services page.
     * Shows a list of paid customer orders pending activation
     *
     * @return unknown
     */
    function output()
    {
        $this->tpl->define(array('suspendqueue_table' => 'views/admin/suspendqueue_table.tpl'));
        $this->tpl->define_dynamic('suspend', 'suspendqueue_table');
        $rowclass="odd";
        $queueEmpty = true;
    
        $overdueArray = $this->_getOverduePackages();
    
        for ($i = 0; $i < sizeof($overdueArray['package']); $i++) {
            $domain = new Domain($overdueArray['package'][$i], $this->user);
            $user =& new User($domain->getCustomerID());
            $user->populateCustomFields();
            if ($domain->HasPlugin()) {
                $auto = "No";
            } else {
                $auto = "<span style=\"color:red\"><b>Yes</b></span>";
            }
            $query = "SELECT p.planname, pr.name FROM package p, promotion pr WHERE p.id = ? AND p.planid = pr.id";
            $pResult = $this->db->query($query, $domain->GetPlanID());
            list($planName,$promoName) = $pResult->fetch();
            $this->tpl->setkey(array(
                'trClass'                  => $rowclass,
                'autosuspend_customer'     => $user->getLastName().", ".$user->getFirstName(),
                'autosuspend_customerid'   => $user->getId(),
                'autosuspend_packagetype'  => $promoName,
                'autosuspend_package'      => $planName,
                'autosuspend_domainid'     => $domain->getID(),
                'autosuspend_domain'       => $domain->getReference(true),
                'autosuspend_date'         => $overdueArray['duedate'][$i],
                'autosuspend_manual'       => $auto,
            ));
    
            $queueEmpty = false;
    
            //alternate row color
            if ($rowclass=="odd") $rowclass="even";
            else $rowclass="odd";
    
            $this->tpl->subst('trash', '.suspend');
        }
    
    
        if ($queueEmpty) {
            $this->tpl->setkey('NOPACKAGES', "<tr><td colspan=\"5\" align=\"center\" style=\"font-style:italic\">".$this->user->lang('The queue is empty')."</td></tr>");
        } else {
            $this->tpl->setkey('NOPACKAGES', '');
        }
    
        $this->tpl->parse('output', 'suspendqueue_table');
    
        return $this->tpl->fetch('output');
    
    }
    
    function dashboard()
    {
        $overdueArray = $this->_getOverduePackages();
    
        $autoSuspend = 0;
        $manualSuspend = 0;
    
        for ($i = 0; $i < sizeof($overdueArray['package']); $i++) {
            $domain = new Domain($overdueArray['package'][$i], $this->user);
            if ($domain->HasPlugin()) {
                $autoSuspend++;
            } else {
                $manualSuspend++;
            }
        }
    
        $message = $this->user->lang('Number of packages pending auto suspension: %d', $autoSuspend);
        $message .= "<br>";
    
        $message .= $this->user->lang('Number of packages requiring manual suspension: %d', $manualSuspend);
    
        return $message;
    }
    
    function _getOverduePackages() {
        $query = "SELECT id FROM invoice WHERE paid=0 AND billdate < DATE_SUB( NOW() , INTERVAL ? DAY ) ORDER BY billdate ASC";
        $result = $this->db->query($query, @$this->settings->get('plugin_autosuspend_Days Overdue Before Suspending'));
        $overdueArray = array(
                            "package"  => array(),
                            "duedate"  => array(),
                            "customer" => array(),
                            "cduedate" => array()
                            );
        while ($row = $result->fetch()) {
            $invoice = new Invoice($this->user, $row['id']);
            $user =& new User($invoice->getUserID());
            if ($user->getStatus() != 1) continue;
            foreach ($invoice->getInvoiceEntries() as $invoiceEntry) {
                if ($invoiceEntry->AppliesTo() != 0) {
                    // Found an overdue package, add it to the list
                    if (!in_array($invoiceEntry->AppliesTo(), $overdueArray['package'])) {
                        $package = new Domain($invoiceEntry->AppliesTo(), $this->user);
                        if ($package->getStatus() != 1) continue;
                        $overdueArray['package'][] = $invoiceEntry->AppliesTo();
                        $overdueArray['duedate'][] = $invoice->getDate();
                    }
                } else {
                    // Found an overdue recurring fee that doesn't belong to a package.  Assume the entire client is overdue.
                    if (!in_array($invoiceEntry->GetCustomerID(), $overdueArray['customer'])) {
                        $overdueArray['customer'][] = $invoiceEntry->GetCustomerID();
                        $overdueArray['cduedate'][] = $invoice->getDate();
                    }
                }
            }
        }
        // Now we have all the overdue packages and clients.
        // We'll loop through the clients and all their packages to the list.
        for ($i = 0; $i < sizeof($overdueArray['customer']); $i++) {
            $query = "SELECT id FROM domains WHERE CustomerID=? AND status=1";
            $result = $this->db->query($query, $overdueArray['customer'][$i]);
            while ($row = $result->fetch()) {
                if (!in_array($row['id'], $overdueArray['package'])) {
                    $overdueArray['package'][] = $row['id'];
                    $overdueArray['duedate'][] = $overdueArray['cduedate'][$i];
                }
            }
        }
        unset($overdueArray['customer']);
        unset($overdueArray['cduedate']);
        return $overdueArray;
    }
}
?>
