<?php

require_once 'classes/ExportPlugin.php';

/**
* @package Plugins
*/
class PluginInvoicesdata extends ExportPlugin
{
    var $name = /*T*/'Export Invoices Data'/*/T*/;

    function getForm()
    {
        $this->tpl->define(array('PluginInvoicesdata' => 'views/reports/PluginInvoicesdata.tpl'));

        $fields = array('Invoice ID', 'Amount', 'Tax percentage', 'Tax amount', 'Customer ID', 'Customer Name', 'Customer Last Name', 'Organization', 'Description', 'Bill Date', 'Date Paid');
        for ($i = 0; $i < count($fields); $i++) {
            $this->tpl->setkey('inputname', str_replace(array(' ', '_'), array('_', '__'), $fields[$i]));
            $this->tpl->setkey('fieldname', $this->user->varLang($fields[$i]));
            $this->tpl->setkey('checked', 'checked');
            $this->tpl->parse('trash', '.invoices_field');
            if (!(($i+1) % 3)) {
                $this->tpl->parse('trash', '.invoices_fields_column');
                $this->tpl->clear_dynamic('invoices_field');
            }
        }
        // print last unfilled column
        if ((--$i+1) % 3) {
            $this->tpl->parse('trash', '.invoices_fields_column');
            $this->tpl->clear_dynamic('invoices_field');
        }

        return $this->tpl->subst('PluginInvoicesdata_out', 'PluginInvoicesdata');
    }

    function process($post)
    {
        $fields = array();
        foreach ($post as $fieldname => $value) {
            if (strpos($fieldname, 'invoices_field_') === 0) {
                $fields[] = str_replace(array('__', '_'), array('_', ' '), substr($fieldname, 15));
            }
        }
        if (!$fields) {
            NE_Lib::redirectPage("index.php?fuse=reports&action=ViewExport");
        }
        $csv = $this->_getInvoicesCSV($fields, $_POST['invoice_status']);
        NE_Lib::download($csv, $this->user->lang("invoices").'.csv');
    }

    function _getInvoicesCSV($fields, $status)
    {
        $numFields = count($fields);
        $fieldsMap = array(
            'Invoice ID'        => 'id',
            'Amount'            => 'amount',
            'Tax percentage'    => 'tax',
            'Description'       => 'description',
            'Bill Date'         => 'billdate',
            'Date Paid'         => 'datepaid',
        );
        $dbFields = array();
        foreach ($fieldsMap as $human => $machine) {
            if (in_array($human, $fields)) {
                $dbFields[] = $machine;
            }
        }
        if (in_array('Tax amount', $fields)) {
            if (!in_array('tax', $dbFields)){
                $dbFields[] = 'tax';
            }
            if (!in_array('amount', $dbFields)){
                $dbFields[] = 'amount';
            }
        }
        $dbFields[] = 'customerid';
        $dbFields = implode(", ", $dbFields);
        $query = "SELECT $dbFields FROM invoice";
        if ($status == 'paid') {
            $query .= " WHERE status = 1";
        } elseif ($status == 'unpaid') {
            $query .= " WHERE status = 0";
        }
        $result = $this->db->query($query);
        $fieldstranslated = "";
        $numOfTheField = 1;
        foreach ($fields as $field) {
            if ($numOfTheField == $numFields) {
                $fieldstranslated .= '"'.$this->user->varLang($field).'"';
            } else {
        	$fieldstranslated .= '"'.$this->user->varLang($field).'", ';
            }
            $numOfTheField ++;
        }
        $csv = $fieldstranslated. "\n";
        while ($row = $result->fetch()) {
            for ($i = 0; $i < $numFields; $i++) {
                if ($fields[$i] == 'Customer Name') {
                    $query = "SELECT value FROM user_customuserfields WHERE userid = '{$row['customerid']}' AND customid = 1";
                    $result2 = $this->db->query($query);
                    $row2 = $result2->fetch();
                    $csv .= "\"{$row2['value']}\"";
                } elseif ($fields[$i] == 'Customer Last Name') {
                    $query = "SELECT value FROM user_customuserfields WHERE userid = '{$row['customerid']}' AND customid = 2";
                    $result2 = $this->db->query($query);
                    $row2 = $result2->fetch();
                    $csv .= "\"{$row2['value']}\"";
                } elseif ($fields[$i] == 'Customer ID') {
                    $csv .= "\"{$row['customerid']}\"";
                } elseif ($fields[$i] == 'Tax amount') {
                    $taxAmount = $row['amount'] * $row['tax'] / 100;
                    require_once 'classes/Currency.php';
                    $currency = new Currency($this->user);                    
                    $csv .= "\"".$currency->format($this->settings->get('Default Currency'), $taxAmount)."\"";
                } elseif ($fields[$i] == 'Organization') {
                    $query = "SELECT value FROM user_customuserfields WHERE userid = ? AND customid = ?";
                    $result2 = $this->db->query($query, $row['customerid'], 10);
                    $row2 = $result2->fetch();
                    $csv .= "\"{$row2['value']}\"";
                } else {
                    $csv .= '"' . $row[$fieldsMap[$fields[$i]]] . '"';
                }
                if ($i == ($numFields - 1)) {
                    $csv .= "\n";
                } else {
                    $csv .= ", ";
                }
            }
        }
	$csv = str_replace('Invoice #', $this->user->lang('Invoice #'), $csv);
        return $csv;
    }
}

?>
