<?php

require_once 'common/mailfunctions.php';
require_once 'classes/user.php';
require_once 'classes/domain.php';
require_once 'classes/PackageType.php';
require_once 'classes/server.php';
require_once 'classes/class.PluginInterface.php';
/**
 * All plugin variables/settings to be used for this particular service.
 *
 * @return array The plugin variables.
 */
function plugin_order_variables()
{
    $variables = array(
        'Plugin Name'   => array(
            'type'          => 'hidden',
            'description'   => '',
            'value'         => 'Order Processor',
        ),
        'Enabled'       => array(
            'type'          => 'yesno',
            'description'   => 'When enabled, new orders will be activated and processed when this service is run.  Please note that manually added packages will not be processed.',
            'value'         => '0',
        ),
        'E-mail Notifications'       => array(
            'type'          => 'text',
            'description'   => 'When a domain requires manual registration or transfer, or an account requires manual setup you will be notified at this E-mail address.',
            'value'         => '',
        ),
        '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;
}


/**
 * 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_order_execute()
{
    global $gSettingsArray;
    $messages = array();
    $numOrdersProcessed = 0;
    // We'll select all domains that are pending and weren't manually added
    $query = "SELECT id FROM domains WHERE status = 0 AND signup = 1";
    $result = $GLOBALS['db']->query($query);
    while ($row = $result->fetch()) {
        $useRegistrarPlugin = false;
        $useServerPlugin = false;
        $domain = new Domain($row['id']);
        $user =& new User($domain->getCustomerID());
        $user->populateCustomFields();
        $packageType = new PackageType($domain->GetPromotionID());
        $server = new Server($domain->GetServerID());
        
        // Activate the user if pending
        if ($user->GetStatus() == 0 && sizeof($user->getUnpaidInvoices()) == 0) {
            $user->setStatus(1);
            $user->save();
        }
        // Make sure that the domain is paid and user is active and the plan has domain options
        if($domain->isPaid() && $user->GetStatus() == 1) {
            if ($server->GetPluginName() != "") {
                // determine whether to register the domain
                if ($packageType->isRegDomain() && !$packageType->isSub()) {
                    if ($domain->getRegistrationRequest() == 0) {
                        $pluginsRegistrar = new PluginInterface(dirname(__FILE__)."/../../registrars",array('variables','register_domain'));
                        $pluginNames = $pluginsRegistrar->getFoundPluginNames();
                        foreach ($pluginNames as $pluginName) {
                            if (@$gSettingsArray["plugin_{$pluginName}_Use ".ucfirst($pluginName)." to check and register domains"]) {
                                $useRegistrarPlugin = true;
                            }
                        }
                        if ($useRegistrarPlugin == false) {
                            $strEmailMessage = "Dear Support Member,\r\n\r\nCustomer ".$user->getFullName()
                        ." has requested the registration of the domain, ".htmlspecialchars($domain->getDomainName())
                        .". There is no registrar plugin setup to process this registration.  Please process the registration as soon as possible.\r\n\r\nThank You";
                        MailMessageEmail($strEmailMessage,$gSettingsArray['Support E-mail'],$gSettingsArray['Support E-mail'],$gSettingsArray['plugin_order_E-mail Notifications'],$bcc,lang("Manual Intervention Required:")." ".$user->getFullName(),3,0);
                        }
                        // Check if there is a valid registrar plugin
                        // if not notify admin that a manual registration needs to be done
                    } elseif ($domain->getRegistrationRequest() == 1) { 
                        $strEmailMessage = "Dear Support Member,\r\n\r\nCustomer ".$user->getFullName()
                        ." has requested a manual transfer of the domain, ".htmlspecialchars($domain->getDomainName())
                        .". Please process the transfer as soon as possible.\r\n\r\nThank You";
                        MailMessageEmail($strEmailMessage,$gSettingsArray['Support E-mail'],$gSettingsArray['Support E-mail'],$gSettingsArray['plugin_order_E-mail Notifications'],$bcc,lang("Manual Intervention Required:")." ".$user->getFullName(),3,0);
                    }
                }
                $numOrdersProcessed++;
                $domain->activate(true,true,$useRegistrarPlugin,true);
            } else {
                $strEmailMessage = "Dear Support Member,\r\n\r\nCustomer ".$user->getFullName()
                    ." has ordered a package that requires manual processing. Please process the order as soon as possible.\r\n\r\nThank You";
                MailMessageEmail($strEmailMessage,$gSettingsArray['Support E-mail'],$gSettingsArray['Support E-mail'],$gSettingsArray['plugin_order_E-mail Notifications'],$bcc,lang("Manual Intervention Required:")." ".$user->getFullName(),3,0);
                // Don't want to send notification more than once.
                $sql = "UPDATE `domains` SET `signup` = '2' WHERE `id` = ?";
                $GLOBALS['db']->query($sql, $row['id']);
            }
        }
    }
    array_unshift($messages, lang('%s order(s) processed', $numOrdersProcessed));
    return $messages;
}

/**
 * The output shown in the admin->plugins->services page.
 * Shows a list of paid customer orders pending activation
 *
 * @return unknown
 */
function plugin_order_output()
{
    global $tpl;

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

    $query = "SELECT id FROM domains WHERE status = 0 AND signup > 0";
    $result = $GLOBALS['db']->query($query);
    $queueEmpty = true;
    while ($row = $result->fetch()) {
        $domain = new Domain($row['id']);
        $user =& new User($domain->getCustomerID());
        $server = new Server($domain->GetServerID());
        if ($server->GetPluginName() != "") {
            $auto = lang("No");
        } else {
            $auto = "<span style=\"color:red\"><b>".lang('Yes')."</b></span>";
        }
        if ($domain->isPaid() && ($user->GetStatus() == 0 || $user->getStatus() == 1) && sizeof($user->getUnpaidInvoices()) == 0) {
            $user->populateCustomFields();
            $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,
                'order_customer'     => $user->getLastName().", ".$user->getFirstName(),
                'order_packagetype'  => $promoName,
                'order_package'      => $planName,
                'order_domain'       => htmlspecialchars($domain->GetDomainName()),
                'order_manual'       => $auto,
            ));

            $queueEmpty = false;

            //alternate row color
            if ($rowclass=="odd") $rowclass="even";
            else $rowclass="odd";

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

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

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

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

function plugin_order_dashboard()
{    
    $query = "SELECT COUNT(id) as orders FROM domains WHERE status = 0 AND signup = 1";
    $result = $GLOBALS['db']->query($query);
    $row = $result->fetch();
    if (!$row) {
        $row['orders'] = 0;
    }
    
    $message = lang('Number of orders pending auto activation: %d', $row['orders']);
    $message .= "<br>";
    
    $query = "SELECT COUNT(id) as orders FROM domains WHERE status = 0 AND signup = 2";
    $result = $GLOBALS['db']->query($query);
    $row = $result->fetch();
    if (!$row) {
        $row['orders'] = 0;
    }
    
    $message .= lang('Number of orders requiring manual setup: %d', $row['orders']);
    
    return $message;
}

?>
