<?php

///////////////////////////////////////////////////////////////////////////////////////////////////
// DELETE BALANCE /////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
if ($R['deleteIdBalance']) {

	try {

		// START DELETING THE BALANCE /////////////////////////////////////////////////////////////

		// start transaction
		DB::startTransaction();

		// store the current balance components - to be reselected later
		if ($R['reselectComponents']) {
			$balDet=\Entity\Balance::selectForUpdate($R['deleteIdBalance']);
			$reselectBalance_client=$balDet->orderServicesList;
			$reselectBalance_supplier=$balDet->supplierInvoiceRowsList;
		}

		// delete the balance
		$balance=\Entity\Balance::delete($R['deleteIdBalance']);
		$balance->save();

		// BALANCE DELETED - OTHER STUFF TO DO UPON SUCCESS ///////////////////////////////////////
		// assign success message
		$balance->assignMessages($showMessage);

		// finish transaction
		DB::commitTransaction();

		// update user trace
		$userTrailItem->updateActionOld('Modules/Invoices/BalancesList-delete');
		$userTrailItem->updateEntityOld('invoiceBalance', $R['deleteIdBalance']);

		// reselect the balance details
		if ($R['reselectComponents']) {
			$S['manualBalance']['idServices']=array();
			foreach($reselectBalance_client as $idServ) $S['manualBalance']['idServices'][$idServ]=true;
			$S['manualBalance']['idSupplierRows']=array();
			foreach($reselectBalance_supplier as $idRow) $S['manualBalance']['idSupplierRows'][$idRow]=true;
		}

		// redirect to parent (so we lose ?delete)
		header("Location: ./");
		exit;

	} catch (\App\Entity\Exception $e) {
		$e->decorate($showMessage);
		DB::rollbackTransaction();
	}

}
