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


    /**
     * 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()
    {
        require_once 'newedge/classes/NE_PluginCollection.php';

        $messages = array();
        $numOrdersProcessed = 0;
        // We'll select all packages that allow automatic activation
        $query = "SELECT id FROM package WHERE automaticactivation = 1";
        $result = $this->db->query($query);
        while ($row = $result->fetch()) {
            $automaticactivation[$row['id']] = $row['id'];
        }
        // We'll select all domains that are pending and weren't manually added
        $query = "SELECT id, Plan "
                ."FROM domains "
                ."WHERE status = 0 "
                ."AND signup = 1 ";
        $result = $this->db->query($query);
        while ($row = $result->fetch()) {
            $useRegistrarPlugin = false;
            $useServerPlugin = false;
            $domain = new Domain($row['id'], $this->user);
            if ($domain->getCustomerID() == 0) continue; // prevents orphaned domains from creating many users
            $user = $domain->getUser();
            $packageType = new PackageType($domain->GetPromotionID());
            $server = new Server($domain->GetServerID());
            
            // Activate the user if pending
            if ($user->GetStatus() == 0 && sizeof($user->getUnpaidInvoices()) == 0 && sizeof($user->getPartiallyPaidInvoices()) == 0) {
                $user->setStatus(1);
                $user->save();
            }
            // Make sure that the domain is paid and user is active and the plan has domain options
            // Also, make sure that the plugin "Order Processor" is Enabled and thet the domain allows automatic activation,
            // or make sure that the plugin "Order Processor" is disabled, meaning this is a Manual Execution.
            if($domain->isPaid() && $user->GetStatus() == 1) {
                $mailGateway = new NE_MailGateway();
                if ($server->GetPluginName() != "" && (($this->settings->get('plugin_order_Enabled') && isset($automaticactivation[$row['Plan']])) || (!$this->settings->get('plugin_order_Enabled')))) {
                    // determine whether to register the domain
                    if ($packageType->isTypeDomain() && !$packageType->isSub()) {
                        if ($domain->getRegistrationRequest() == 0) {
                            $tld = '';
                            if (($position = strpos($domain->GetDomainName(), '.')) !== false) {
                                $tld = mb_substr($domain->GetDomainName(), $position + 1);
                            }
                            $query = "SELECT plugin FROM tld WHERE name = ?";
                            $result = $this->db->query($query, $tld);
                            list ($pluginName) = $result->fetch();
                            if ($pluginName != '') {
                                $useRegistrarPlugin = true;
                            }
                            if ($useRegistrarPlugin == false && $this->settings->get('plugin_order_E-mail Notifications') != '') {
                                $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";

                                $destinataries = explode("\r\n", $this->settings->get('plugin_order_E-mail Notifications'));
                                foreach ($destinataries as $destinatary) {
                                    $mailGateway->mailMessageEmail( $strEmailMessage,
                                                                    $this->settings->get('Support E-mail'),
                                                                    $this->settings->get('Support E-mail'),
                                                                    $destinatary,
                                                                    '',
                                                                    $this->user->lang("Manual Intervention Required:")." ".$user->getFullName());
                                }
                            }
                            // Check if there is a valid registrar plugin
                            // if not notify admin that a manual registration needs to be done
                        } elseif ($domain->getRegistrationRequest() == 1 && $this->settings->get('plugin_order_E-mail Notifications') != '') { 
                            $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";

                            $destinataries = explode("\r\n", $this->settings->get('plugin_order_E-mail Notifications'));
                            foreach ($destinataries as $destinatary) {
                                $mailGateway->mailMessageEmail( $strEmailMessage,
                                                                $this->settings->get('Support E-mail'),
                                                                $this->settings->get('Support E-mail'),
                                                                $destinatary,
                                                                '',
                                                                $this->user->lang("Manual Intervention Required:")." ".$user->getFullName());
                            }
                        }
                    }
                    $numOrdersProcessed++;
                    $view = null;
                    $domain->activate($view, 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";

                    $destinataries = explode("\r\n", $this->settings->get('plugin_order_E-mail Notifications'));
                    foreach ($destinataries as $destinatary) {
                        $mailGateway->mailMessageEmail( $strEmailMessage,
                                                        $this->settings->get('Support E-mail'),
                                                        $this->settings->get('Support E-mail'),
                                                        $destinatary,
                                                        '',
                                                        $this->user->lang("Manual Intervention Required:")." ".$user->getFullName());
                    }
                    // Don't want to send notification more than once.
                    $sql = "UPDATE `domains` "
                          ."SET `signup` = '2' "
                          ."WHERE `id` = ? ";
                    $this->db->query($sql, $row['id']);
                }
            }
        }
        array_unshift($messages, $this->user->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 output()
    {
        $this->tpl->define(array('orderqueue_table' => 'views/admin/orderqueue_table.tpl'));
        $this->tpl->define_dynamic('order', 'orderqueue_table');
        $rowclass="odd";

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

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

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

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

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

    function dashboard()
    {    
        $query = "SELECT COUNT(id) AS orders "
                ."FROM domains "
                ."WHERE status = 0 "
                ."AND signup = 1 ";
        $result = $this->db->query($query);
        $row = $result->fetch();
        if (!$row) {
            $row['orders'] = 0;
        }
        
        $message = $this->user->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 = $this->db->query($query);
        $row = $result->fetch();
        if (!$row) {
            $row['orders'] = 0;
        }
        
        $message .= $this->user->lang('Number of orders requiring manual setup: %d', $row['orders']);
        
        return $message;
    }
}

?>
