<?php
/**
 * phpaga
 *
 * quotations functionality.
 *
 * This file contains the necessary routines for quotations management.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @version $Id: quotations.php 653 2005-10-03 21:53:26Z worf $
 *
 * 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.
 */


/**
 * Checks if the quotation information is valid.
 *
 * @param  array   $quotInfo    Array containing billoing information
 * @return array   $errors      Array containing error codes
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.1
 */

function phpaga_quotations_checkInfo ($quotInfo)
{

    $errors = array();

    if (!is_array($quotInfo))
        $quotInfo = array($quotInfo);

    if (!isset($quotInfo["quot_number"]) || !strlen($quotInfo["quot_number"]))
        $errors[] = PHPAGA_ERR_QUOTATION_INVALID_NUMBER;

    if (!isset($quotInfo["quot_date"])
        || !phpaga_checkdate ($quotInfo["quot_date"], false))

        $errors[] = PHPAGA_ERR_QUOTATION_INVALID_DATE;

    if (!isset($quotInfo["cpn_id"]) || !is_numeric($quotInfo["cpn_id"]))
        $errors[] = PHPAGA_ERR_QUOTATION_INVALID_CPNID;

    if (!isset($quotInfo["bmt_id"]) || !is_numeric($quotInfo["bmt_id"]))
        $errors[] = PHPAGA_ERR_QUOTATION_INVALID_BMTID;

    if (!isset($quotInfo["curr_id"]) || !is_numeric($quotInfo["curr_id"]))
        $errors[] = PHPAGA_ERR_QUOTATION_INVALID_CURRID;

    if (!isset($quotInfo["quot_startsum"])
        || !is_numeric($quotInfo["quot_startsum"]))

        $errors[] = PHPAGA_ERR_QUOTATION_INVALID_STARTSUM;

    return $errors;
}


/**
 * Creates and inserts a new quotation.
 *
 * @param  array   $quotInfo    Array containing billing information
 * @param  int     $quotID      ID of the newly inserted quotation record
 * @return array   $errors      Array containing error codes
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.1
 */

function phpaga_quotations_add ($quotInfo,
                                &$quotID)
{

    $quotID = "";

    $result = phpaga_quotations_checkInfo($quotInfo);

    if (count($result) > 0)
        return PHPAGA_ERR_INSERT_DATA_INVALIDFORMAT;

    if (!isset($quotInfo["quot_payterm"]) || !strlen($quotInfo["quot_payterm"]))
        $quotInfo["quot_payterm"] = null;

    phpaga_db_connect($db);
    $quotID = $db->nextId("quotations_quot_id");

    $fields = array("quot_id" => $quotID,
                    "quot_number" => $quotInfo["quot_number"],
                    "quot_date" => $quotInfo["quot_date"],
                    "quot_payterm" => $quotInfo["quot_payterm"],
                    "cpn_id" => $quotInfo["cpn_id"],
                    "quot_sent" => PHPAGA_NO,
                    "quot_startsum" => $quotInfo["quot_startsum"],
                    "quot_endsum" => $quotInfo["quot_endsum"],
                    "bmt_id" => $quotInfo["bmt_id"],
                    "curr_id" => $quotInfo["curr_id"]
        );

    $result = $db->autoExecute("quotations", $fields, DB_AUTOQUERY_INSERT);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    /* insert line items */
    $fields = array("quot_id",
                    "lit_id",
                    "lit_prodcode",
                    "lit_desc",
                    "lit_qty",
                    "lit_netprice");

    $sth = $db->autoPrepare("lineitems", $fields,
                            DB_AUTOQUERY_INSERT);

    if (PEAR::isError($sth))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    foreach ($quotInfo["lineitems"] as $lit)
    {

        $val = array($quotID,
                     $db->nextId("lineitems_lit_id"),
                     $lit["lit_prodcode"],
                     $lit["lit_desc"],
                     $lit["lit_qty"],
                     $lit["lit_netprice"]);

        $res =& $db->execute($sth, $val);

        if (PEAR::isError($res))
            return PHPAGA_ERR_DB_EXEC_QUERY;
    }

    return PHPAGA_ERR_NONE;
}


/**
 * Generates a new quotation number for the current year.
 * This "number" can be any alphanumeric combination.
 *
 * @param  mixed $quotationNumber    An quotation number
 *
 * @return int   $result           A result code.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.1
 */

