<?php
/**
 * phpaga
 *
 * Company management functionality.
 *
 * This file contains the necessary routines to manage companies.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @version $Id: companies.php 878 2007-10-31 22:11: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.
 */


/**
 * Gets a list of companies from the database and returns them as an
 * array.
 *
 * @return array  $cpnList  Array of companies. A PhPagaError object on failure.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.1
 */

function phpaga_companies_getCompanyList()
{
    $cpnList = array();

    $d = new PhPagaDbData;

    $r = $d->queryAll('SELECT cpn_id, cpn_name, cpn_city FROM companies ORDER BY cpn_name');

    if (PhPagaError::isError($r))
        return $r;

    foreach ($r as $qrow) {

        $tmp = $qrow['cpn_name'];

        if (isset($qrow['cpn_city']) && strlen($qrow['cpn_city']))
            $tmp .= ' ('.$qrow['cpn_city'].')';

        $cpnList[$qrow['cpn_id']] = $tmp;
    }

    return $cpnList;
}


/**
 * Gets a company's information
 *
 * @param int    $cpnID   Company ID
 *
 * @return array  $peInfo Array containing the results. A PhPagaError object on failure.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.1
 */

function phpaga_companies_getInfo($cpnID)
{
    $cpnInfo = array();
    $prjInfo = array();
    $billInfo = array();
    $rows = array();
    $count = 0;
    $summary = array();
    $offset = '';

    if (!isset($cpnID) || !is_numeric($cpnID))
        return PhPagaError::raiseErrorByCode(PHPAGA_ERR_COMPANY_INVALIDID);

    $query = 'SELECT companies.cpn_id, cpn_name, cpn_address, cpn_address2, cpn_city,
        cpn_zip, cpn_region, companies.ctr_id, cpn_defaultpayterm,
        ctr_name, ctr_code, cpn_logoname,
        companies.ccat_id, ccat_title, cpn_taxnr,
        cpn_url, cpn_phone, cpn_fax, cpn_email, cpn_owner_taxnr, companies.pe_id,
        p2.pe_lastname as owner_pe_lastname,
        p2.pe_firstname as owner_pe_firstname
        FROM companies
        LEFT JOIN companycat ON companycat.ccat_id = companies.ccat_id
        LEFT JOIN countries on countries.ctr_id = companies.ctr_id
        LEFT JOIN persons p2 ON p2.pe_id = companies.pe_id
        WHERE companies.cpn_id = ?';

    $d = new PhPagaDbData;
    $cpnInfo = $d->queryRow($query, $cpnID);

    if (PhPagaError::isError($cpnInfo) || !count($cpnInfo))
        return $cpnInfo;

    $cpnInfo['location'] = phpaga_getLocation($cpnInfo['cpn_city'], $cpnInfo['cpn_region']);

    $cpnInfo['full_location'] = phpaga_getFullLocation($cpnInfo['cpn_city'],
                                                       $cpnInfo['cpn_region'],
                                                       $cpnInfo['cpn_zip'],
                                                       $cpnInfo['ctr_name']);

    $cpnInfo['owner_pe_person'] = phpaga_persons_formatname($cpnInfo['owner_pe_lastname'], $cpnInfo['owner_pe_firstname']);

    phpaga_sanitizeArray($cpnInfo);

    $billInfo = array('cpn_id' => $cpnID);

    $rows = phpaga_bills_search($count, $billInfo);

    if (!PhPagaError::isError($rows))
        $cpnInfo['bills'] = $rows;

    $quotInfo = array('cpn_id' => $cpnID);

    $rows = phpaga_quotations_search($count, $quotInfo);

    if (!PhPagaError::isError($rows))
        $cpnInfo['quotations'] = $rows;

    $prjInfo['cpn_id'] = $cpnID;

    $rows = phpaga_projects_search($count, $duration, $prjIds, $prjInfo);

    if (!PhPagaError::isError($rows))
        $cpnInfo['projects'] = $rows;
    else
        return PhPagaError::raiseErrorByCode($result);

    $summary = phpaga_bills_getSummaryCpn($cpnID);

    if (!PhPagaError::isError($summary))
        $cpnInfo['billing_summary'] = $summary;
    else
        return PhPagaError::raiseErrorByCode($result);

    return $cpnInfo;
}


