<?php
/**
 * phpaga
 *
 * Add quotation
 *
 * This is the interface to create a new quotation.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @version $Id: add_quotation.php 864 2007-09-28 21:03:00Z florian $
 *
 * Copyright (c) 2002, 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_QUOTATIONS);

$select_bmt = array();
$select_currencies = array();
$h_pe = array();

$quotInfo = array(
    "quot_number" => "",
    "quot_date" => "",
    "quot_payterm" => "",
    "cpn_id" => "",
    "pe_id_recipient" => "1",
    "bmt_id" => "",
    "curr_id" => PHPAGA_DEFAULTCURRENCY,
    "quot_startsum" => 0,
    "lineitems" => array());

$quot_id = "";
$quoting_err = "";
$quot_endsum = null;
$quot_details = null;

$products = null;
$prodcount = 0;
$prodIds = null;

$persons = array();
$persons_count = 0;


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

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

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

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

        $quotInfo["quot_number"] = phpaga_quotations_getNewQuotationNumber();

        /* overwrite old quotation's date with current date */
        $quotInfo["quot_date"] = date("Y-m-d");

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

    if (isset($_REQUEST["quot_number"]) && strlen($_REQUEST["quot_number"]))
        $quotInfo["quot_number"] = $_REQUEST["quot_number"];

    if (isset($_REQUEST["quot_date"]) && strlen($_REQUEST["quot_date"]))
        $quotInfo["quot_date"] = $_REQUEST["quot_date"];

    if (isset($_REQUEST["quot_payterm"]) && strlen($_REQUEST["quot_payterm"]))
        $quotInfo["quot_payterm"] = $_REQUEST["quot_payterm"];

    if (isset($_REQUEST["cpn_id"]) && is_numeric($_REQUEST["cpn_id"])) {
        $quotInfo["cpn_id"] = $_REQUEST["cpn_id"];

        if (isset($_REQUEST["pe_id_recipient"]) && is_numeric($_REQUEST["pe_id_recipient"]))
            $quotInfo["pe_id_recipient"] = $_REQUEST["pe_id_recipient"];
    }

    if (isset($_REQUEST["bmt_id"]) && is_numeric($_REQUEST["bmt_id"]))
        $quotInfo["bmt_id"] = $_REQUEST["bmt_id"];

    if (isset($_REQUEST["curr_id"]) && is_numeric($_REQUEST["curr_id"]))
        $quotInfo["curr_id"] = $_REQUEST["curr_id"];

    /* line items */

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

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

            if (isset($_REQUEST["lit_prodcode"][$x]) && strlen($_REQUEST["lit_prodcode"][$x]))
                $h_lit_prodcode = $_REQUEST["lit_prodcode"][$x];

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

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

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

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

            if (is_numeric($h_lit_netprice))
                $quotInfo["quot_startsum"] += $h_lit_netprice;

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

                $quotInfo["lineitems"][] = array("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);

        }
    }

    switch($_REQUEST["action"])
    {
    case ACTION_QUOTATION_MAKEIT:

        /* include_once the appropriate billing method plugin */
        $result = phpaga_bills_includebmtPlugin($quotInfo["bmt_id"]);

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

                /* check if all quotInfo fields are valid */
                $result = phpaga_quotations_checkInfo($quotInfo);

                if (PhPagaError::isError($result))
                    $quoting_err = $result->getFormattedMessage();
                else
                {
                    /* now we should do our fine calculation with the billing
                     * method plugin */

                    phpaga_bill_calculate($quotInfo["quot_startsum"],
                                          $quotInfo["curr_id"],
                                          $quotInfo["quot_endsum"],
                                          $h_details);

                    /* we should be ready to insert the quotation record */

                    $quot_id = phpaga_quotations_add($quotInfo);

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

        case ACTION_BILL_RECALC:
        case ACTION_BILL_ADDLINEITEMS:

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

            break;

        default:
            $quotInfo["quot_number"] = phpaga_quotations_getNewQuotationNumber();
            $quotInfo["quot_date"] = date("Y-m-d");
            $quotInfo["bmt_id"] = PHPAGA_DEFAULTBMT;
            break;

    }

    /* check if all quotInfo fields are valid */
    $result = phpaga_quotations_checkInfo($quotInfo);

    if (PhPagaError::isError($result))
        $quoting_err = $result->getFormattedMessage();
}
else
{
    $quotInfo["quot_number"] = phpaga_quotations_getNewQuotationNumber();
    $quotInfo["quot_date"] = date("Y-m-d");
    $quotInfo["bmt_id"] = PHPAGA_DEFAULTBMT;
    _add_lineitems($quotInfo["lineitems"]);
}

if (isset($quotInfo["bmt_id"]) && is_numeric($quotInfo["bmt_id"])
    && isset($quotInfo["curr_id"]) && is_numeric($quotInfo["curr_id"])
    && isset($quotInfo["quot_startsum"]) && is_numeric($quotInfo["quot_startsum"]))
{
    /* include_once billing method plugin */
    $result = phpaga_bills_includebmtPlugin($quotInfo["bmt_id"]);
    if (PhPagaError::isError($result))
        $quoting_err = $result->getFormattedMessage();
    else
    {
        /* now we should do our fine calculation with the billing
         * method plugin */
        phpaga_bill_calculate($quotInfo["quot_startsum"],
                              $quotInfo["curr_id"],
                              $quot_endsum,
                              $quot_details);
    }

}

phpaga_header(array("calendar" => true, "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 (isset($quotInfo["cpn_id"]) && is_numeric($quotInfo["cpn_id"])) {

    $persons = phpaga_persons_list($persons_count, null, $quotInfo["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());

$tpl = new psmarty;

$tpl->assign("select_bmt", $select_bmt);
$tpl->assign("select_curr", $select_currency);
$tpl->assign("select_cpn", $select_company);
$tpl->assign("quotInfo", $quotInfo);
$tpl->assign("quot_details", $quot_details->details);
$tpl->assign("FORM_ACTION", basename($_SERVER["PHP_SELF"]));
$tpl->assign("QUOTATION_ERR", $quoting_err);
$tpl->assign("products", $products);
$tpl->assign("persons", $persons);

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

phpaga_footer();

?>