function phpaga_quotations_getNewQuotationNumber (&$quotationNumber)
{
    $quotationNumber = "";
    $quotnums = array();

    phpaga_db_connect($db);

    $query = "SELECT quot_id, quot_number ".
        "FROM quotations WHERE YEAR(quot_date) = YEAR(NOW()) ";

    $result = $db->getAssoc($query);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    if (count($result) == 0)
        $quotationNumber = 1;
    else
    {

        foreach($result as $dummy => $num)
            $quotnums[] = $num;

        natsort($quotnums);
        $quotnums = array_values($quotnums);
        $quotationNumber = $quotnums[count($quotnums) - 1];

        /* increase the existing quotation number by one; note that this
         * works also with alphanumeric strings */

        $quotationNumber++;
    }

    return PHPAGA_ERR_NONE;
}


/**
 * Search quotations matching search criteria.
 *
 * @param array  $rows      Array containing the results
 * @param int    $count     Number of records matching the query
 * @param array  $quotInfo  Quotation information
 * @param int    $offset    Offset
 * @param int    $limit     Limit
 *
 * @return int   $result  A result code.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.1
 */

function phpaga_quotations_search (&$rows,
                                   &$count,
                                   $quotInfo,
                                   $offset = "",
                                   $limit = "")
{
    $count = 0;
    $rows = array();
    $where = array();
    $where_clause = "";

    phpaga_db_connect($db);

    /* total number of matching records */

    $countquery = "SELECT COUNT(quot_id) AS count_quote "."FROM quotations ";

    /* select matching records from quotations */

    $query = "SELECT quot_id, quot_number, quot_date, ".
        "quotations.cpn_id, cpn_name, quot_sent, ".
        "quot_startsum, quot_endsum, quot_payterm, ".
        "quotations.bmt_id, quotations.curr_id, ".
        "curr_name, bmt_description ".
        "FROM quotations ".
        "LEFT JOIN companies ON companies.cpn_id = quotations.cpn_id ".
        "LEFT JOIN currencies ON currencies.curr_id = quotations.curr_id ".
        "LEFT JOIN billing_methods ON billing_methods.bmt_id = quotations.bmt_id ";

    /* collect elements of the where clause */

    if (isset($quotInfo["quot_id"]) && is_numeric($quotInfo["quot_id"]))
        $where[] = "quotations.quot_id = ".$db->quoteSmart($quotInfo["quot_id"]);

    if (isset($quotInfo["curr_id"]) && is_numeric($quotInfo["curr_id"]))
        $where[] = "quotations.curr_id = ".$db->quoteSmart($quotInfo["curr_id"]);

    if (isset($quotInfo["cpn_id"]) && is_numeric($quotInfo["cpn_id"]))
        $where[] = "quotations.cpn_id = ".$db->quoteSmart($quotInfo["cpn_id"]);

    if (isset($quotInfo["bmt_id"]) && is_numeric($quotInfo["bmt_id"]))
        $where[] = "quotations.bmt_id = ".$db->quoteSmart($quotInfo["bmt_id"]);

    if (isset($quotInfo["quot_sent"]) && is_numeric($quotInfo["quot_sent"]))
    {
        switch ($quotInfo["quot_sent"])
        {
            case PHPAGA_QUOTATION_NOTSENT:
                $where[] = "quotations.quot_sent IS NULL";
                break;

            case PHPAGA_QUOTATION_SENT:
                $where[] = "quotations.quot_sent IS NOT NULL";
                break;

            default:
                break;
        }
    }

    if (isset($quotInfo["quot_number"]) && strlen($quotInfo["quot_number"]))
        $where[] = "quotations.quot_number = ".$db->quoteSmart($quotInfo["quot_number"]);

    if (isset($quotInfo["quot_datefrom"])
        && phpaga_checkdate($quotInfo["quot_datefrom"], false))
    {
        $where[] = "quotations.quot_date >= ".$db->quoteSmart($quotInfo["quot_datefrom"]);
    }
    if (isset($quotInfo["quot_dateto"])
        && phpaga_checkdate($quotInfo["quot_dateto"], false))
    {
        $where[] = "quotations.quot_date <= ".$db->quoteSmart($quotInfo["quot_dateto"]);
    }

    if (isset($quotInfo["quot_year"]) && is_numeric($quotInfo["quot_year"]))
        $where[] = "YEAR(quotations.quot_date) = ".$db->quoteSmart($quotInfo["quot_year"]);

    /* build the where clause */

    if (count($where) > 0)
    {
        $where_clause .= "WHERE ".implode(" AND ", $where)." ";
        $query .= $where_clause;
        $countquery .= $where_clause;
    }

    $query .= " ORDER BY quot_date DESC, quot_number DESC ";

    /* first do the count stuff */

    $result = $db->query($countquery);

    if (($result != false) && ($result->numRows() > 0)
        && ($countrow = $result->fetchRow()))
    {
        $count = $countrow["count_quote"];
    }

    /* limit the number of results starting from $offset if both $offset
     * and $limit are set and valid */

    if (isset($offset) && is_numeric($offset) && isset($limit) &&
        is_numeric($limit) && ($limit > 0))

        $result = $db->limitQuery($query, $offset, $limit);
    else
        $result = $db->query($query);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    if ($result->numRows() > 0)
        while ($qrow = $result->fetchRow())
            $rows[] = $qrow;

    $result->free();
    return PHPAGA_ERR_NONE;
}