/**
 * Gets a list of company categories from the database and returns
 * them as the content of an array.
 *
 * @return array $result    Array containing the results. A PhPagaError object on failure.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.3
 */

function phpaga_companies_getCategories()
{
    $ccatList = array();

    $d = new PhPagaDbData;

    $r = $d->queryAll('SELECT ccat_id, ccat_title FROM companycat ORDER BY ccat_title');

    if (PhPagaError::isError($r))
        return $r;

    foreach ($r as $qrow)
        $ccatList[$qrow['ccat_id']] = $qrow['ccat_title'];

    return $ccatList;
}


/**
 * Checks if all fields of a company contain valid values.
 *
 * @param  array  $cpnInfo  Array containing the company's information.
 *
 * @return bool   $r        True. A PhPagaError object on failure.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.1
 */

function phpaga_companies_validdata($cpnInfo)
{

    $errors = array();

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

    if (isset($cpnInfo['cpn_email']) && strlen($cpnInfo['cpn_email'])
        && !phpaga_checkemailaddress($cpnInfo['cpn_email']))
        $errors[] = PHPAGA_ERR_INVALID_EMAIL;

    if (!isset($cpnInfo['cpn_name']) || !strlen($cpnInfo['cpn_name']))
        $errors[] = PHPAGA_ERR_COMPANY_INVALIDNAME;

    if (isset($cpnInfo['ctr_id']) && !is_numeric($cpnInfo['ctr_id']))
        $errors[] = PHPAGA_ERR_COUNTRY_INVALIDID;

    if (isset($cpnInfo['ccat_id']) && !is_numeric($cpnInfo['ccat_id']))
        $errors[] = PHPAGA_ERR_CCAT_INVALIDID;

    if (isset($cpnInfo['pe_id']) && !is_numeric($cpnInfo['pe_id']))
        $errors[] = PHPAGA_ERR_PERSON_INVALIDID;

    if (count($errors))
        return PhPagaError::raiseErrorByCode($errors);

    return true;
}


/**
 * Adds a company to the database
 *
 * @param array  $cpnInfo  Array containing the company information
 *
 * @return int   $result  ID of the freshly inserted company. A PhPagaError object on failure.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.1
 */

function phpaga_companies_add($cpnInfo)
{

    $result = phpaga_companies_validdata($cpnInfo);

    if (PhPagaError::isError($result))
        return $result;

    $d = new PhPagaDbData;

    $cpn_id = $d->nextId('companies_cpn_id');

    if (!isset($cpnInfo['cpn_name']) || !strlen($cpnInfo['cpn_name']))
        $cpnInfo['cpn_name'] = null;

    if (!isset($cpnInfo['cpn_address']) || !strlen($cpnInfo['cpn_address']))
        $cpnInfo['cpn_address'] = null;

    if (!isset($cpnInfo['cpn_address2']) || !strlen($cpnInfo['cpn_address2']))
        $cpnInfo['cpn_address2'] = null;

    if (!isset($cpnInfo['cpn_city']) || !strlen($cpnInfo['cpn_city']))
        $cpnInfo['cpn_city'] = null;

    if (!isset($cpnInfo['cpn_zip']) || !strlen($cpnInfo['cpn_zip']))
        $cpnInfo['cpn_zip'] = null;

    if (!isset($cpnInfo['cpn_region']) || !strlen($cpnInfo['cpn_region']))
        $cpnInfo['cpn_region'] = null;

    if (!isset($cpnInfo['cpn_taxnr']) || !strlen($cpnInfo['cpn_taxnr']))
        $cpnInfo['cpn_taxnr'] = null;

    if (!isset($cpnInfo['cpn_url']) || !strlen($cpnInfo['cpn_url']))
        $cpnInfo['cpn_url']  = null;

    if (!isset($cpnInfo['cpn_phone']) || !strlen($cpnInfo['cpn_phone']))
        $cpnInfo['cpn_phone'] = null;

    if (!isset($cpnInfo['cpn_fax']) || !strlen($cpnInfo['cpn_fax']))
        $cpnInfo['cpn_fax'] = null;

    if (!isset($cpnInfo['cpn_email']) || !strlen($cpnInfo['cpn_email']))
        $cpnInfo['cpn_email'] = null;

    if (!isset($cpnInfo['cpn_defaultpayterm']) || !strlen($cpnInfo['cpn_defaultpayterm']))
        $cpnInfo['cpn_defaultpayterm'] = null;

    $fields = array('cpn_id' => $cpn_id,
                    'cpn_name' => $cpnInfo['cpn_name'],
                    'cpn_address' => $cpnInfo['cpn_address'],
                    'cpn_address2' => $cpnInfo['cpn_address2'],
                    'cpn_city' => $cpnInfo['cpn_city'],
                    'cpn_zip' => $cpnInfo['cpn_zip'],
                    'cpn_region' => $cpnInfo['cpn_region'],
                    'ctr_id' => $cpnInfo['ctr_id'],
                    'ccat_id' => $cpnInfo['ccat_id'],
                    'cpn_taxnr' => $cpnInfo['cpn_taxnr'],
                    'cpn_url' => $cpnInfo['cpn_url'],
                    'cpn_phone' => $cpnInfo['cpn_phone'],
                    'cpn_fax' => $cpnInfo['cpn_fax'],
                    'cpn_email' => $cpnInfo['cpn_email'],
                    'pe_id' => $cpnInfo['pe_id'],
                    'cpn_defaultpayterm' => $cpnInfo['cpn_defaultpayterm']
        );

    $r = $d->insert('companies', $fields);

    if (PhPagaError::isError($r))
        return $r;

    return $cpn_id;
}


