<?php
  /**
   * phpaga
   *
   * Add invoice
   *
   * This is the interface to create a new invoice with line items.
   *
   * @author Florian Lanthaler <florian@phpaga.net>
   * @version $Id$
   *
   * Copyright (c) 2005, Florian Lanthaler <florian@phpaga.net>
   *
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are
   * met:
   *
   *    * Redistributions of source code must retain the above copyright
   *      notice, this list of conditions and the following disclaimer.
   *
   *    * Redistributions in binary form must reproduce the above copyright
   *      notice, this list of conditions and the following disclaimer in
   *      the documentation and/or other materials provided with the
   *      distribution.
   *
   *    * Neither the name of Florian Lanthaler nor the names of his
   *      contributors may be used to endorse or promote products derived
   *      from this software without specific prior written permission.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
   * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
   * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
   * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

include_once("./config.php");

phpaga_user_pageperm(PHPAGA_PERM_MANAGE_INVOICES);

$opIds = array();
$oprows = array();
$select_bmt = array();
$select_currency = array();#
$products = null;
$prodcount = 0;
$prodIds = null;

$expinfo = array();
$expenses = array();
$expensesum = 0;

$payments = array();
$paymentsum = array();

$persons = array();
$h_pe = array();

$humancost = array("total_amount" => "");

$billInfo = array("bill_number" => "",
                  "bill_date" => "",
                  "bill_date_due" => "",
                  "bill_payterm" => "",
                  "cpn_id" => "",
                  "bmt_id" => "",
                  "curr_id" => PHPAGA_DEFAULTCURRENCY,
                  "bill_startsum" => 0,
                  "taskassociation" => 0,
                  "lineitems" => array(),
                  "expenses" => array(),
				  "bill_additional_line" => "",
                  "rbill_id" => null,
                  "rbill_type" => PHPAGA_RBILL_TYPE_NONE,
                  "rbill_end" => null);

$opInfo = array("cpn_id" => "",
                "pe_id" => "",
                "prj_id" => "",
                "opcat_id" => "",
                "op_desc" => "",
                "op_startdatefrom" => "",
                "op_startdateto" => "");

$duration = "";
$statusmsg = "";
$statusmsgarr = array();
$op_id = "";
$bill_id = "";
$billing_err = "";
$tmp_nr = "";
$bill_endsum = "";
$bill_details = null;
$dropped_operations = 0;
$dropped_materialref = 0;

function _add_lineitems(&$lineitems)
{
    for ($i = 0; $i < 5; $i++) {
        $lineitems[] = array("op_id" => null,
                             "mat_id" => null,
                             "lit_prodcode" => null,
                             "lit_desc" => null,
                             "lit_qty" => null,
                             "lit_unitnetprice" => null,
                             "lit_netprice" => null);
    }
}

if (isset($REQUEST_DATA["id"]) && is_numeric($REQUEST_DATA["id"]) && isset($REQUEST_DATA["action"]) && ($REQUEST_DATA["action"] == ACTION_CLONE))
{
    /* clone an existing bill */

    $billInfo = phpaga_bills_getinfo($REQUEST_DATA["id"]);

    if (!PhPagaError::isError($billInfo))
    {

        /* we don't want to bill tasks or expenses twice */
        $billInfo["operations"] = array();
        $billInfo["expenses"] = array();

        if (is_array($billInfo["lineitems"]) && (count($billInfo["lineitems"]) > 0))
        {
            $tmp_lit = $billInfo["lineitems"];
            $billInfo["lineitems"] = array();

            foreach ($tmp_lit as $tlit)
            {
                if (!isset($tlit["op_id"]) || !strlen($tlit["op_id"])) {

                    if (isset($tlit["mat_id"]) && strlen($tlit["mat_id"])) {
                        $tlit["mat_id"] = null;
                        $dropped_materialref++;
                    }

                    $billInfo["lineitems"][] = $tlit;
                }  else
                    $dropped_operations++;
            }
        }
        else
            $billInfo["lineitems"] = array();

        if ($dropped_operations > 0)
            $statusmsgarr[] = sprintf(_("%s line items that were associated to tasks have been removed in this cloned invoice."),
                                      $dropped_operations);

        if ($dropped_materialref > 0)
            $statusmsgarr[] = sprintf(_("%s material references have been removed, the respective line items have been preserved."),
                                      $dropped_materialref);

        $billInfo["bill_number"] = phpaga_bills_getNewInvoiceNumber();

        /* overwrite old bill's date with current date */
        $billInfo["bill_date"] = date("Y-m-d");

    }
}
elseif (isset($REQUEST_DATA["id"]) && is_numeric($REQUEST_DATA["id"])
        && isset($REQUEST_DATA["action"]) && ($REQUEST_DATA["action"] == ACTION_FROMQUOTATION))
{
    /* create a bill from a quotation */

    $quotInfo = phpaga_quotations_getinfo($REQUEST_DATA["id"]);

    if (!PhPagaError::isError($quotInfo)) {

        if (isset($REQUEST_DATA['getquotnum']) && ($REQUEST_DATA['getquotnum'] == '1') && isset($quotInfo["quot_number"]) && strlen($quotInfo["quot_number"]))
            $tmp_nr = $quotInfo["quot_number"];
        else
            $tmp_nr = phpaga_bills_getNewInvoiceNumber();

        $billInfo = array("bill_date" => date("Y-m-d"),
                          "bill_number" => $tmp_nr,
                          "cpn_id" => (int)$quotInfo["cpn_id"],
                          "bill_startsum" => $quotInfo["quot_startsum"],
						  "bill_additional_line" => $quotInfo["quot_additional_line"],
                          "bmt_id" =>  $quotInfo["bmt_id"],
                          "curr_id" => $quotInfo["curr_id"]
            );

        $billInfo["operations"] = array();

        if (is_array($quotInfo["lineitems"]) && (count($quotInfo["lineitems"]) > 0))
        {
            $tmp_lit = $quotInfo["lineitems"];
            $billInfo["lineitems"] = array();

            foreach ($tmp_lit as $tlit)
                $billInfo["lineitems"][] = $tlit;

        }
        else
            $billInfo["lineitems"] = array();

    }
}
elseif (isset($REQUEST_DATA["action"]) && is_numeric($REQUEST_DATA["action"]))
{

    if (isset($REQUEST_DATA["bill_number"]) && strlen($REQUEST_DATA["bill_number"]))
        $billInfo["bill_number"] = $REQUEST_DATA["bill_number"];

    if (isset($REQUEST_DATA["bill_date"]) && strlen($REQUEST_DATA["bill_date"]))
        $billInfo["bill_date"] = $REQUEST_DATA["bill_date"];

    if (isset($REQUEST_DATA["bill_date_due"]) && strlen($REQUEST_DATA["bill_date_due"]))
        $billInfo["bill_date_due"] = $REQUEST_DATA["bill_date_due"];

    if (isset($REQUEST_DATA["bill_payterm"]) && strlen($REQUEST_DATA["bill_payterm"]))
        $billInfo["bill_payterm"] = $REQUEST_DATA["bill_payterm"];

    if (isset($REQUEST_DATA["cpn_id"]) && is_numeric($REQUEST_DATA["cpn_id"]))
    {
        $billInfo["cpn_id"] = $REQUEST_DATA["cpn_id"];

        if (!isset($billInfo["bill_payterm"]) || !strlen($billInfo["bill_payterm"]))
            $billInfo["bill_payterm"] = phpaga_companies_getdefaultpayterm($billInfo["cpn_id"]);

        if (isset($REQUEST_DATA["pe_id_recipient"]) && is_numeric($REQUEST_DATA["pe_id_recipient"]))
            $billInfo["pe_id_recipient"] = $REQUEST_DATA["pe_id_recipient"];
    }

    if (isset($REQUEST_DATA["bill_additional_line"]) && strlen($REQUEST_DATA["bill_additional_line"]))
        $billInfo["bill_additional_line"] = $REQUEST_DATA["bill_additional_line"];

    if (isset($REQUEST_DATA["rbill_id"]) && is_numeric($REQUEST_DATA["rbill_id"]))

        $billInfo["rbill_id"] = $REQUEST_DATA["rbill_id"];

    else {

        if (isset($REQUEST_DATA["rbill_type"]) && is_numeric($REQUEST_DATA["rbill_type"]))
            $billInfo["rbill_type"] = $REQUEST_DATA["rbill_type"];

        if (isset($REQUEST_DATA["rbill_end"]) && strlen($REQUEST_DATA["rbill_end"]))
            $billInfo["rbill_end"] = $REQUEST_DATA["rbill_end"];
    }

    if (isset($REQUEST_DATA["bmt_id"]) && is_numeric($REQUEST_DATA["bmt_id"]))
        $billInfo["bmt_id"] = $REQUEST_DATA["bmt_id"];

    if (isset($REQUEST_DATA["curr_id"]) && is_numeric($REQUEST_DATA["curr_id"]))
        $billInfo["curr_id"] = $REQUEST_DATA["curr_id"];

    if (isset($REQUEST_DATA["taskassociation"]) && strlen($REQUEST_DATA["taskassociation"]))
        $billInfo["taskassociation"] = $REQUEST_DATA["taskassociation"];

    /* operation ids (if chosen) */
    if (isset($REQUEST_DATA["op_id"]) && is_array($REQUEST_DATA["op_id"]))
    {

        $opIds = phpaga_operations_sanitizeopids($REQUEST_DATA["op_id"]);

        $billInfo["operations_listin"] = implode(", ", $opIds);

        /* load all records that match the search criteria */

        $oprows = phpaga_operations_search($dummy_count, $duration, $dummy_opIds,
                                           array("opidlist" => $billInfo["operations_listin"]));

        if (PhPagaError::isError($oprows))
            $oprows->printMessage();
    }

    /* line items */

    if (isset($REQUEST_DATA["lit_prodcode"]) && is_array($REQUEST_DATA["lit_prodcode"]))
    {
        for ($x = 0; $x <= count($REQUEST_DATA["lit_prodcode"]); $x++)
        {

            $h_lit_op_id = null;
            $h_lit_mat_id = null;
            $h_lit_prodcode = null;
            $h_lit_desc = null;
            $h_lit_qty = null;
            $h_lit_unitnetprice = null;
            $h_lit_netprice = null;

            if (isset($REQUEST_DATA["lit_prodcode"][$x]) && strlen($REQUEST_DATA["lit_prodcode"][$x])) {
                $_pc = $REQUEST_DATA["lit_prodcode"][$x];
                if (phpaga_strlen($_pc) > 18)
                    $_pc = phpaga_substr($_pc, 0, 18);
                $h_lit_prodcode = $_pc;
            }

            if (isset($REQUEST_DATA["lit_op_id"][$x]) && strlen($REQUEST_DATA["lit_op_id"][$x]))
                $h_lit_op_id = $REQUEST_DATA["lit_op_id"][$x];

            if (isset($REQUEST_DATA["lit_mat_id"][$x]) && strlen($REQUEST_DATA["lit_mat_id"][$x]))
                $h_lit_mat_id = $REQUEST_DATA["lit_mat_id"][$x];

            if (isset($REQUEST_DATA["lit_desc"][$x]) && strlen($REQUEST_DATA["lit_desc"][$x]))
                $h_lit_desc = $REQUEST_DATA["lit_desc"][$x];

            if (isset($REQUEST_DATA["lit_qty"][$x]) && strlen($REQUEST_DATA["lit_qty"][$x]))
                $h_lit_qty = $REQUEST_DATA["lit_qty"][$x];

            if (isset($REQUEST_DATA["lit_unitnetprice"][$x]) && strlen($REQUEST_DATA["lit_unitnetprice"][$x]))
                $h_lit_unitnetprice = $REQUEST_DATA["lit_unitnetprice"][$x];

            if (isset($REQUEST_DATA["lit_netprice"][$x]) && strlen($REQUEST_DATA["lit_netprice"][$x]))
                $h_lit_netprice = $REQUEST_DATA["lit_netprice"][$x];

            if (is_numeric($h_lit_netprice))
                $billInfo["bill_startsum"] += $h_lit_netprice;

            if (strlen($h_lit_op_id) ||
                strlen($h_lit_mat_id) ||
                strlen($h_lit_prodcode) ||
                strlen($h_lit_desc) ||
                strlen($h_lit_qty) ||
                strlen($h_lit_unitnetprice) ||
                strlen($h_lit_netprice))

                $billInfo["lineitems"][] = array("op_id" => $h_lit_op_id,
                                                 "mat_id" => $h_lit_mat_id,
                                                 "lit_prodcode" => $h_lit_prodcode,
                                                 "lit_desc" => $h_lit_desc,
                                                 "lit_qty" => $h_lit_qty,
                                                 "lit_unitnetprice" => $h_lit_unitnetprice,
                                                 "lit_netprice" => $h_lit_netprice);


        }
    }

    if (isset($REQUEST_DATA["exp_id"]) && is_array($REQUEST_DATA["exp_id"])) {

        $expinfo["idlist"] = $REQUEST_DATA["exp_id"];
        $expinfo["bill_id"] = null;

        $expenses = phpaga_expenses_getexpenses($expinfo);

        if (PhPagaError::isError($expenses))
            $expenses->printMessage();
        else {
            $billInfo["expenses"] = $expenses;

            if (count($expenses) > 0) {
                foreach ($expenses as $exp)
                    $expensesum += $exp["exp_sum"];
            }
        }
    }

    switch($REQUEST_DATA["action"])
    {

    case ACTION_BILL_MAKEIT:

        $result = phpaga_bills_checkInfo($billInfo);

        if (PhPagaError::isError($result))
            $billing_err = $result->getFormattedMessage();
        else {

            /* Check whether the invoice number is unique for this year */

            $tb = array("bill_number" => $billInfo["bill_number"],
                "bill_year" => date("Y", strtotime($billInfo["bill_date"])));

            $tbr = phpaga_bills_search($tbcnt, $tb);

            if ($tbcnt > 0)
                $billing_err = phpaga_returnerror(sprintf(_("This invoice number has already been used in the year %s."),
                    $tb["bill_year"]));
            else {

                $result = phpaga_bills_get_billing_details($billInfo["bmt_id"], $billInfo["curr_id"], $billInfo["bill_startsum"], $expensesum);

                if (PhPagaError::isError($result))
                    $billing_err = $result->getFormattedMessage();
                else {

                    $billInfo["bill_endsum"] = $result->get_endsum();
                    $bill_id = phpaga_bills_add($billInfo);

                    if (PhPagaError::isError($bill_id))
                        $billing_err = $bill_id->getFormattedMessage();
                    else {
                        header("Location: bill.php?id=$bill_id");
                        exit;
                    }
                }
            }
        }
        break;

    case ACTION_BILL_WITHOPERATIONS:
        $billInfo["bill_number"] = phpaga_bills_getNewInvoiceNumber();
        $billInfo["bill_date"] = date("Y-m-d");
        $billInfo["bill_date_due"] = null;
        $billInfo["bmt_id"] = PHPAGA_DEFAULTBMT;

        /* get search criteria for related operations */

        if (isset($REQUEST_DATA["cpn_id"]) && is_numeric($REQUEST_DATA["cpn_id"]))
            $opInfo["cpn_id"] = $REQUEST_DATA["cpn_id"];

        if (isset($REQUEST_DATA["pe_id"]) && is_numeric($REQUEST_DATA["pe_id"]))
            $opInfo["pe_id"] = $REQUEST_DATA["pe_id"];

        if (isset($REQUEST_DATA["prj_id"]) && is_numeric($REQUEST_DATA["prj_id"]))
            $opInfo["prj_id"] = $REQUEST_DATA["prj_id"];

        if (isset($REQUEST_DATA["opcat_id"]) && is_numeric($REQUEST_DATA["opcat_id"]))
            $opInfo["opcat_id"] = $REQUEST_DATA["opcat_id"];

        if (isset($REQUEST_DATA["op_desc"]) && ($REQUEST_DATA["op_desc"] != ""))
            $opInfo["op_desc"] = rawurldecode($REQUEST_DATA["op_desc"]);

        if (isset($REQUEST_DATA["prj_billabletype"]) && is_numeric($REQUEST_DATA["prj_billabletype"]))
            $opInfo["prj_billabletype"] = $REQUEST_DATA["prj_billabletype"];

        if (isset($REQUEST_DATA["op_billabletype"]) && is_numeric($REQUEST_DATA["op_billabletype"]))
            $opInfo["op_billabletype"] = $REQUEST_DATA["op_billabletype"];

        if (isset($REQUEST_DATA["op_startdatefrom"]) && ($REQUEST_DATA["op_startdatefrom"] != ""))
            $opInfo["op_startdatefrom"] = rawurldecode($REQUEST_DATA["op_startdatefrom"]);

        if (isset($REQUEST_DATA["op_startdateto"]) && ($REQUEST_DATA["op_startdateto"] != ""))
            $opInfo["op_startdateto"] = rawurldecode($REQUEST_DATA["op_startdateto"]);

        /* we can only bill operations that have not been billed yet */
        $opInfo["op_billed"] = PHPAGA_BILL_NOTBILLED;

        /* load all records that match the search criteria */
        $oprows = phpaga_operations_search($count, $duration, $opIds, $opInfo);

        _add_lineitems($billInfo["lineitems"]);


        if (isset($REQUEST_DATA["add_expenses"]) && 
            (
                (isset($REQUEST_DATA["prj_id"]) && is_numeric($REQUEST_DATA["prj_id"]))
                ||
                (isset($REQUEST_DATA["cpn_id"]) && is_numeric($REQUEST_DATA["cpn_id"]))
            ))
        {
            if (isset($REQUEST_DATA["prj_id"]) && is_numeric($REQUEST_DATA["prj_id"]))
                $expinfo["prj_id"] = $REQUEST_DATA["prj_id"];
            if (isset($REQUEST_DATA["cpn_id"]) && is_numeric($REQUEST_DATA["cpn_id"]))
                $expinfo["cpn_id"] = $REQUEST_DATA["cpn_id"];
            $expinfo["bill_id"] = null;

            $expenses = phpaga_expenses_getexpenses($expinfo);

            if (PhPagaError::isError($expenses))
                $expenses->printMessage();
            else {
                $billInfo["expenses"] = $expenses;

                if (count($expenses) > 0) {
                    foreach ($expenses as $exp)
                        $expensesum += $exp["exp_sum"];
                }
            }
        }

        break;

    case ACTION_BILL_RECALC:
    case ACTION_BILL_ADDLINEITEMS:

        if ($REQUEST_DATA["action"] == ACTION_BILL_ADDLINEITEMS)
            _add_lineitems($billInfo["lineitems"]);
        elseif (count($billInfo["lineitems"]) == 0)
            _add_lineitems($billInfo["lineitems"]);

        break;


    case ACTION_BILL_MAKEOPITEMS:

        $billInfo["taskassociation"] = PHPAGA_BILL_TASKASSOC_LOCKED;

        if (count($oprows) > 0) {
            foreach ($oprows as $op) {
                $_pc = null;
                if (isset($op["prj_title"]) && strlen($op["prj_title"])) {
                    $_pc = $op["prj_title"];
                    if (phpaga_strlen($_pc) > 18)
                        $_pc = phpaga_substr($_pc, 0, 18);
                }
                $billInfo["lineitems"][] = array("op_id" => $op["op_id"],
                                                 "mat_id" => null,
                                                 "lit_prodcode" => $_pc,
                                                 "lit_desc" => $op["op_desc"],
                                                 "lit_qty" => phpaga_minutes2duration($op["op_duration"]),
                                                 "lit_unitnetprice" => null,
                                                 "lit_netprice" => ($op["op_billabletype"] == 0) ? sprintf("%01.2f", $op["amount"]) : '0.00');

                if ($op["op_billabletype"] == 0)
                    $billInfo["bill_startsum"] += $op["amount"];
            }

        }

        break;

    case ACTION_BILL_MAKESINGLEOPITEM:

        $billInfo["taskassociation"] = PHPAGA_BILL_TASKASSOC_LOCKED;

        if (count($oprows) > 0)
        {
            $h_amount = 0;

            foreach ($oprows as $op) {

                if ($op["op_billabletype"] == 0)
                    $h_amount += $op["amount"];
            }

            $billInfo["bill_startsum"] += $h_amount;

            $billInfo["lineitems"][] = array("op_id" => "-1",
                                             "mat_id" => null,
                                             "lit_prodcode" => null,
                                             "lit_desc" => null,
                                             "lit_qty" => $duration,
                                             "lit_unitnetprice" => null,
                                             "lit_netprice" => sprintf("%01.2f", $h_amount));

        }
        break;

    case ACTION_BILL_MAKEOPITEMSPERPRJ:

        $billInfo["taskassociation"] = PHPAGA_BILL_TASKASSOC_LOCKED;
        $h_lineitems = array();

        if (count($oprows) > 0) {
            foreach ($oprows as $op) {
                $_pc = null;
                if (isset($op["prj_title"]) && strlen($op["prj_title"])) {
                    $_pc = $op["prj_title"];
                    if (phpaga_strlen($_pc) > 18)
                        $_pc = phpaga_substr($_pc, 0, 18);
                }
                if (!isset($h_lineitems[$op["prj_id"]]))
                    $h_lineitems[$op["prj_id"]] = array("lit_prodcode" => $_pc,
                                                        "lit_qty" => 0,
                                                        "lit_unitnetprice" => null,
                                                        "lit_netprice" => 0);

                $h_lineitems[$op["prj_id"]]["lit_qty"] += $op["op_duration"];

                if ($op["op_billabletype"] == 0)
                    $h_lineitems[$op["prj_id"]]["lit_netprice"] += $op["amount"];
            }

            foreach ($h_lineitems as $h_lineitem) {

                $billInfo["lineitems"][] = array("op_id" => -1,
                                                 "mat_id" => null,
                                                 "lit_prodcode" => $h_lineitem["lit_prodcode"],
                                                 "lit_desc" => null,
                                                 "lit_qty" => phpaga_minutes2duration($h_lineitem["lit_qty"]),
                                                 "lit_unitnetprice" => null,
                                                 "lit_netprice" => sprintf("%01.2f", $h_lineitem["lit_netprice"]));

                $billInfo["bill_startsum"] += $h_lineitem["lit_netprice"];
            }

        }
        break;

    case ACTION_BILL_FROMPROJECT:
        $billInfo["bill_number"] = phpaga_bills_getNewInvoiceNumber();
        $billInfo["bill_date"] = date("Y-m-d");
        $billInfo["bmt_id"] = PHPAGA_DEFAULTBMT;


        $materials = array();
        $matinfo = array("prj_id" => null,
                         "unbilled" => true);

        if (isset($REQUEST_DATA["add_material"]) && isset($REQUEST_DATA["prj_id"]) && is_numeric($REQUEST_DATA["prj_id"])) {
            $matinfo["prj_id"] = $REQUEST_DATA["prj_id"];
            $materials = phpaga_materials_getmaterials($matinfo);

            if (PhPagaError::isError($materials))
                $materials->printMessage();
            else
            {
                if (count($materials) > 0)
                {
                    foreach ($materials as $mat) {

                        $h_desc = null;

                        if (isset($mat["mat_name"]) && strlen($mat["mat_name"]))
                            $h_desc .= $mat["mat_name"];


                        if (isset($mat["mat_desc"]) && strlen($mat["mat_desc"])) {

                            if (strlen($h_desc))
                                $h_desc .= " - ";

                            $h_desc .= $mat["mat_desc"];
                        }

                        $billInfo["lineitems"][] = array("mat_id" => $mat["mat_id"],
                                                         "op_id" => null,
                                                         "lit_prodcode" => $mat["mat_prodcode"],
                                                         "lit_desc" => $h_desc,
                                                         "lit_qty" => $mat["mat_qty"],
                                                         "lit_unitnetprice" => null,
                                                         "lit_netprice" => sprintf("%01.2f", $mat["mat_price"]));

                        $billInfo["bill_startsum"] += $mat["mat_price"];
                    }

                }

            }
        }

        if (isset($REQUEST_DATA["add_expenses"]) && isset($REQUEST_DATA["prj_id"]) && is_numeric($REQUEST_DATA["prj_id"])) {
            $expinfo["prj_id"] = $REQUEST_DATA["prj_id"];
            $expinfo["bill_id"] = null;

            $expenses = phpaga_expenses_getexpenses($expinfo);

            if (PhPagaError::isError($expenses))
                $expenses->printMessage();
            else {
                $billInfo["expenses"] = $expenses;

                if (count($expenses) > 0) {
                    foreach ($expenses as $exp)
                        $expensesum += $exp["exp_sum"];
                }
            }
        }

        /* get search criteria for related operations */

        if (isset($REQUEST_DATA["add_manhours"]) && isset($REQUEST_DATA["prj_id"]) && is_numeric($REQUEST_DATA["prj_id"])) {

            $billInfo["taskassociation"] = PHPAGA_BILL_TASKASSOC_LOCKED;

            $opInfo["prj_id"] = $REQUEST_DATA["prj_id"];
            $opInfo["op_billabletype"] = 0;
            $opInfo["op_billed"] = PHPAGA_BILL_NOTBILLED;

            $oprows = phpaga_operations_search($count, $duration, $opIds, $opInfo);

            if (count($oprows) > 0) {
                if (isset($REQUEST_DATA["singlemulti"]) && ($REQUEST_DATA["singlemulti"] == 1)) {

                    $h_amount = 0;
                    $h_prodcode = null;

                    foreach ($oprows as $op) {

                        if ($op["op_billabletype"] == 0)
                            $h_amount += $op["amount"];

                        if (!strlen($h_prodcode) && isset($op["prj_title"]) && strlen($op["prj_title"])) {
                            $h_prodcode = $op["prj_title"];
                            if (phpaga_strlen($h_prodcode > 18))
                                $h_prodcode = phpaga_substr($h_prodcode, 0, 18);
                        }
                    }

                    $billInfo["bill_startsum"] += $h_amount;

                    $billInfo["lineitems"][] = array("op_id" => "-1",
                                                     "mat_id" => null,
                                                     "lit_prodcode" => $h_prodcode,
                                                     "lit_desc" => null,
                                                     "lit_qty" => $duration,
                                                     "lit_unitnetprice" => null,
                                                     "lit_netprice" => sprintf("%01.2f", $h_amount));

                } else {

                    foreach ($oprows as $op) {
                        $_pc = null;
                        if (isset($op["prj_title"]) && strlen($op["prj_title"])) {
                            $_pc = $op["prj_title"];
                            if (phpaga_strlen($_pc) > 18)
                                $_pc = phpaga_substr($_pc, 0, 18);
                        }
                        $billInfo["lineitems"][] = array("op_id" => $op["op_id"],
                            "mat_id" => null,
                            "lit_prodcode" => $_pc,
                            "lit_desc" => $op["op_desc"],
                            "lit_qty" => phpaga_minutes2duration($op["op_duration"]),
                            "lit_unitnetprice" => null,
                            "lit_netprice" =>  ($op["op_billabletype"] == 0) ? sprintf("%01.2f", $op["amount"]) : '0.00'

                        );

                        if ($op["op_billabletype"] == 0)
                            $billInfo["bill_startsum"] += $op["amount"];
                    }
                }
            }
        }

        _add_lineitems($billInfo["lineitems"]);

        break;

    default:
        $billInfo["bill_number"] = phpaga_bills_getNewInvoiceNumber();
        $billInfo["bill_date"] = date("Y-m-d");
        $billInfo["bmt_id"] = PHPAGA_DEFAULTBMT;
        break;
    }

    /* Check if all billInfo fields are valid - but only if we're not
     * coming from another page. */
    if (isset($REQUEST_DATA['action']) && ($REQUEST_DATA['action'] != ACTION_BILL_WITHOPERATIONS)) {
        $result = phpaga_bills_checkInfo($billInfo);

        if (PhPagaError::isError($result))
            $billing_err = $result->getFormattedMessage();
    }
} else {
    $billInfo["bill_number"] = phpaga_bills_getNewInvoiceNumber();
    $billInfo["bill_date"] = date("Y-m-d");
    $billInfo["bmt_id"] = PHPAGA_DEFAULTBMT;
    _add_lineitems($billInfo["lineitems"]);
}

