<?php

function plugin_batchnotifier_variables()
{
    $variables = array(
        'Plugin Name'   => array(
            'type'          => 'hidden',
            'description'   => '',
            'value'         => 'Upcoming Batch Invoice Notifier',
        ),
        'Enabled'       => array(
            'type'          => 'yesno',
            'description'   => 'When enabled, alert credit card autopayment customers a set number of days before an invoice is processed.<br><b>NOTE:</b> Only run once per day to avoid duplicate E-mails.',
            'value'         => '0',
        ),
        'Summary E-mail'     => array(
            'type'          => 'text',
            'description'   => 'E-mail address to which a summary of each service run will be sent.  (Leave blank if you do not wish to receive a summary)',
            'value'         => '',
        ),
        'Days Offset'       => array(
            'type'          => 'text',
            'description'   => 'Number of days before due date to send the E-mail notification.',
            'value'         => '1',
        ),
        'E-mail Subject'     => array(
            'type'          => 'text',
            'description'   => 'The E-mail subject sent to the client.',
            'value'         => 'Billing Department - Upcoming Invoice Notification',
        ),
        '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'         => '*',
        ),
    );

    return $variables;
}

function plugin_batchnotifier_execute()
{
    global $gSettingsArray;
    require_once 'classes/user.php';
    require_once 'common/mailfunctions.php';
    require_once 'common/currency.php';
    
    $messages = array();
    $numCustomers = 0;
    // Summary Variables
    $summaryNames = array();
    $summaryAmounts = array();
    
    $dueDateTimeStamp = mktime(0, 0, 0, date("m"), date("d") + $gSettingsArray['plugin_batchnotifier_Days Offset'], date("Y"));
    $dueDate = date($gSettingsArray['Date Format'], $dueDateTimeStamp);
    
    $query = "SELECT DISTINCT (c.id)
                       FROM users c, recurringfee r
                       WHERE c.groupid=1
                       AND c.autopayment=1
                       AND c.status=1
                       AND r.disablegenerate<>2
                       AND r.customerid=c.id
                       AND (UNIX_TIMESTAMP(r.nextbilldate) = ?)";
    $result = $GLOBALS['db']->query($query, $dueDateTimeStamp);
    while(list($customerid) = $result->fetch()) {
        $user =& new User($customerid);
        $user->populateCustomFields();
        
        $query = "SELECT SUM(`amount`) 
                           FROM `recurringfee` 
                           WHERE `customerid`=? 
                           AND (UNIX_TIMESTAMP(nextbilldate) = ?)";
        $subResult = $GLOBALS['db']->query($query, $customerid, $dueDateTimeStamp);
        list($batchAmount) = $subResult->fetch();
        $batchAmount = ShowCurrencySymbol($user->getCurrency(),false).sprintf("%01.2f", $batchAmount);
        // Setup the customer email template
        $strEmail = $gSettingsArray['Batch Invoice Notification Template'];
        $strEmail = str_replace('[DATE]', $dueDate, $strEmail);
        $strEmail = str_replace('[CLIENTNAME]', $user->getFullName(), $strEmail);
        $strEmail = str_replace('[CLIENTEMAIL]', $user->getEmail(), $strEmail);
        $strEmail = str_replace('[AMOUNT]', $batchAmount, $strEmail);
        $strEmail = str_replace('[CLIENTAPPLICATIONURL]', $gSettingsArray['ClientExec URL'], $strEmail);
        $strEmail = str_replace('[FORGOTPASSWORDURL]', $gSettingsArray["ClientExec URL"]."/index.php?fuse=".cLOGOFF."&action=".cGENERAL_SHOWFORGOTPASSWORDWINDOW, $strEmail);
        $strEmail = str_replace('[COMPANYNAME]', $gSettingsArray['Company Name'], $strEmail);
        $strEmail = str_replace('[BILLINGEMAIL]', $gSettingsArray['Billing E-mail'], $strEmail);
        $strEmail = ReplaceCustomFields($strEmail, $customerid);
        
        mailMessage($strEmail,$gSettingsArray['Billing E-mail'],$gSettingsArray['Billing E-mail'],$customerid,"",$gSettingsArray['plugin_batchnotifier_E-mail Subject'],3,0);
        // Save information for summary email
        $summaryNames[] = $user->getFullName();
        $summaryAmounts[] = $batchAmount;
        $numCustomers++;
    }
    if ($gSettingsArray['plugin_batchnotifier_Summary E-mail'] != "") {
        if (count($summaryNames) == 0) {
            $summaryEmail = lang("No upcoming batch invoice transactions for %s.",$dueDate);
        } else {
            $summaryEmail = lang("Upcoming batch invoice notifications for %s sent to", $dueDate).":\n";
            for ($i = 0; $i < count($summaryNames); $i++) {
                $summaryEmail .= $summaryNames[$i]."  ".$batchAmount."\n";
            }
        }
        mailMessageEmail($summaryEmail,$gSettingsArray['Billing E-mail'],$gSettingsArray['Billing E-mail'],$gSettingsArray['plugin_batchnotifier_Summary E-mail'],"",$gSettingsArray['plugin_batchnotifier_E-mail Subject'],3,0);
    }
    array_unshift($messages, lang('%s customer(s) were notified.', $numCustomers));
    return $messages;
}

