<?php

require_once 'newedge/classes/NE_MailGateway.php';
require_once 'modules/clients/models/user.php';
require_once 'modules/admin/models/ServicePlugin.php';
require_once 'modules/admin/models/Package.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*/'Activate Cancelled Users'/*/T*/       => array(
                'type'          => 'yesno',
                'description'   => /*T*/'When enabled, new orders from cancelled customers will also be activated.'/*/T*/,
                '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;
    }


    /**
     * Execute the order processor.  We'll activate any pending users and 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();
        $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()) {
            $domain = new UserPackage($row['id'], $this->user);
            if ($domain->CustomerId == 0) continue; // prevents orphaned domains from creating many users
            $user = new User($domain->CustomerId);
            // Activate the user if pending
            if ($user->GetStatus() == USER_STATUS_PENDING && sizeof($user->getUnpaidInvoices()) == 0 && sizeof($user->getPartiallyPaidInvoices()) == 0) {
                $user->setStatus(USER_STATUS_ACTIVE);
                $user->save();
            }

            // Activate the user if they are cancelled and we are activating cancelled users
            if ( $this->settings->get('plugin_order_Activate Cancelled Users') ) {
                if ( $user->GetStatus() == USER_STATUS_CANCELLED && sizeof($user->getUnpaidInvoices()) == 0 && sizeof($user->getPartiallyPaidInvoices()) == 0 ) {
                    $user->setStatus(USER_STATUS_ACTIVE);
                    $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() == USER_STATUS_ACTIVE) {
                $mailGateway = new NE_MailGateway();
                $userPackageGateway = new UserPackageGateway($user);
                if ( (($this->settings->get('plugin_order_Enabled') && isset($automaticactivation[$row['Plan']])) || (!$this->settings->get('plugin_order_Enabled')))) {
                    // If we are here, then we should be automatically registering the domain as well, based on the automatic activation of product setting.
                    $useRegistrarPlugin = true;
                    
                    $useServerPlugin = false;
                    // Only use server plugin if we have a plugin to use
                    if ( $userPackageGateway->hasPlugin($domain , $pluginName) ) {
                        $useServerPlugin = true;
                    }
                    // determine whether to register the domain
                    // ToDo4.1 !$packageType->isSub()
                    if ( $domain->getProductType() == 3 ) {
                       if ($domain->getCustomField('Registration Option') == 2 && $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->getCustomField('Domain Name'))
                            .". 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++;
					$package = new Package($domain->Plan);
                    try {
                        $domain->activate($this, $package->sendwelcome, $useServerPlugin, $useRegistrarPlugin, true);
                    } catch ( Exception $e ) {
                        // Update signup value so we don't constantly try to activate a failed activation
                        $sql = "UPDATE `domains` "
                          ."SET `signup` = '2' "
                          ."WHERE `id` = ? ";
                        $this->db->query($sql, $row['id']);

                        // Send an e-mail to notifiy admin that the attempt to automatically activate the package failed.
                        if ( $this->settings->get('plugin_order_E-mail Notifications') != '' ) {
                            $strEmailMessage = "Dear Support Member,\r\n\r\nCustomer ".$user->getFullName()
                                ." has ordered a package that requires manual processing, as the automatic attempt failed. Error message: " . $e->getMessage() . "\r\n\r\nPlease 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());
                            }
                        }
                    }
                } else {
                    if ( $this->settings->get('plugin_order_E-mail Notifications') != '' ) {
                        $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;
    }

    function 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;
    }
}

?>