<?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 (mb_substr($arrDays[$i],strlen($arrDays[$i]) - 1, 1) == '+') {
                $val = mb_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 pendingItems()
	{
		include_once 'modules/clients/models/user.php';
        include_once 'modules/billing/models/Currency.php';
        $currency = new Currency($this->user);
        // 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);
		$returnArray = array();
		$returnArray['data'] = array();
        while ($row = $result->fetch()) {
            $user = new User($row['customerid']);
			$tmpInfo = array();
			$tmpInfo['customer'] = $user->getFullName();
			$tmpInfo['customer_id'] = $user->getId();
			$tmpInfo['invoice_number'] = $row['id'];
			$tmpInfo['amount'] = $currency->format($this->settings->get('Default Currency'), $row['amount'], true);
			$tmpInfo['balance_due'] = $currency->format($this->settings->get('Default Currency'), $row['balance_due'], true);
			$tmpInfo['days'] = $row['days'];
			$returnArray['data'][] = $tmpInfo;
        }
		$returnArray["totalcount"] = count($returnArray['data']);
        return $returnArray;
	}
    
    function 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']);
    }
}
?>