<?php
/**
 * phpaga
 *
 * Payments functionality.
 *
 * This file contains the necessary routines to manage payments.
 *
 * @author Michael Kimmick <support@nichewares.com>
 * @version $Id$
 *
 * Copyright (c) 2008, Michael Kimmick <support@nichewares.com>
 *
 * 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.
 */


/**
 * Deletes a payment
 */
function phpaga_payment_delete($pmt_id, $bill_id) {
    if (!isset($bill_id) || !is_numeric($bill_id))
        return PhPagaError::raiseErrorByCode(PHPAGA_ERR_PMT_INVALID_BILL_ID);

    if (!isset($pmt_id) || !is_numeric($bill_id))
	return PhPagaError::raiseErrorByCode(PHPAGA_ERR_INVALID_PAYMENTID);

    $d = new PhPagaDbData;

    /* check for dependencies: a payment cannot be deleted if it the bill has a pay_date
     * i.e. payment has already been completed */

    $depqueries = 'SELECT COUNT(bill_id) FROM bills WHERE bill_id = ? AND bill_paydate IS NOT NULL';


    $n = $d->queryOneVal($depqueries, $bill_id);

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

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

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

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

    return true;

}


/**
 * Gets a specific invoice's information
 *
 * @author Michael Kimmick <support@nichewares.com>
 */
function phpaga_payment_getinfo($pmt_id)
{
    /* Get data for an individual payment */
    $pmt = array();

    $query = 'Select *
	FROM payments
	WHERE pmt_id=?';

	$d = new PhPagaDbData;
	$pmt = $d->queryRow($query, $pmt_id);

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

    return $pmt;
}

/**
 * Gets an invoice's payments information
 *
 * @param int    $bill_id   Invoice ID
 *
 * @return array $peInfo Array containing the results. A PhPagaError object on failure.
 *
 * @author Michael Kimmick <support@nichewares.com>
 */

function phpaga_bills_getPmtinfo($bill_id)
{
    /* Collect Individual Payments for given bill_id */
    $pmts = array();

    $query = 'SELECT pmt_id, bill_id, pmt_amt, pmt_date, pmt_note
	FROM payments
        WHERE bill_id = ?';

    $d = new PhPagaDbData;
    $pmts = $d->queryAll($query, $bill_id);

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

    /* Calculate sum of payments for given bill_id */
    $pmtSum = array();

    $query = 'Select sum(pmt_amt) as pmt_sum
	FROM payments
	WHERE bill_id = ?';

    $pmtSum = $d->queryAll($query, $bill_id);

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


    if (count($pmts)) {
        $config = phpaga_config_get();
        $pmtInfo['payments'] = array();

	foreach ($pmts as $qrow) {
		phpaga_sanitizeArray($qrow);
                $qrow['pmt_amt_format'] = $config['MONETARY_SYMBOL'].phpaga_formatamount((float)$qrow['pmt_amt']);
                $pmtInfo['payments'][] = $qrow; 
        }

	foreach ($pmtSum as $r) {
	    $pmtInfo['sum'] = $r['pmt_sum'];
	}
    }

    return $pmtInfo;
}

/**
 * Adds a payment for a bill
 *
 * @author Michael Kimmick <support@nichewares.com>
 * @since phpaga 0.4
 */

function phpaga_payment_add($bill_id, $pmt_amt, $pmt_date, $pmt_note)
{

    /* Need to check bills.bill_endsum, and sum of all related payments.  If this payment,
       causes the sum of payments to reach the bills end_sum, then set the bill's payment
       date. */
    $d = new PhPagaDbData;
    $query = 'Select bill_endsum, bill_paydate
	FROM bills
	WHERE bill_id = ?';

    $r = $d->queryRow($query, $bill_id);

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

    $bill_total = $r['bill_endsum'];
    $bill_paydate = $r['bill_paydate'];

    $query = 'Select sum(pmt_amt) as pmt_sum
	FROM payments
	WHERE bill_id = ?';

    $r = $d->queryRow($query, $bill_id);

    if (PhPagaError::isError($r)) {
	return $r;
    }
    
    $pmt_sum = $r['pmt_sum'];

    /* query for total latefees for this bill */
    $query = 'Select sum(fee_amt) as latefee_sum
       FROM latefees
       WHERE bill_id = ?';

    $r = $d->queryRow($query, $bill_id);

    if (PhPagaError::isError($r)) {
       return $r;
    }
    $latefee_sum = $r['latefee_sum'];


    /* Process (insert) payment into payments table */
    $fields = array('bill_id' => $bill_id, 'pmt_amt' => $pmt_amt, 'pmt_date' => $pmt_date, 'pmt_note' => $pmt_note);

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

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

   /* Check to see if we need to set bill pay_date */
   if (!strlen($bill_paydate)) {
       if (($bill_total+$latefee_sum-$pmt_sum-$pmt_amt) <= 0) {
           $fields = array('bill_paydate' => $pmt_date);
           $r = $d->update('bills', $fields, 'bill_id = ?', $bill_id);

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

    return true;
}


/**
 * Updates a payment for a bill
 *
 * @author Michael Kimmick <support@nichewares.com>
 * @since phpaga 0.4
 */

function phpaga_payment_update($pmt_id, $pmt_amt, $pmt_date, $pmt_note)
{   
    $fields = array('pmt_amt' => $pmt_amt, 'pmt_date' => $pmt_date, 'pmt_note' => $pmt_note);

    $d = new PhPagaDbData;
    $r = $d->update('payments', $fields, 'pmt_id = ?', $pmt_id);

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


}


?>