if (isset($billInfo["bmt_id"]) && is_numeric($billInfo["bmt_id"])
    && isset($billInfo["curr_id"]) && is_numeric($billInfo["curr_id"])
    && isset($billInfo["bill_startsum"]) && is_numeric($billInfo["bill_startsum"])) {

    $result = phpaga_bills_get_billing_details($billInfo["bmt_id"], $billInfo["curr_id"], $billInfo["bill_startsum"], $expensesum);

    if (PhPagaError::isError($result))
        $billing_err = $result->getFormattedMessage();
    else {
        $bill_endsum = $result->get_endsum();
        $bill_details = $result->get_details();
    }
}

phpaga_header(array("menuitem" => "finance"));

$select_company = phpaga_companies_getCompanyList();
phpaga_arrayAddOption($select_company, PHPAGA_OPTION_SELECT);

$select_currency = phpaga_currencies_getCurrencyList();
$select_bmt = phpaga_bills_getInvoiceTypeList();

if (count($opIds))
    $humancost = phpaga_operations_gethumancost($opIds);

if (PhPagaError::isError($oprows))
    $statusmsgarr[] = $oprows->getMessage();

if (isset($billInfo["cpn_id"]) && is_numeric($billInfo["cpn_id"])) {

    $persons = phpaga_persons_list($persons_count, null, $billInfo["cpn_id"]);

    foreach ($persons as $person)
        $h_pe[$person["pe_id"]] = $person["pe_person"];

    $persons = array("" => " ") + $h_pe;
}

$products = phpaga_products_search($prodcount, $prodIds, array());

$config = phpaga_config_get();

$tpl = new psmarty;
$tpl->assign("STATUSMSG", count($statusmsgarr) ? phpaga_returnmessage(_("Notice"), $statusmsgarr) : null);
$tpl->assign("select_cpn", $select_company);
$tpl->assign("select_bmt", $select_bmt);
$tpl->assign("select_curr", $select_currency);
$tpl->assign("select_rbilltypes", $phpaga_rbill_types);
$tpl->assign("billinfo", $billInfo);
$tpl->assign("config", $config);
$tpl->assign("BILLING_ERR", $billing_err);
$tpl->assign("bill_details", $bill_details);
$tpl->assign("humancost", $humancost);
$tpl->assign("expenses", $expenses);
$tpl->assign("operations", $oprows);
$tpl->assign("products", $products);
$tpl->assign("persons", $persons);
$tpl->assign("TOTALHOURS", $duration);

$tpl->display("add_bill.tpl.html");

phpaga_footer ();

?>