/**
 * Updates a company.
 *
 * @param array   $cpnInfo Array containing the company information
 *
 * @return bool   $result  True, or PhPagaError
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.1
 */

function phpaga_companies_update($cpnInfo)
{

    $result = phpaga_companies_validdata($cpnInfo);

    if (PhPagaError::isError($result))
        return $result;

    if (!isset($cpnInfo['cpn_name']) || !strlen($cpnInfo['cpn_name']))
        $cpnInfo['cpn_name'] = null;

    if (!isset($cpnInfo['cpn_address']) || !strlen($cpnInfo['cpn_address']))
        $cpnInfo['cpn_address'] = null;

    if (!isset($cpnInfo['cpn_address2']) || !strlen($cpnInfo['cpn_address2']))
        $cpnInfo['cpn_address2'] = null;

    if (!isset($cpnInfo['cpn_city']) || !strlen($cpnInfo['cpn_city']))
        $cpnInfo['cpn_city'] = null;

    if (!isset($cpnInfo['cpn_zip']) || !strlen($cpnInfo['cpn_zip']))
        $cpnInfo['cpn_zip'] = null;

    if (!isset($cpnInfo['cpn_region']) || !strlen($cpnInfo['cpn_region']))
        $cpnInfo['cpn_region'] = null;

    if (!isset($cpnInfo['cpn_taxnr']) || !strlen($cpnInfo['cpn_taxnr']))
        $cpnInfo['cpn_taxnr'] = null;

    if (!isset($cpnInfo['cpn_url']) || !strlen($cpnInfo['cpn_url']))
        $cpnInfo['cpn_url']  = null;

    if (!isset($cpnInfo['cpn_phone']) || !strlen($cpnInfo['cpn_phone']))
        $cpnInfo['cpn_phone'] = null;

    if (!isset($cpnInfo['cpn_fax']) || !strlen($cpnInfo['cpn_fax']))
        $cpnInfo['cpn_fax'] = null;

    if (!isset($cpnInfo['cpn_email']) || !strlen($cpnInfo['cpn_email']))
        $cpnInfo['cpn_email'] = null;

    if (!isset($cpnInfo['cpn_defaultpayterm']) || !strlen($cpnInfo['cpn_defaultpayterm']))
        $cpnInfo['cpn_defaultpayterm'] = null;

    $fields = array('cpn_name' => $cpnInfo['cpn_name'],
                    'cpn_address' => $cpnInfo['cpn_address'],
                    'cpn_address2' => $cpnInfo['cpn_address2'],
                    'cpn_city' => $cpnInfo['cpn_city'],
                    'cpn_zip' => $cpnInfo['cpn_zip'],
                    'cpn_region' => $cpnInfo['cpn_region'],
                    'ctr_id' => $cpnInfo['ctr_id'],
                    'ccat_id' => $cpnInfo['ccat_id'],
                    'cpn_taxnr' => $cpnInfo['cpn_taxnr'],
                    'cpn_url' => $cpnInfo['cpn_url'],
                    'cpn_phone' => $cpnInfo['cpn_phone'],
                    'cpn_fax' => $cpnInfo['cpn_fax'],
                    'cpn_email' => $cpnInfo['cpn_email'],
                    'cpn_defaultpayterm' => $cpnInfo['cpn_defaultpayterm']
        );

    $d = new PhPagaDbData;
    $r = $d->update('companies', $fields, 'cpn_id = ?', array($cpnInfo['cpn_id']));

    if (PhPagaError::isError($r))
        return $r;

    return true;
}