function plugin_batchnotifier_output()
{
    global $tpl;
    global $gSettingsArray;

    require_once 'classes/user.php';
    require_once 'common/currency.php';
    
    $tpl->define(array('batchnotifier_table' => 'views/admin/batchnotifier_table.tpl'));
    $tpl->define_dynamic('charge', 'batchnotifier_table');
    $rowclass="odd";
    $dueDateTimeStamp = mktime(0, 0, 0, date("m"), date("d") + $gSettingsArray['plugin_batchnotifier_Days Offset'], date("Y"));
    $dueDate = date($gSettingsArray['Date Format'], $dueDateTimeStamp);
    $queueEmpty = true;
    
    $query = "SELECT DISTINCT (c.id)
                       FROM users c, recurringfee r
                       WHERE c.groupid=1
                       AND c.autopayment=1
                       AND c.status=1
                       AND r.disablegenerate<>2
                       AND r.customerid=c.id
                       AND (UNIX_TIMESTAMP(r.nextbilldate) = ?)";
    $result = $GLOBALS['db']->query($query, $dueDateTimeStamp);
    while(list($customerid) = $result->fetch()) {
        $user =& new User($customerid);
        $user->populateCustomFields();
        
        $query = "SELECT SUM(`amount`) 
                           FROM `recurringfee` 
                           WHERE `customerid`=? 
                           AND (UNIX_TIMESTAMP(nextbilldate) = ?)";
        $subResult = $GLOBALS['db']->query($query, $customerid, $dueDateTimeStamp);
        list($batchAmount) = $subResult->fetch();
        $batchAmount = ShowCurrencySymbol($user->getCurrency(),false).sprintf("%01.2f", $batchAmount);
        $tpl->setkey(array(
        'trClass'            => $rowclass,
        'charge_customer'   => $user->getFullName(),
        'charge_customerid' => $customerid,
        'charge_amount'     => $batchAmount,
        'charge_date'       => $dueDate,
        ));

        $queueEmpty = false;

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

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

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

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

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

function plugin_batchnotifier_dashboard()
{
    global $gSettingsArray;
    
    $dueDateTimeStamp = mktime(0, 0, 0, date("m"), date("d") + $gSettingsArray['plugin_batchnotifier_Days Offset'], date("Y"));
    $dueDate = date($gSettingsArray['Date Format'], $dueDateTimeStamp);
    
    $query = "SELECT COUNT(DISTINCT (c.id)) as customers
                       FROM users c, recurringfee r
                       WHERE c.groupid=1
                       AND c.autopayment=1
                       AND c.status=1
                       AND r.disablegenerate<>2
                       AND r.customerid=c.id
                       AND (UNIX_TIMESTAMP(r.nextbilldate) = ?)";
    $result = $GLOBALS['db']->query($query, $dueDateTimeStamp);
    $row = $result->fetch();
    if (!$row) {
        $row['customers'] = 0;
    }
    return lang('Number of upcoming batch payments for %s: %d', $dueDate, $row['customers']);
}

?>
