<?php
require_once 'modules/admin/models/ServicePlugin.php';
/**
* @package Plugins
*/
class PluginRebiller extends ServicePlugin
{
    function getVariables()
    {
        $variables = array(
            /*T*/'Plugin Name'/*/T*/   => array(
                'type'          => 'hidden',
                'description'   => /*T*/''/*/T*/,
                'value'         => /*T*/'Invoice Reminder'/*/T*/,
            ),
            /*T*/'Enabled'/*/T*/       => array(
                'type'          => 'yesno',
                'description'   => /*T*/'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.'/*/T*/,
                'value'         => '0',
            ),
            /*T*/'Days to trigger reminder'/*/T*/       => array(
                'type'          => 'text',
                'description'   => /*T*/'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.'/*/T*/,
                'value'         => '1,5,10+',
            ),
            /*T*/'Run schedule - Minute'/*/T*/  => array(
                'type'          => 'text',
                'description'   => /*T*/'Enter number, range, list or steps'/*/T*/,
                'value'         => '0',
                'helpid'        => '8',
            ),
            /*T*/'Run schedule - Hour'/*/T*/  => array(
                'type'          => 'text',
                'description'   => /*T*/'Enter number, range, list or steps'/*/T*/,
                'value'         => '0',
            ),
            /*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;
    }
    
    function execute()
    {
        require_once 'modules/billing/models/BillingGateway.php';
        $messages = array();
        $numReminders = 0;
        $arrDays = explode(',', $this->settings->get('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.`status`='0' OR i.`status`='5') AND u.`id`=i.`customerid` AND u.`status`='1' AND TO_DAYS(NOW()) - TO_DAYS(i.`billdate`) > 0 "
                ."ORDER BY i.`billdate`";
        $result = $this->db->query($query);
        while ($row = $result->fetch()) {
            if (in_array($row['days'], $arrDays) || in_array('*',$arrDays) || (isset($gtNum) && $row['days'] >= $gtNum)) {
                $billingGateway = new BillingGateway($this->user);
                $billingGateway->sendOverdueNotice($row['id']);
                $numReminders++;
            }
        }
        array_unshift($messages, $this->user->lang('%s overdue invoice reminders were sent', $numReminders));
        return $messages;
    }
    
    function output()
    {
        include_once 'modules/clients/models/user.php';
        include_once 'modules/billing/models/Currency.php';
        $currency = new Currency($this->user);
        $this->tpl->define(array('overdueinvoices_table' => 'views/admin/overdueinvoices_table.tpl'));
        $this->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`, i.`balance_due`, (TO_DAYS(NOW()) - TO_DAYS(i.`billdate`)) AS days "
                ."FROM `invoice` i, `users` u "
                ."WHERE (i.`status`='0' OR i.`status`='5') AND u.`id`=i.`customerid` AND u.`status`='1' AND TO_DAYS(NOW()) - TO_DAYS(i.`billdate`) > 0 "
                ."ORDER BY i.`billdate`";
        $result = $this->db->query($query);
        $queueEmpty = true;
        // Loop through the customers
        while ($row = $result->fetch()) {
            $user = new User($row['customerid']);
    
            $this->tpl->setkey(array(
                'trClass'              => $rowclass,
                'overdue_customer'     => $user->getFullName(),
                'overdue_customerid'   => $user->getId(),
                'overdue_number'       => $row['id'],
                'overdue_amount'       => $currency->format($this->settings->get('Default Currency'), $row['amount'], true),
                'overdue_balance_due'  => $currency->format($this->settings->get('Default Currency'), $row['balance_due'], true),
                'overdue_days'         => $row['days'],
            ));
    
            $queueEmpty = false;
    
            //alternate row color
            if ($rowclass=="odd") $rowclass="even";
            else $rowclass="odd";
    
            $this->tpl->subst('trash', '.overdue');
        }
    
        if ($queueEmpty) {
            $this->tpl->setkey('NOINVOICES', "<tr><td colspan=\"5\" align=\"center\" style=\"font-style:italic\">".$this->user->lang('There are no overdue invoices')."</td></tr>");
        } else {
            $this->tpl->setkey('NOINVOICES', '');
        }
    
        $this->tpl->parse('output', 'overdueinvoices_table');
    
        return $this->tpl->fetch('output');   
    }
    
    function dashboard()
    {
        $query = "SELECT COUNT(*) AS overdue "
                ."FROM `invoice` i, `users` u "
                ."WHERE (i.`status`='0' OR i.`status`='5') AND u.`id`=i.`customerid` AND u.`status`='1' AND TO_DAYS(NOW()) - TO_DAYS(i.`billdate`) > 0";
        $result = $this->db->query($query);
        $row = $result->fetch();
        if (!$row) {
            $row['overdue'] = 0;
        }
        return $this->user->lang('Number of invoices overdue: %d', $row['overdue']);
    }
}
?>
