<?php

function plugin_rebiller_variables()
{
    $variables = array(
        'Plugin Name'   => array(
            'type'          => 'hidden',
            'description'   => '',
            'value'         => 'Invoice Reminder',
        ),
        'Enabled'       => array(
            'type'          => 'yesno',
            'description'   => 'When enabled, late invoice reminders will be sent out to customers. This service should only run once per day to avoid sending reminders twice in the same day.',
            'value'         => '0',
        ),
        'Days to trigger reminder'       => array(
            'type'          => 'text',
            'description'   => 'Enter on which number of days late to send an invoice reminder.  You can enter the numbers of days late separated by commas,
                                 a number followed by a + sign to indicate all invoices greater than or equal to this number of days or use * to send reminders each day.
                                <br> Example: 1,5,10+ would send on one day late, five days late and ten or more days late.',
            'value'         => '1,5,10+',
        ),
        'E-mail Subject'     => array(
            'type'          => 'text',
            'description'   => 'Subject to be displayed on E-mail notifications of overdue invoices',
            'value'         => 'Billing Department - Overdue Notice',
        ),
        '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_rebiller_execute()
{
    global $gSettingsArray;
    
    require_once 'modules/billing/fncInvoiceFunctions.php';
    $messages = array();
    $numReminders = 0;
    $arrDays = explode(',', $gSettingsArray['plugin_rebiller_Days to trigger reminder']);

    for($i=0; $i < sizeof($arrDays); $i++) {
        if (substr($arrDays[$i],strlen($arrDays[$i]) - 1, 1) == '+') {
            $val = substr($arrDays[$i],0,strlen($arrDays[$i]) - 1);
            if (!isset($gtNum) || $gtNum > $val)
                $gtNum = $val;
        }
    }
    
    $query = "SELECT i.id, (TO_DAYS(NOW()) - TO_DAYS(i.`billdate`)) as days
    FROM `invoice` i, `users` u 
    WHERE i.`paid`='0' AND u.`id`=i.`customerid` AND u.`status`='1' AND TO_DAYS(NOW()) - TO_DAYS(i.`billdate`) > 0
    ORDER BY i.`billdate`";
    $result = $GLOBALS['db']->query($query);
    while ($row = $result->fetch()) {
        if (in_array($row['days'], $arrDays) || in_array('*',$arrDays) || (isset($gtNum) && $row['days'] >= $gtNum)) {
            sendOverdueNotice($row['id']);
            $numReminders++;
        }
    }
    array_unshift($messages, lang('%s overdue invoice reminders were sent', $numReminders));
    return $messages;
}

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

    require_once 'classes/user.php';
    require_once 'common/currency.php';
    $tpl->define(array('overdueinvoices_table' => 'views/admin/overdueinvoices_table.tpl'));
    $tpl->define_dynamic('overdue', 'overdueinvoices_table');
    $rowclass="odd";
    // Select all customers that have an invoice that needs generation
    $query = "SELECT i.`id`,i.`customerid`, i.`amount`, (TO_DAYS(NOW()) - TO_DAYS(i.`billdate`)) as days
    FROM `invoice` i, `users` u 
    WHERE i.`paid`='0' AND u.`id`=i.`customerid` AND u.`status`='1' AND TO_DAYS(NOW()) - TO_DAYS(i.`billdate`) > 0
    ORDER BY i.`billdate`";
    $result = $GLOBALS['db']->query($query);
    $queueEmpty = true;
    // Loop through the customers
    while ($row = $result->fetch()) {
        $user =& new User($row['customerid']);
        $user->populateCustomFields();

        $tpl->setkey(array(
            'trClass'              => $rowclass,
            'overdue_customer'     => $user->getFullName(),
            'overdue_customerid'   => $user->getId(),
            'overdue_number'       => $row['id'],
            'overdue_amount'       => ShowCurrencySymbol($gSettingsArray['Default Currency']).sprintf("%01.2f",$row['amount']),
            'overdue_days'         => $row['days'],
        ));

        $queueEmpty = false;

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

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

    if ($queueEmpty) {
        $tpl->setkey('NOINVOICES', "<tr><td colspan=\"5\" align=\"center\" style=\"font-style:italic\">".lang('There are no overdue invoices')."</td></tr>");
    } else {
        $tpl->setkey('NOINVOICES', '');
    }

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

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

function plugin_rebiller_dashboard()
{
    global $gSettingsArray;
    
    $query = "SELECT COUNT(*) as overdue
    FROM `invoice` i, `users` u 
    WHERE i.`paid`='0' AND u.`id`=i.`customerid` AND u.`status`='1' AND TO_DAYS(NOW()) - TO_DAYS(i.`billdate`) > 0";
    $result = $GLOBALS['db']->query($query);
    $row = $result->fetch();
    if (!$row) {
        $row['overdue'] = 0;
    }
    return lang('Number of invoices overdue: %d', $row['overdue']);
}

?>
