<?php

function plugin_invoicegenerator_variables()
{
    $variables = array(
        'Plugin Name'   => array(
            'type'          => 'hidden',
            'description'   => '',
            'value'         => 'Invoice Generator',
        ),
        'Enabled'       => array(
            'type'          => 'yesno',
            'description'   => 'When enabled, invoices will automatically be sent to your customers for non-autopayment gateways.',
            'value'         => '0',
        ),
        'Run schedule - Minute'  => array(
            'type'          => 'text',
            'description'   => 'Enter number, range, list or steps',
            'value'         => '30',
            'helpid'        => '8',
        ),
        'Run schedule - Hour'  => array(
            'type'          => 'text',
            'description'   => 'Enter number, range, list or steps',
            'value'         => '*',
        ),
        '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_invoicegenerator_execute()
{
    global $gSettingsArray;
    
    $messages = array();
    $numCustomers = 0;
    
    require_once 'modules/billing/fncInvoiceFunctions.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()) <=".$gSettingsArray['Send Invoice Offset'].")";
    $result = $GLOBALS['db']->query($query);
    while(list($customerid,$paymenttype,$userautopayment) = $result->fetch()) {
        ProcessCustomerBilling($customerid, $userautopayment);
        $numCustomers++;
    }
    $query = "update setting set value=? where name = 'LastDateGenerateInvoices'";
    $result = $GLOBALS['db']->query($query, mktime());
    array_unshift($messages, "$numCustomers customer(s) were invoiced");
    return $messages;
}

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

    require_once 'classes/user.php';
    require_once 'common/currency.php';
    $tpl->define(array('invoicequeue_table' => 'views/admin/invoicequeue_table.tpl'));
    $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()) <=".$gSettingsArray['Send Invoice Offset'].")";
    $result = $GLOBALS['db']->query($query);
    $queueEmpty = true;
    // Loop through the customers
    while ($row = $result->fetch()) {

        $user =& new User($row['id']);
        $user->populateCustomFields();
        $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()) <=".$gSettingsArray['Send Invoice Offset'].")"
                 ." order by r.nextbilldate";
        $result2 = $GLOBALS['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 = $GLOBALS['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 = $GLOBALS['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++) {
            $tpl->setkey(array(
            'trClass'            => $rowclass,
            'invoice_customer'   => $user->getFullName(),
            'invoice_customerid' => $row['id'],
            'invoice_amount'     => ShowCurrencySymbol($gSettingsArray['Default Currency']).sprintf("%01.2f",$arrInvoiceAmount[$i]),
            'invoice_date'       => date($gSettingsArray['Date Format'],$arrInvoiceDate[$i]),
            ));

            $queueEmpty = false;

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

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

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

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

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

function plugin_invoicegenerator_dashboard()
{
    global $gSettingsArray;
    
    $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()) <=".$gSettingsArray['Send Invoice Offset'].")";
    $result = $GLOBALS['db']->query($query);
    $row = $result->fetch();
    if (!$row) {
        $row['customers'] = 0;
    }
    return lang('Number of customers to be billed: %d', $row['customers']);
}

?>
