<?php
require_once 'classes/ServicePlugin.php';
/**
* @package Plugins
*/
class PluginInvoicegenerator extends ServicePlugin
{
    function getVariables()
    {
        $variables = array(
            /*T*/'Plugin Name'/*/T*/   => array(
                'type'          => 'hidden',
                'description'   => /*T*/''/*/T*/,
                'value'         => /*T*/'Invoice Generator'/*/T*/,
            ),
            /*T*/'Enabled'/*/T*/       => array(
                'type'          => 'yesno',
                'description'   => /*T*/'When enabled, invoices will automatically be sent to your customers for non-autopayment gateways.'/*/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;
    }
    
    function execute()
    {
        $messages = array();
        $numCustomers = 0;
        require_once 'modules/billing/models/BillingGateway.php';
        
        $query = "SELECT DISTINCT (c.id), c.paymenttype, c.autopayment "
                ."FROM users c, recurringfee r "
                ."WHERE c.groupid=1 "
                ."AND c.autopayment=0 "
                ."AND c.status=1 "
                ."AND r.disablegenerate<>2 "
                ."AND r.customerid=c.id "
                ."AND (TO_DAYS(r.nextbilldate) - TO_DAYS(NOW()) <=".$this->settings->get('Send Invoice Offset').")";
        $result = $this->db->query($query);
        while(list($customerid,$paymenttype,$userautopayment) = $result->fetch()) {
            $billingGateway = new BillingGateway($this->user);
            $billingGateway->processCustomerBilling($customerid, $userautopayment);
            $numCustomers++;
        }
        $query = "UPDATE setting SET value=? WHERE name = 'LastDateGenerateInvoices'";
        $result = $this->db->query($query, mktime());
        array_unshift($messages, "$numCustomers customer(s) were invoiced");
        return $messages;
    }
    
    function output()
    {
        require_once 'classes/user.php';
        require_once 'classes/Currency.php';
        $this->tpl->define(array('invoicequeue_table' => 'views/admin/invoicequeue_table.tpl'));
        $this->tpl->define_dynamic('invoice', 'invoicequeue_table');
        $rowclass="odd";
        // Select all customers that have an invoice that needs generation
        $query = "SELECT DISTINCT (c.id),c.paymenttype,c.autopayment "
                ."FROM users c, recurringfee r "
                ."WHERE c.groupid=1 "
                ."AND c.autopayment=0 "
                ."AND c.status=1 "
                ."AND r.disablegenerate<>2 "
                ."AND r.customerid=c.id "
                ."AND (TO_DAYS(r.nextbilldate) - TO_DAYS(NOW()) <=".$this->settings->get('Send Invoice Offset').")";
        $result = $this->db->query($query);
        $queueEmpty = true;
        // Loop through the customers
        while ($row = $result->fetch()) {
    
            $user =& new User($row['id']);
            $query = "SELECT r.disablegenerate, r.id, UNIX_TIMESTAMP(r.nextbilldate), r.paymentterm, c.currency, r.appliestoid, r.billingtypeid, r.description, r.detail, r.amount "
                     ."FROM users c, recurringfee r "
                     ."WHERE c.groupid=1 "
                     ."AND c.autopayment=0 "
                     ."AND r.customerid=c.id "
                     ."AND r.disablegenerate<>2 "
                     ."AND c.id = ?"
                     ."AND (TO_DAYS(r.nextbilldate) - TO_DAYS(NOW()) <=".$this->settings->get('Send Invoice Offset').") "
                     ."ORDER BY r.nextbilldate";
            $result2 = $this->db->query($query, $row['id']);
            $arrInvoiceAmount = array();
            $arrInvoiceDate = array();
            $arrInvoiceApply = array();
            // Loop through all the recurring fees
            while ($row2 = $result2->fetch()) {
                $found = false;
                for ($i = 0; $i < sizeof($arrInvoiceAmount); $i++) {
                    // If we have an invoice due on the same day add the total to that invoice
                    if ($row2['UNIX_TIMESTAMP(r.nextbilldate)'] == $arrInvoiceDate[$i]) {
                        $arrInvoiceAmount[$i] += $row2['amount'];
                        // Check to see if we've already grabbed all the invoice entries that need to be applied to this domain
                        if (!in_array($row2['appliestoid'],$arrInvoiceApply)) {
                            $uninvoicedquery = "SELECT price FROM invoiceentry WHERE invoiceid=0 AND recurring=0 AND includenextpayment=1 AND customerid=? AND appliestoid=?";
                            $uninvoicedresult = $this->db->query($uninvoicedquery, $row['id'], $row2['appliestoid']);
                            // Add any invoice entries that will be merged to the total price
                            while(list($entryPrice) = $uninvoicedresult->fetch())
                            {
                                $arrInvoiceAmount[$i] += $entryPrice;
                            }
                            $arrInvoiceApply[] = $row2['appliestoid'];
                        }
                        $found = true;
                        break;
                    }
                }
                if (!$found) {
                    $arrInvoiceAmount[] = $row2['amount'];
                    $arrInvoiceDate[] = $row2['UNIX_TIMESTAMP(r.nextbilldate)'];
                    // Check to see if we've already grabbed all the invoice entries that need to be applied to this domain
                    if (!in_array($row2['appliestoid'],$arrInvoiceApply)) {
                        $uninvoicedquery = "SELECT price FROM invoiceentry WHERE invoiceid=0 AND recurring=0 AND includenextpayment=1 AND customerid=? AND appliestoid=?";
                        $uninvoicedresult = $this->db->query($uninvoicedquery, $row['id'], $row2['appliestoid']);
                        // Add any invoice entries that will be merged to the total price
                        while(list($entryPrice) = $uninvoicedresult->fetch())
                        {
                            $arrInvoiceAmount[sizeof($arrInvoiceAmount)-1] += $entryPrice;
                        }
                        $arrInvoiceApply[] = $row2['appliestoid'];
                    }
                }  
            }
            // Loop through all the invoices for this customer and display them in the table
            for ($i = 0; $i < sizeof($arrInvoiceAmount); $i++) {
                $tCurrency = new Currency($this->user);
                $this->tpl->setkey(array(
                'trClass'            => $rowclass,
                'invoice_customer'   => $user->getFullName(),
                'invoice_customerid' => $row['id'],
                'invoice_amount'     => $tCurrency->format($this->settings->get('Default Currency'), $arrInvoiceAmount[$i], true),
                'invoice_date'       => date($this->settings->get('Date Format'),$arrInvoiceDate[$i]),
                ));
    
                $queueEmpty = false;
    
                //alternate row color
                if ($rowclass=="odd") $rowclass="even";
                else $rowclass="odd";
    
                $this->tpl->subst('trash', '.invoice');
            }
        }
    
        if ($queueEmpty) {
            $this->tpl->setkey('NOINVOICES', "<tr><td colspan=\"5\" align=\"center\" style=\"font-style:italic\">".$this->user->lang('The queue is empty')."</td></tr>");
        } else {
            $this->tpl->setkey('NOINVOICES', '');
        }
    
        $this->tpl->parse('output', 'invoicequeue_table');
    
        return $this->tpl->fetch('output');   
    }
    
    function dashboard()
    {
        $query = "SELECT COUNT(DISTINCT (c.id))  AS customers "
                ."FROM users c, recurringfee r "
                ."WHERE c.groupid=1 "
                ."AND c.autopayment=0 "
                ."AND c.status=1 "
                ."AND r.disablegenerate<>2 "
                ."AND r.customerid=c.id "
                ."AND (TO_DAYS(r.nextbilldate) - TO_DAYS(NOW()) <=".$this->settings->get('Send Invoice Offset').")";
        $result = $this->db->query($query);
        $row = $result->fetch();
        if (!$row) {
            $row['customers'] = 0;
        }
        return $this->user->lang('Number of customers to be billed: %d', $row['customers']);
    }
}
?>
