<?php

require_once 'common/mailfunctions.php';
require_once 'classes/user.php';
require_once 'classes/domain.php';
require_once 'classes/invoice.php';
require_once 'classes/invoiceentry.php';

/**
 * All plugin variables/settings to be used for this particular service.
 *
 * @return array The plugin variables.
 */
function plugin_autosuspend_variables()
{
    $variables = array(
        'Plugin Name'   => array(
            'type'          => 'hidden',
            'description'   => '',
            'value'         => 'Auto Suspender',
        ),
        'Enabled'       => array(
            'type'          => 'yesno',
            'description'   => 'When enabled, overdue packages will be suspended when this service is run.',
            'value'         => '0',
        ),
        'E-mail Notifications'       => array(
            'type'          => 'text',
            'description'   => '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.',
            'value'         => '',
        ),
        'Days Overdue Before Suspending'    => array(
            'type'          => 'text',
            'description'   => 'Only suspend packages that are this many days overdue.',
            'value'         => '7',
        ),
        'Run schedule - Minute'  => array(
            'type'          => 'text',
            'description'   => 'Enter number, range, list or steps',
            'value'         => '0',
            'helpid'        => '8',
        ),
        'Run schedule - Hour'  => array(
            'type'          => 'text',
            'description'   => 'Enter number, range, list or steps',
            'value'         => '0',
        ),
        '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'         => '*',
        ),
        'Notified Package List' => array(
            'type'          => 'hidden',
            'description'   => 'Used to store package IDs of manually suspended packages whose E-mail has already been sent.',
            '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 Error_CE an error if one occurs
 */
function plugin_autosuspend_execute()
{
    global $gSettingsArray;

    $messages = array();
    $autoSuspend = array();
    $manualSuspend = array();

    
    $preEmailed = unserialize($gSettingsArray['plugin_autosuspend_Notified Package List']);
    $newPreEmailed = array();

    $overdueArray = _plugin_autosuspend_getOverduePackages();

    for ($i = 0; $i < sizeof($overdueArray['package']); $i++) {
        $domain = new Domain($overdueArray['package'][$i]);
        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 = lang("Autosuspend Service Summary")."\n\n";
    if (sizeof($autoSuspend) > 0) {
        $sendSummary = true;
        $body .= lang("Suspended").":\n\n";
        foreach ($autoSuspend as $id) {
            $domain = new Domain($id);
            $user =& new User($domain->getCustomerID());
            $user->populateCustomFields();
            $body .= $user->getFullName()." => ".$domain->getReference(true)."\n";
        }
        $body .= "\n";
    }
    if (sizeof($manualSuspend) > 0) {
        $sendSummary = true;
        $body .= lang("Requires Manual Suspension").":\n\n";
        foreach ($manualSuspend as $id) {
            $domain = new Domain($id);
            $user =& new User($domain->getCustomerID());
            $user->populateCustomFields();
            $body .= $user->getFullName()." => ".$domain->getReference(true)."\n";
        }
    }

    if ($sendSummary && $gSettingsArray['plugin_autosuspend_E-mail Notifications'] != "") {
        MailMessageEmail($body,$gSettingsArray['Support E-mail'],$gSettingsArray['Support E-mail'],$gSettingsArray['plugin_autosuspend_E-mail Notifications'],false,lang("AutoSuspend Service Summary"),3,0);
    }

    // Store the new notified list
    $query = "UPDATE setting SET value=? WHERE name='plugin_autosuspend_Notified Package List'";
    $result = $GLOBALS['db']->query($query, serialize($newPreEmailed));

    array_unshift($messages, 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 plugin_autosuspend_output()
{
    global $tpl;

    $tpl->define(array('suspendqueue_table' => 'views/admin/suspendqueue_table.tpl'));
    $tpl->define_dynamic('suspend', 'suspendqueue_table');
    $rowclass="odd";
    $queueEmpty = true;

    $overdueArray = _plugin_autosuspend_getOverduePackages();

    for ($i = 0; $i < sizeof($overdueArray['package']); $i++) {
        $domain = new Domain($overdueArray['package'][$i]);
        $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 = $GLOBALS['db']->query($query, $domain->GetPlanID());
        list($planName,$promoName) = $pResult->fetch();
        $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";

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


    if ($queueEmpty) {
        $tpl->setkey('NOPACKAGES', "<tr><td colspan=\"5\" align=\"center\" style=\"font-style:italic\">".lang('The queue is empty')."</td></tr>");
    } else {
        $tpl->setkey('NOPACKAGES', '');
    }

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

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

}

function plugin_autosuspend_dashboard()
{
    $overdueArray = _plugin_autosuspend_getOverduePackages();

    $autoSuspend = 0;
    $manualSuspend = 0;

    for ($i = 0; $i < sizeof($overdueArray['package']); $i++) {
        $domain = new Domain($overdueArray['package'][$i]);
        if ($domain->HasPlugin()) {
            $autoSuspend++;
        } else {
            $manualSuspend++;
        }
    }

    $message = lang('Number of packages pending auto suspension: %d', $autoSuspend);
    $message .= "<br>";

    $message .= lang('Number of packages requiring manual suspension: %d', $manualSuspend);

    return $message;
}

function _plugin_autosuspend_getOverduePackages() {
    global $gSettingsArray;

    $query = "SELECT id FROM invoice WHERE paid=0 AND billdate < DATE_SUB( NOW() , INTERVAL ? DAY ) ORDER BY billdate ASC";
    $result = $GLOBALS['db']->query($query, @$gSettingsArray['plugin_autosuspend_Days Overdue Before Suspending']);
    $overdueArray = array(
                        "package"  => array(),
                        "duedate"  => array(),
                        "customer" => array(),
                        "cduedate" => array()
                        );
    while ($row = $result->fetch()) {
        $invoice = new Invoice($row['id']);
        $user =& new User($invoice->getUserID());
        if ($user->getStatus() != 1) continue;
        foreach ($invoice->getInvoiceEntriesArray() as $invoiceEntryId) {
            $invoiceEntry = new InvoiceEntry($invoiceEntryId);
            if ($invoiceEntry->isPackage() && $invoiceEntry->AppliesTo() != 0) {
                // Found an overdue package, add it to the list
                if (!in_array($invoiceEntry->AppliesTo(), $overdueArray['package'])) {
                    $package = new Domain($invoiceEntry->AppliesTo());
                    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 = $GLOBALS['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;
}

?>