/**
 * Loads all company categories into an array.
 *
 * @return array $result    Array containing the results. A PhPagaError object on failure.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.1
 */

function phpaga_companies_getCpncats()
{
    $ccatInfo = array();

    $d = new PhPagaDbData;

    $ccatInfo = $d->queryAll('SELECT ccat_id, ccat_title FROM companycat ORDER BY ccat_title');

    return $ccatInfo;
}


/**
 * Add a new company category.
 *
 * @param  string  $ccat_title   Company category to be added
 *
 * @return int     $id           Category Id or a PhPagaError.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.1
 */

function phpaga_companies_addCpncat($ccat_title)
{

    if (!isset($ccat_title) || !strlen($ccat_title))
        return PhPagaError::raiseErrorByCode(PHPAGA_ERR_CCAT_INVALIDTITLE);

    $d = new PhPagaDbData;

    $id = $d->nextId('companycat_ccat_id');

    $r = $d->insert('companycat', array('ccat_id' => $id,
                                        'ccat_title' => $ccat_title));

    if (PhPagaError::isError($r))
        return $r;

    return $id;
}


/**
 * Delete a company category.
 *
 * First check if this category is needed by any table relationship;
 * delete it only if it is not needed.
 *
 * @param  int     $ccat_id     Company category to be deleted
 *
 * @return bool    $result      True if successful, PhPagaError otherwise.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.1
 */

function phpaga_companies_deleteCpncat($ccat_id)
{
    if (!isset($ccat_id) || !is_numeric($ccat_id))
        return PhPagaError::raiseErrorByCode(PHPAGA_ERR_CCAT_INVALIDID);

    $d = new PhPagaDbData;

    $n = $d->queryOneVal('SELECT COUNT(cpn_id) FROM companies WHERE ccat_id = ?', $ccat_id);

    if (PhPagaError::isError($n))
        return $n;

    if ($n > 0)
        return PhPagaError::raiseErrorByCode(PHPAGA_ERR_DEL_DEPENDENCIES);

    $result = $d->execute('DELETE FROM companycat WHERE ccat_id = ?', $ccat_id);

    if (PhPagaError::isError($result))
        return $result;

    return true;

}


/**
 * Delete a company. A company can only be deleted if there are no
 * dependencies left.
 *
 * @param  int     $cpn_id      Company ID
 *
 * @return bool    $result      True if successfull, PhPagaError otherwise.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.3
 */

function phpaga_companies_delete($cpn_id)
{
    if (!isset($cpn_id) || !is_numeric($cpn_id))
        return PhPagaError::raiseErrorByCode(PHPAGA_ERR_BILL_INVALID_CPNID);

    $d = new PhPagaDbData;

    /* Check, if this company is needed by any table relationship if
     * it is not needed, then delete it, otherwise don't */

    $depqueries = array('SELECT COUNT(cpn_id) FROM bills WHERE cpn_id = ?',
                        'SELECT COUNT(cpn_id) FROM quotations WHERE cpn_id = ?',
                        'SELECT COUNT(cpn_id) FROM persons WHERE cpn_id = ?');

    foreach ($depqueries as $dpq) {

        $n = $d->queryOneVal($dpq, $cpn_id);

        if (PhPagaError::isError($n))
            return $n;

        if ($n > 0)
            return PhPagaError::raiseErrorByCode(PHPAGA_ERR_DEL_DEPENDENCIES);
    }

    $n = $d->queryOneVal('SELECT COUNT(cpn_id) FROM projects WHERE cpn_id = ? OR cpn_id_issuebill = ?',
                         array($cpn_id, $cpn_id));

    if (PhPagaError::isError($n))
        return $n;

    if ($n > 0)
        return PhPagaError::raiseErrorByCode(PHPAGA_ERR_DEL_DEPENDENCIES);

    $result = $d->execute('DELETE FROM companies WHERE cpn_id = ?', $cpn_id);

    if (PhPagaError::isError($result))
        return $result;

    return true;
}


