#
#
#
#
#
##
# rectrans-new.php :: Multiple debit-credit Transactions
##
# get settings
require "settings.php";
require "core-settings.php";
# decide what to do
if (isset($_POST["key"])) {
    switch ($_POST["key"]) {
        case "cconfirm":
            $OUTPUT = cconfirm($_POST);
            break;
        case "write":
            $OUTPUT = write($_POST);
            break;
        case "writerem":
            $OUTPUT = writerem($_POST);
            break;
        default:
            if (isset($_POST['proc'])) {
                # Process
                $OUTPUT = confirm($_POST);
            } elseif (isset($_POST["rem"])) {
                # Remove
                $OUTPUT = confirmrem($_POST);
            }
function update_qty()
{
    extract($_REQUEST);
    $sql = "SELECT * FROM cubit.nons_invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "' and done='n'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class='err'>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    $sql = "SELECT traddisc FROM hire.hire_invoices WHERE invid='{$inv['hire_invid']}'";
    $disc_rslt = db_exec($sql) or errDie("Unable to retrieve discount.");
    $traddisc = pg_fetch_result($disc_rslt, 0);
    $total_amt = 0;
    $vattot = 0;
    foreach ($qty as $item_id => $new_qty) {
        $sql = "\r\n\t\tSELECT unitcost, item_id AS note_item_id\r\n\t\tFROM hire.hire_nons_inv_items\r\n\t\tWHERE id='{$item_id}'";
        $item_rslt = db_exec($sql) or errDie("Unable to retrieve items.");
        $item = pg_fetch_array($item_rslt);
        $sql = "SELECT basis, hours, weeks, qty,\r\n\t\t\t\t\textract('epoch' from from_date) AS e_from,\r\n\t\t\t\t\textract('epoch' from to_date) AS e_to\r\n\t\t\t\tFROM hire.hire_invitems\r\n\t\t\t\tWHERE id='{$item['note_item_id']}'";
        $hired_rslt = db_exec($sql) or errDie("Unable to retrieve items.");
        $hired_data = pg_fetch_array($hired_rslt);
        if ($new_qty > $hired_data["qty"] || $new_qty < 1) {
            return cconfirm("\r\n\t\t\t<li class='err'>\r\n\t\t\t\tInvalid quantity, check that the quantity you're trying to\r\n\t\t\t\treturn is not more than what was hired out.\r\n\t\t\t</li>");
        }
        if ($hired_data["weeks"]) {
            $hired_days = sprint($hired_data["weeks"] * 7);
        } elseif ($hired_data["e_from"] > 0) {
            $secs = $hired_data["e_to"] - $hired_data["e_from"];
            $hired_days = sprint($secs / (60 * 60 * 24) + 1);
        } elseif ($hired_data["hours"]) {
            $secs = $hired_data["hours"] / 24;
            $hired_days = sprint($secs);
        } else {
            $hired_days = 0;
        }
        $hired_days = floor($hired_days);
        $amt = $item["unitcost"] * $new_qty;
        $total_amt += $amt;
        if ($traddisc > 0) {
            $vattot += $amt / 100 * (100 - $traddisc) / 100 * 14;
        } else {
            $vattot += $amt / 100 * 14;
        }
        $sql = "\r\n\t\tUPDATE hire.hire_nons_inv_items SET amt='{$amt}', qty='{$new_qty}'\r\n\t\tWHERE id='{$item_id}'";
        db_exec($sql) or errDie("Unable to update item amount.");
    }
    if (isset($stock_qty) && is_array($stock_qty)) {
        foreach ($stock_qty as $id => $value) {
            $sql = "SELECT stkid, unitcost, qty, excl_amount, vatamount FROM hire.hire_stock_items WHERE id='{$id}'";
            $cost_rslt = db_exec($sql) or errDie("Unable to retrieve cost.");
            list($stkid, $cost, $oqty, $excl, $vatamount) = pg_fetch_array($cost_rslt);
            $cost += 0;
            if ($traddisc > 0) {
                if ($oqty != 0) {
                    $stkamt = sprint($excl / $oqty * $value / 100 * (100 - $traddisc));
                }
            } else {
                if ($oqty != 0) {
                    $stkamt = sprint($excl / $oqty * $value);
                }
            }
            if (!isset($stkamt)) {
                $stkamt = 0;
            }
            $total_amt += $stkamt;
            if ($traddisc > 0) {
                if ($oqty != 0) {
                    $vattot += $vatamount / $oqty * $value / 100 * (100 - $traddisc);
                }
            } else {
                if ($oqty != 0) {
                    $vattot += $vatamount / $oqty * $value;
                }
            }
            if ($oqty == 0) {
                $oqty = 1;
            }
            $sql = "\r\n\t\t\tUPDATE cubit.stock SET alloc=((alloc-'{$oqty}')+'{$value}')\r\n\t\t\tWHERE stkid='{$stkid}'";
            db_exec($sql) or errDie("Unable to update stock allocation.");
            $sql = "\r\n\t\t\tUPDATE hire.hire_stock_items SET amount='{$stkamt}', qty='{$value}', excl_amount=excl_amount/{$oqty}*{$value}, vatamount=vatamount/{$oqty}*{$value}\r\n\t\t\tWHERE id='{$id}'";
            db_exec($sql) or errDie("Unable to update amount.");
        }
    }
    // Retrieve trade discount and delivery cost
    $sql = "\r\n\tSELECT traddisc, delivery FROM hire.hire_invoices\r\n\tWHERE invid='{$inv['hire_invid']}'";
    $note_rslt = db_exec($sql) or errDie("Unable to retrieve hire note.");
    list($traddisc, $delivery) = pg_fetch_array($note_rslt);
    $traddiscamt = sprint($total_amt / 100 * $traddisc);
    $subtotal = sprint($total_amt - $traddiscamt + $delivery);
    $vat = sprint($vattot);
    //sprint(($subtotal/100)*14);
    $total = sprint($subtotal + $vat);
    $sql = "\r\n\tUPDATE cubit.nons_invoices SET discount='{$traddiscamt}',\r\n\t\tsubtot='{$subtotal}', vat='{$vat}', total='{$total}'\r\n\tWHERE invid='{$inv['invid']}'";
    db_exec($sql) or errDie("Unable to update invoice.");
    /*$total_amt = 0;
    	while ($items = pg_fetch_array($items_rslt)) {
    		$amt = ($items["rate"] * $items["hired_days"]) * $items["qty"];
    		$unitcost = $amt / $items["qty"];
    
    		$sql = "
    		UPDATE hire.hire_nons_inv_items SET amt='$amt', unitcost='$unitcost'
    		WHERE item_id='$items[id]'";
    		db_exec($sql) or errDie("Unable to update qtys");
    
    		$total_amt += $amt;
    	}
    
    	// Retrieve trade discount and delivery cost
    	$sql = "
    	SELECT traddisc, delivery FROM hire.hire_invoices
    	WHERE invid='$inv[hire_invid]'";
    	$note_rslt = db_exec($sql) or errDie("Unable to retrieve hire note.");
    	list($traddisc, $delivery) = pg_fetch_array($note_rslt);
    
    	$traddiscamt = ($total_amt/100)*$traddisc;
    	$subtotal = $total_amt - $traddisc + $delivery;
    
    	$sql = "
    	UPDATE cubit.nons_invoices SET discount='$traddiscamt',
    		delivery='$delivery', subtot='$subtotal'
    	WHERE invid='$inv[hire_invid]'";
    
    	$sql = "
    	UPDATE hire.hire_invoices SET delivery='0'
    	WHERE invid='$inv[hire_invid]'";
    	db_exec($sql) or errDie("Unable to update hire invoice.");*/
    return cconfirm();
}