/**
 * Gets an quotation's information
 *
 * @param int    $quot_id   Invoice ID
 * @param array  $quotInfo  Invoice information
 *
 * @return int   $result  A result code.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.3
 */

function phpaga_quotations_getinfo ($quot_id, &$quotInfo)
{

    $quotInfo = array();

    phpaga_db_connect($db);

    $query = "SELECT quot_id, quot_number, quot_date, ".
        "quotations.cpn_id, cpn_name, quot_sent, quot_payterm, ".
        "quot_startsum, quot_endsum, quotations.bmt_id, ".
        "quotations.curr_id, curr_name, bmt_description ".
        "FROM quotations ".
        "LEFT JOIN companies ON companies.cpn_id = quotations.cpn_id ".
        "LEFT JOIN currencies ON currencies.curr_id = quotations.curr_id ".
        "LEFT JOIN billing_methods ON billing_methods.bmt_id = quotations.bmt_id ".
        "WHERE quot_id = ".$db->quoteSmart($quot_id);

    $result = $db->query($query);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    if (($result->numRows() > 0) && ($qrow = $result->fetchRow ()))
    {

        $quotInfo = $qrow;

        /* line items */

        $query = "SELECT lit_id, NULL as op_id, lit_prodcode, lit_desc, lit_qty, lit_netprice ".
            "FROM lineitems ".
            "WHERE quot_id = ".$db->quoteSmart($quot_id).
            "ORDER BY lit_id";

        $litres = $db->query($query);

        if (DB::isError($litres))
            return PHPAGA_ERR_DB_EXEC_QUERY;

        $quotInfo["lineitems"] = array();

        while ($qrow = $litres->fetchRow ()) {
            $qrow["lit_netprice_format"] = phpaga_formatamount((float)$qrow["lit_netprice"]);
            $quotInfo["lineitems"][] = $qrow;
        }

        /* calculation detail */

        $quotInfo["quot_details"] = array();

        $plres = phpaga_bills_includebmtPlugin($quotInfo["bmt_id"]);

        if ($plres != PHPAGA_ERR_NONE)
            return $plres;

        $endsum = 0;
        $bcres = phpaga_bill_calculate($quotInfo["quot_startsum"],
                                       $quotInfo["curr_id"], $endsum, $details);

        if ($bcres != PHPAGA_ERR_NONE)
            return $bcres;

        $quotInfo["quot_details"] = $details->details;

    }

    $result->free();
    return PHPAGA_ERR_NONE;
}

/**
 * Deletes a quotation. This is only possible if no depending records
 * exists.
 *
 * @param  int     $quot_id     ID of the quotation
 *
 * @return int     $result      A result code.
 *
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.3
 */

function phpaga_quotations_delete ($quot_id)
{

    if (!isset($quot_id) || !is_numeric($quot_id))
        return PHPAGA_ERR_INVALID_QUOTATIONID;

    phpaga_db_connect($db);

    $query = "SELECT prj_id ".
        "FROM projects ".
        "WHERE quot_id = ".$db->quoteSmart($quot_id);

    if (phpaga_db_transaction_begin($db) != PHPAGA_ERR_NONE)
        return PHPAGA_ERR_DB_TRANSACTBEGIN;

    $result = $db->query($query);
    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    if ($result->numRows() > 0)
        return PHPAGA_ERR_DEL_DEPENDENCIES;

    $query = "DELETE FROM lineitems WHERE quot_id = ".
        $db->quoteSmart($quot_id);

    $result = $db->query($query);

    if (DB::isError($result))
        if (phpaga_db_transaction_rollback($db) != PHPAGA_ERR_NONE)
            return PHPAGA_ERR_DB_TRANSACTROLLBACK;
        else
            return PHPAGA_ERR_DB_EXEC_QUERY;

    $query = "DELETE FROM quotations WHERE quot_id = ".
        $db->quoteSmart($quot_id);

    $result = $db->query($query);
    if (DB::isError($result))
        if (phpaga_db_transaction_rollback($db) != PHPAGA_ERR_NONE)
            return PHPAGA_ERR_DB_TRANSACTROLLBACK;
        else
            return PHPAGA_ERR_DB_EXEC_QUERY;

    if (phpaga_db_transaction_commit($db) != PHPAGA_ERR_NONE)
        return PHPAGA_ERR_DB_TRANSACTCOMMIT;

    return PHPAGA_ERR_NONE;
}

?>