/**
 * Gets all companies matching the search parmeters (from $offset to
 * $limit, if set)
 *
 * @param int    $count     Number of records matching the query
 * @param array  $cpnInfo   Company information
 * @param array  $cpnIds    IDs of the resulting companies
 * @param int    $order     Specifies the order by field
 * @param int    $offset    Offset (optional)
 * @param int    $limit     Limit (optional)
 *
 * @return array $rows      Array containing the results. A PhPagaError object on failure.
 *
 * @author Mark Parssey <markpa@users.sourceforge.net>
 * @since phpaga 0.3
 */

function phpaga_companies_search(&$count,
                                 &$cpnIds,
                                 $cpnInfo,
                                 $order = 0,
                                 $offset = null,
                                 $limit = null)
{

    $count = 0;
    $rows = array();
    $cpnIds = array();
    $where = array();
    $where_clause = null;
    $qparam = array();

    /* how many matching records are there */

    $countquery = 'SELECT COUNT(cpn_id) AS count_cpn '.'FROM companies ';

    /* select limited number of records */

    $query = 'SELECT cpn_id, cpn_name, cpn_address, cpn_address2, cpn_city,
        cpn_region, cpn_zip, companies.ctr_id, ctr_name, ctr_code,
        companies.ccat_id, ccat_title, cpn_taxnr, cpn_url,
        cpn_phone, cpn_fax, cpn_email, cpn_owner_taxnr, pe_id
        FROM companies
        LEFT JOIN companycat ON companycat.ccat_id = companies.ccat_id
        LEFT JOIN countries ON countries.ctr_id = companies.ctr_id ';

    /* collect elements of the where clause */

    if (isset($cpnInfo['cpn_name']) && strlen($cpnInfo['cpn_name'])) {
        $where[] = 'companies.cpn_name LIKE ?';
        $qparam[] = '%'.$cpnInfo['cpn_name'].'%';
    }

    if (isset($cpnInfo['cpn_address']) && strlen($cpnInfo['cpn_address'])) {
        $where[] = 'companies.cpn_address LIKE ?';
        $qparam[] = '%'.$cpnInfo['cpn_address'].'%';
    }

    if (isset($cpnInfo['cpn_address2']) && strlen($cpnInfo['cpn_address2'])) {
        $where[] = 'companies.cpn_address2 LIKE ?';
        $qparam[] = '%'.$cpnInfo['cpn_address2'].'%';
    }

    if (isset($cpnInfo['cpn_city']) && strlen($cpnInfo['cpn_city'])) {
        $where[] = 'companies.cpn_city LIKE ?';
        $qparam[] = '%'.$cpnInfo['cpn_city'].'%';
    }

    if (isset($cpnInfo['cpn_zip']) && strlen($cpnInfo['cpn_zip'])) {
        $where[] = 'companies.cpn_zip LIKE ?';
        $qparam[] = '%'.$cpnInfo['cpn_zip'].'%';
    }

    if (isset($cpnInfo['cpn_region']) && strlen($cpnInfo['cpn_region'])) {
        $where[] = 'companies.cpn_region LIKE ?';
        $qparam[] = '%'.$cpnInfo['cpn_region'].'%';
    }

    if (isset($cpnInfo['ctr_id']) && is_numeric($cpnInfo['ctr_id'])) {
        $where[] = 'companies.ctr_id = ?';
        $qparam[] = $cpnInfo['ctr_id'];
    }

    if (isset($cpnInfo['ccat_id']) && is_numeric($cpnInfo['ccat_id'])) {
        $where[] = 'companies.ccat_id = ?';
        $qparam[] = $cpnInfo['ccat_id'];
    }

    if (isset($cpnInfo['cpn_email']) && ($cpnInfo['cpn_email'])) {
        $where[] = 'companies.cpn_email LIKE ?';
        $qparam[] = '%'.$cpnInfo[''].'%';
    }

    /* build the where clause */
    if (count($where) > 0)
    {
        $h = sprintf('WHERE %s ', implode(' AND ', $where));
        $query .= $h;
        $countquery .= $h;
    }

    $query .= ' ORDER BY ';

    /* build the order-by clause */
    /* check validity of order value, eventually set it to default  */

    if (($order == '') || ($order == 0) || !is_numeric($order))
        $order = ORDER_CPN_NAME_ASC;

    switch ($order)
    {
        case ORDER_CPN_NAME_ASC:
            $query .= 'cpn_name ASC';
            break;
        case ORDER_CPN_NAME_DESC:
            $query .= 'cpn_name DESC';
            break;
        case ORDER_CPN_ADDRESS_ASC:
            $query .= 'cpn_address ASC';
            break;
        case ORDER_CPN_ADDRESS_DESC:
            $query .= 'cpn_address DESC';
            break;
        case ORDER_CPN_CITY_ASC:
            $query .= 'cpn_city ASC';
            break;
        case ORDER_CPN_CITY_DESC:
            $query .= 'cpn_city DESC';
            break;
        case ORDER_CPN_COUNTRY_ASC:
            $query .= 'ctr_name ASC';
            break;
        case ORDER_CPN_COUNTRY_DESC:
            $query .= 'ctr_name DESC';
            break;
        case ORDER_CPN_CCAT_ASC:
            $query .= 'ccat_title ASC';
            break;
        case ORDER_CPN_CCAT_DESC:
            $query .= 'ccat_title DESC';
            break;
        case ORDER_CPN_EMAIL_ASC:
            $query .= 'cpn_email ASC';
            break;
        case ORDER_CPN_EMAIL_DESC:
            $query .= 'cpn_email DESC';
            break;
        default:
            $query .= 'cpn_name ASC';
            break;
    }

    $d = new PhPagaDbData;

    $count_cpn = $d->queryOneVal($countquery, $qparam);

    if (!PhPagaError::isError($count_cpn))
        $count = $count_cpn;

    $companies = $d->queryAll($query, $qparam, $offset, $limit);

    if (PhPagaError::isError($companies))
        return $companies;

    foreach($companies as $qrow) {

        phpaga_sanitizearray($qrow);

        $qrow['cpn_long_address'] = ($qrow['cpn_address']);
        if (isset($qrow['cpn_address2']) && strlen($qrow['cpn_address2']))
            $qrow['cpn_long_address'] .= "\n\r".$qrow['cpn_address2'];

        $rows[] = $qrow;
        $cpnIds[] = $qrow['cpn_id'];
    }

    phpaga_sanitizearray($rows);
    return $rows;
}


/**
 * Determine whether some person is the owner of a company record. If
 * pe_id is omitted, the current user's pe_id is used.
 *
 * @param int    $cpn_id    Company ID
 * @param int    $pe_id     Person ID (optional, if omitted, the
 *                          current user's pe_id is used)
 *
 * @return bool  $isowner   True or false
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.3
 */

function phpaga_companies_isowner($cpn_id, $pe_id = null)
{

    $isowner = false;

    if (($pe_id == null) && isset($_SESSION['auth_user']) && isset($_SESSION['auth_user']['pe_id'])
        && is_numeric($_SESSION['auth_user']['pe_id']))

        $pe_id = $_SESSION['auth_user']['pe_id'];

    $d = new PhPagaDbData;

    $cpnpe_id = $d->queryOneVal('SELECT pe_id FROM companies WHERE cpn_id = ?', $cpn_id);

    if (PhPagaError::isError($cpnpe_id))
        return $cpnpe_id;

    return ($cpnpe_id == $pe_id);
}


/**
 * Determine the default term of payment for a given company.
 *
 * @param int      $cpn_id    Company ID
 *
 * @return strong  $result    Default term of payment or null
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.3
 */

function phpaga_companies_getdefaultpayterm($cpn_id)
{

    if (!strlen($cpn_id) || !is_numeric($cpn_id))
        return null;

    $d = new PhPagaDbData;

    $r = $d->queryOneVal('SELECT cpn_defaultpayterm FROM companies WHERE cpn_id = ?', $cpn_id);

    if (PhPagaError::isError($r))
        return null;

    return $r;
}

?>