<?php
/* $Id: index.php 6941 2014-10-26 23:18:08Z daintree $*/
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity=0;
include('includes/DefineCustAllocsClass.php');
include('includes/session.inc');
$Title = _('Customer Receipt') . '/' . _('Credit Note Allocations');
$ViewTopic= 'ARTransactions';
$BookMark = 'CustomerAllocations';
include('includes/newheader.php');
include('includes/SQL_CommonFunctions.inc');

?>

		
  					
	<script src="angular/angular.min.js"></script>  
        
 
     
     
		

   
  
 									
									<?php
//this is where you paste. Below paste it:

if (isset($_GET['debtorno'])) {
		$_SESSION['debtorno'] = stripslashes($_GET['debtorno']);
	}
	$debtorno = $_SESSION['debtorno'];

	if (isset($_GET['account'])) {
		$_SESSION['account'] = stripslashes($_GET['account']);
	}
	$account = $_SESSION['account'];

	if (isset($_GET['transno'])) {
		$_SESSION['transno'] = stripslashes($_GET['transno']);
	}
	$receiptno = $_SESSION['transno'];	



if ( isset($_POST['Cancel']) ) {
	unset($_POST['AllocTrans']);
}

if (isset($_POST['UpdateDatabase']) OR isset($_POST['RefreshAllocTotal'])) {

	if (!isset($_SESSION['Alloc'])) {
		prnMsg(
			_('Allocations can not be processed again') . '. ' .
				_('If you hit refresh on this page after having just processed an allocation') . ', ' .
				_('try to use the navigation links provided rather than the back button') . ', ' .
				_('to avoid this message in future'),
			'info');
		include('includes/footer.inc');
		exit;
	}

	$InputError = 0;
	$TotalAllocated = 0;
	$TotalDiffOnExch = 0;

	for ($AllocCounter=0; $AllocCounter < $_POST['TotalNumberOfAllocs']; $AllocCounter++) {
	// loop through amounts allocated using AllocnItm->ID for each record

		if (isset($_POST['Amt' . $AllocCounter])) {

 			// allocatable charge amounts
			if (!is_numeric(filter_number_format($_POST['Amt' . $AllocCounter]))) {
				$_POST['Amt' . $AllocCounter] = 0;
			}
			if (filter_number_format($_POST['Amt' . $AllocCounter]) < 0) {
				prnMsg(_('Amount entered was negative') . '. ' . _('Only positive amounts are allowed') . '.','warn');
				$_POST['Amt' . $AllocCounter] = 0;
			}
			if (isset($_POST['All' . $AllocCounter]) AND $_POST['All' . $AllocCounter] == True) {
				$_POST['Amt' . $AllocCounter] = $_POST['YetToAlloc' . $AllocCounter];
			}
			if (filter_number_format($_POST['Amt' . $AllocCounter]) > $_POST['YetToAlloc' . $AllocCounter]) {
				$_POST['Amt' . $AllocCounter]=locale_number_format($_POST['YetToAlloc' . $AllocCounter],$_SESSION['Alloc']->CurrDecimalPlaces);
				// Amount entered must be smaller than unallocated amount
			}

			$_SESSION['Alloc']->Allocs[$_POST['AllocID' . $AllocCounter]]->AllocAmt = filter_number_format($_POST['Amt' . $AllocCounter]);
			// recalcuate the new difference on exchange (a +positive amount is a gain -ve a loss)
			$_SESSION['Alloc']->Allocs[$_POST['AllocID' . $AllocCounter]]->DiffOnExch =
			  (filter_number_format($_POST['Amt' . $AllocCounter]) / $_SESSION['Alloc']->TransExRate) -
			  (filter_number_format($_POST['Amt' . $AllocCounter]) / $_SESSION['Alloc']->Allocs[$_POST['AllocID' . $AllocCounter]]->ExRate);

			$TotalDiffOnExch += $_SESSION['Alloc']->Allocs[$_POST['AllocID' . $AllocCounter]]->DiffOnExch;
			$TotalAllocated += filter_number_format($_POST['Amt' . $AllocCounter]);
		}

	}

	if ($TotalAllocated + $_SESSION['Alloc']->TransAmt > 0.008) {
		prnMsg(_('Allocation could not be processed because the amount allocated is more than the').' ' . $_SESSION['Alloc']->TransTypeName  . ' '._('being allocated') . '<br />' . _('Total allocated').' = ' . $TotalAllocated . ' '._('and the total amount of the') .' ' . $_SESSION['Alloc']->TransTypeName  . ' ' . _('was').' ' . -$_SESSION['Alloc']->TransAmt,'error');
		$InputError=1;
	}
}

if (isset($_POST['UpdateDatabase'])) {
	if ($InputError==0) {
		//
		//========[ START TRANSACTION ]===========
		//
		$Error = '';
		$Result= DB_Txn_Begin();
		$AllAllocations = 0;
		foreach ($_SESSION['Alloc']->Allocs as $AllocnItem) {
			if ($AllocnItem->PrevAllocRecordID != 'NA') {
			// original allocation has changed so delete the old allocation record
				$SQL = "DELETE FROM custallocns WHERE id = '" . $AllocnItem->PrevAllocRecordID . "'";
				if( !$Result = DB_query($SQL) ) {
					$Error = _('Could not delete old allocation record');
				}
			 }
  
			if ($AllocnItem->AllocAmt > 0) {
				//get invoice number real amount where it got allocated 
				
				$SQL1= "SELECT ovamount,ovgst
			FROM debtortrans 
			WHERE debtortrans.id='" . $AllocnItem->ID . "'";


	$Result1 = DB_query($SQL1);
	$myrow1 = DB_fetch_array($Result1);
			
				$invoiceamount = $myrow1['ovamount'] + $myrow1['ovgst'];
				
				$SQL = "INSERT INTO
							custallocns (
							datealloc,
							customer,
							amt,
							transid_allocfrom,
							receipt_number,
							receipt_amount,
							receipt_date,
							transid_allocto,
							invoice_number,
							invoice_amount
						) VALUES (
							'" . date('Y-m-d') . "',
							'" . $_SESSION['Alloc']->DebtorNo. "',
							'" . $AllocnItem->AllocAmt . "',
							'" . $_SESSION['Alloc']->AllocTrans . "',
							'" . $_SESSION['Alloc']->TransNo . "',
							
							'" . $_SESSION['Alloc']->TransAmt . "',
							'" . $_SESSION['Alloc']->ReceiptDate . "',
							'" . $AllocnItem->ID . "',
							'" . $AllocnItem->TypeNo . "',
							'" . $invoiceamount. "'
						)";
				if( !$Result = DB_query($SQL) ) {
					$Error = _('Could not change allocation record');
				}
			}
			$NewAllocTotal = $AllocnItem->PrevAlloc + $AllocnItem->AllocAmt;
			$AllAllocations = $AllAllocations + $AllocnItem->AllocAmt;
			$Settled = (abs($NewAllocTotal-$AllocnItem->TransAmount) < 0.005) ? 1 : 0;

			$SQL = "UPDATE debtortrans
					SET diffonexch='" . $AllocnItem->DiffOnExch . "',
					alloc = '" . $NewAllocTotal . "',
					settled = '" . $Settled . "'
					WHERE id = '" . $AllocnItem->ID."'";
			if( !$Result = DB_query($SQL) ) {
				$Error = _('Could not update difference on exchange');
			}
		}
		if (abs($TotalAllocated + $_SESSION['Alloc']->TransAmt) < 0.01) {
			$Settled = 1;
		} else {
			$Settled = 0;
		}
		// Update the receipt or credit note
		$SQL = "UPDATE debtortrans
				SET alloc = '" .  -$AllAllocations . "',
				diffonexch = '" . -$TotalDiffOnExch . "',
				settled='" . $Settled . "'
				WHERE id = '" . $_POST['AllocTrans']."'";

		if( !$Result = DB_query($SQL) ) {
			$Error = _('Could not update receipt or credit note');
		}

		// If GLLink to debtors active post diff on exchange to GL
		$MovtInDiffOnExch = -$_SESSION['Alloc']->PrevDiffOnExch - $TotalDiffOnExch;


		//
		//========[ COMMIT TRANSACTION ]===========
		//
		if (empty($Error) ) {
				$Result = DB_Txn_Commit();
		} else {
				$Result = DB_Txn_Rollback();
				prnMsg($Error,'error');
		}
		unset($_SESSION['Alloc']);
		unset($_POST['AllocTrans']);
	}
}

if (isset($_GET['AllocTrans'])) {

	if (isset($_SESSION['Alloc'])) {
		unset($_SESSION['Alloc']->Allocs);
		unset($_SESSION['Alloc']);
	}

	$_SESSION['Alloc'] = new Allocation;
	$_POST['AllocTrans'] = $_GET['AllocTrans']; // Set AllocTrans when page first called

	$SQL= "SELECT systypes.typename,
				debtortrans.type,
				debtortrans.transno,
				debtortrans.trandate,
				debtortrans.debtorno,
				debtortrans.department,
				debtortrans.account_number,
				debtorsmaster.name,
				debtortrans.rate,
				(debtortrans.ovamount + debtortrans.ovgst + debtortrans.ovfreight + debtortrans.ovdiscount) as total,
				debtortrans.diffonexch,
				debtortrans.alloc,
				currencies.decimalplaces
			FROM debtortrans INNER JOIN systypes
			ON debtortrans.type = systypes.typeid
			INNER JOIN debtorsmaster
			ON debtortrans.debtorno = debtorsmaster.debtorno
			INNER JOIN currencies
			ON debtorsmaster.currcode=currencies.currabrev
			WHERE debtortrans.id='" . $_POST['AllocTrans'] . "' 
			AND debtortrans.cancelled =0 AND debtortrans.account_number='" . $account . "'";

	if ($_SESSION['SalesmanLogin'] != '') {
		$SQL .= " AND debtortrans.salesperson='" . $_SESSION['SalesmanLogin'] . "'";
	}

	$Result = DB_query($SQL);
	$myrow = DB_fetch_array($Result);

	if ($myrow['debtorno'] ==''||$myrow['department'] =='11' ){
	
		$SQLaccount= "SELECT debtorno
			FROM debtoraccount 
			WHERE account_number='" . $myrow['account_number']. "' 
			AND debtortrans.cancelled =0 AND debtortrans.account_number='" . $account . "'";

	
	$Resultaccount = DB_query($SQLaccount);
	$myrowaccount = DB_fetch_array($Resultaccount);

		
		$myrow['debtorno'] = $myrowaccount['debtorno'];
	
		$debtorno = $myrowaccount['debtorno'];
	}
	
	$_SESSION['Alloc']->AllocTrans	= $_POST['AllocTrans'];
	$_SESSION['Alloc']->DebtorNo		= $myrow['debtorno'];
	$_SESSION['Alloc']->CustomerName	= $myrow['name'];
	$_SESSION['Alloc']->TransType		= $myrow['type'];
	$_SESSION['Alloc']->TransTypeName	= $myrow['typename'];//= _($myrow['typename']); **********
	$_SESSION['Alloc']->TransNo		= $myrow['transno'];
	$_SESSION['Alloc']->TransExRate	= $myrow['rate'];
	$_SESSION['Alloc']->TransAmt		= $myrow['total'];
	$_SESSION['Alloc']->PrevDiffOnExch = $myrow['diffonexch'];
	$_SESSION['Alloc']->TransDate		= ConvertSQLDate($myrow['trandate']);
	$_SESSION['Alloc']->CurrDecimalPlaces = $myrow['decimalplaces'];
$_SESSION['Alloc']->ReceiptDate		= $myrow['trandate'];
	$_SESSION['Alloc']->AccountNumber		= $myrow['account_number'];
	// First get transactions that have outstanding balances
	$SQL = "SELECT debtortrans.id,
					typename,
					transno,
					trandate,
					rate,
					
					ovamount+ovgst+ovfreight+ovdiscount as total,
					diffonexch,
					alloc
			FROM debtortrans INNER JOIN systypes
			ON debtortrans.type = systypes.typeid
			WHERE debtortrans.settled=0
			AND debtorno='" . $debtorno. "'
			AND debtortrans.cancelled =0 AND debtortrans.account_number='" . $account . "'";

	if ($_SESSION['SalesmanLogin'] != '') {
		$SQL .= " AND debtortrans.salesperson='" . $_SESSION['SalesmanLogin'] . "'";
	}

	$SQL .= " ORDER BY debtortrans.trandate";

	$Result = DB_query($SQL);

	while ($myrow=DB_fetch_array($Result)) {
		$_SESSION['Alloc']->add_to_AllocsAllocn ($myrow['id'],
												$myrow['typename'],//_($myrow['typename']), **********
												$myrow['transno'],
												ConvertSQLDate($myrow['trandate']),
												0,
												$myrow['total'],
												$myrow['rate'],
												$myrow['diffonexch'],
												$myrow['diffonexch'],
												$myrow['alloc'],
												'NA');
	}
	DB_free_result($Result);

	// Get trans previously allocated to by this trans - this will overwrite incomplete allocations above
	$SQL= "SELECT debtortrans.id,
					typename,
					transno,
					trandate,
					rate,
					ovamount+ovgst+ovfreight+ovdiscount AS total,
					diffonexch,
					debtortrans.alloc-custallocns.amt AS prevallocs,
					amt,
					custallocns.id AS allocid
			FROM debtortrans INNER JOIN systypes
			ON debtortrans.type = systypes.typeid
			INNER JOIN custallocns
			ON debtortrans.id=custallocns.transid_allocto
			WHERE custallocns.transid_allocfrom='" . $_POST['AllocTrans'] . "'
			AND debtorno='" . $debtorno . "'
			AND debtortrans.cancelled =0 AND debtortrans.account_number='" . $account . "'";
 
	if ($_SESSION['SalesmanLogin'] != '') {
		$SQL .= " AND debtortrans.salesperson='" . $_SESSION['SalesmanLogin'] . "'";
	}

	$SQL .= " ORDER BY debtortrans.trandate";

	$Result=DB_query($SQL);

	while ($myrow=DB_fetch_array($Result)) {
		$DiffOnExchThisOne = ($myrow['amt']/$myrow['rate']) - ($myrow['amt']/$_SESSION['Alloc']->TransExRate);
		$_SESSION['Alloc']->add_to_AllocsAllocn ($myrow['id'],
												$myrow['typename'],//_($myrow['typename']), **********
												$myrow['transno'],
												ConvertSQLDate($myrow['trandate']),
												$myrow['amt'],
												$myrow['total'],
												$myrow['rate'],
												$DiffOnExchThisOne,
												($myrow['diffonexch'] - $DiffOnExchThisOne),
												$myrow['prevallocs'],
												$myrow['allocid']);
	}
	DB_free_result($Result);
}


echo '<p class="page_title_text">
		<img src="'.$RootPath.'/css/'.$Theme.'/images/transactions.png" title="' . _('Allocate Receipt') . '" alt="" />' . ' ' . _('Allocate Receipts') . '
	</p>';

$TableHeader = '<tr>
					<th>' . _('Trans Type') . '</th>
					<th>' . _('Customer') . '</th>
					<th>' . _('Account No') . '</th>
					<th>' . _('Number') . '</th>
					<th>' . _('Date') . '</th>
					<th>' . _('Total') . '</th>
					<th>' . _('To Alloc') . '</th>
					<th>' . _('Currency') . '</th>
					<th>' . _('Action') . '</th>
					
				</tr>';

if (isset($_POST['AllocTrans'])) {
	/* Page called with trans number
		Show trans already allocated and potential new allocations
	*/
	echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '" method="post">
		<div>
		<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />
		<input type="hidden" name="AllocTrans" value="' . $_POST['AllocTrans'] . '" />
		<table class="selection">
		<tr>
			<th colspan="7">
			<div class="centre">
				<b>' . $_SESSION['Alloc']->DebtorNo . ' - ' . $_SESSION['Alloc']->CustomerName . '</b>
			</div>';

	if ($_SESSION['Alloc']->TransExRate != 1) {
			echo '<br />' . _('Amount in customer currency') . ' <b>' . locale_number_format(-$_SESSION['Alloc']->TransAmt,$_SESSION['Alloc']->CurrDecimalPlaces) . '</b><i> (' .  _('converted into local currency at an exchange rate of'). ' ' . $_SESSION['Alloc']->TransExRate . ')</i>';
	}
	echo '</th>
		</tr>
		<tr>
			<th>' . _('Trans') . '<br />' . _('Type') . '</th>
			<th>' . _('Trans') . '<br />' . _('Number') . '</th>
			<th>' . _('Trans') . '<br />' . _('Date') . '</th>
			<th>' . _('Total') . '<br />' . _('Amount') . '</th>
			<th>' . _('Yet to') . '<br />' . _('Allocate') . '</th>
			<th>' . _('This') . '<br />' . _('Allocation') . '</th>
			<th>' . _('Running') . '<br />' . _('Balance') . '</th>
		</tr>';

	$Counter = 0;
	$TotalAllocated = 0;
	$Balance = 0;
	$j=0;
	foreach ($_SESSION['Alloc']->Allocs as $AllocnItem) {
		$YetToAlloc = ($AllocnItem->TransAmount - $AllocnItem->PrevAlloc);

		if ( $AllocnItem->ID == $_POST['AllocTrans'] ) {
			echo '<tr class="OddTableRows">';
			$curTrans = _('Being allocated');
		} else if ($AllocnItem->AllocAmt > 0) {
			echo '<tr class="OddTableRows">';
		} else {
			echo '<tr class="EvenTableRows">';
			$curTrans = "&nbsp;";
		}

		echo '<td>' . _($AllocnItem->TransType) . '</td>
			<td class="number">' . $AllocnItem->TypeNo . '</td>
			<td>' . $AllocnItem->TransDate . '</td>
			<td class="number">' . locale_number_format($AllocnItem->TransAmount,$_SESSION['Alloc']->CurrDecimalPlaces) . '</td>
			<td class="number">' . locale_number_format($YetToAlloc,$_SESSION['Alloc']->CurrDecimalPlaces) . '</td>';
		$j++;

		if ($AllocnItem->TransAmount < 0) {
				$Balance+=$YetToAlloc;
				echo '<td>' . $curTrans  . '</td>
						<td class="number">' . locale_number_format($Balance,$_SESSION['Alloc']->CurrDecimalPlaces) . '</td>
					</tr>';
		} else {
				echo '<td class="number"><input type="hidden" name="YetToAlloc' . $Counter . '" value="' . round($YetToAlloc,$_SESSION['Alloc']->CurrDecimalPlaces) . '" />';
				echo '<input tabindex="' . $j .'" type="checkbox" title="' . _('Check this box to allocate the entire amount of this transaction. Just enter the amount without ticking this check box for a partial allocation') . '" name="All' .  $Counter . '"';// NewText: _('Check this box to allocate the entire amount of this transaction. Just enter the amount without ticking this check box for a partial allocation')

				if (ABS($AllocnItem->AllocAmt-$YetToAlloc) < 0.01) {
						echo ' checked="checked" />';
				} else {
						echo ' />';
				}
				$Balance += $YetToAlloc-$AllocnItem->AllocAmt;
				$j++;
				echo '<input tabindex="' . $j . '" type="text" class="number" ' . ($j==1 ? 'autofocus="autofocus"' :'') . ' name="Amt' . $Counter .'" title="' . _('Enter the amount of this transaction to be allocated. Nothing should be entered here if the entire transaction is to be allocated, use the check box') . '" maxlength="12" size="13" value="' . locale_number_format(round($AllocnItem->AllocAmt,$_SESSION['Alloc']->CurrDecimalPlaces),$_SESSION['Alloc']->CurrDecimalPlaces) . '" />
					<input type="hidden" name="AllocID' . $Counter . '" value="' . $AllocnItem->ID . '" ></td>
					<td class="number">' . locale_number_format($Balance,$_SESSION['Alloc']->CurrDecimalPlaces) . '</td>
				</tr>';
		}
		$TotalAllocated += round($AllocnItem->AllocAmt,$_SESSION['Alloc']->CurrDecimalPlaces);
		$Counter++;
	}

	echo '<tr>
			<td colspan="5" class="number"><b>' . _('Total Allocated').':</b></td>
			<td class="number"><b>' . locale_number_format($TotalAllocated,$_SESSION['Alloc']->CurrDecimalPlaces) . '</b></td>';
	$j++;
	echo '<td colspan="2">
			<input tabindex="'.$j.'" type="submit" name="RefreshAllocTotal" value="' . _('Recalculate Total To Allocate') . '" /></td>
        </tr>
		<tr>
			<td colspan="5" class="number"><b>' . _('Left to allocate') . '</b></td>
			<td class="number"><b>' . locale_number_format(-$_SESSION['Alloc']->TransAmt-$TotalAllocated,$_SESSION['Alloc']->CurrDecimalPlaces) . '</b></td>
		</tr>
		</table>
		<br />
		<input type="hidden" name="TotalNumberOfAllocs" value="' . $Counter . '" />
		<div class="centre">
			<input tabindex="' . $j . '" type="submit" name="UpdateDatabase" value="' . _('Process Allocations') . '" />
			<input tabindex="' . $j . '" type="submit" name="Cancel" value="' . _('Cancel') . '" />
		</div>
        </div>
        </form>';

} 
else {
	// Page called with customer code
	unset($_SESSION['Alloc']->Allocs);
	unset($_SESSION['Alloc']);

	$SQL = "SELECT debtortrans.id,
				debtortrans.transno,
				systypes.typename,
				debtortrans.type,
				debtortrans.debtorno,
				debtorsmaster.name,
				debtortrans.trandate,
				debtortrans.reference,
				debtortrans.account_number,
				
				debtortrans.ovamount+debtortrans.ovgst+debtortrans.ovdiscount+debtortrans.ovfreight as total,
				debtortrans.alloc
			FROM debtortrans INNER JOIN debtorsmaster
			ON debtortrans.debtorno=debtorsmaster.debtorno
			INNER JOIN systypes
			ON debtortrans.type=systypes.typeid
			WHERE debtortrans.account_number='" . $account . "'
			AND (debtortrans.type=12 OR debtortrans.type=11)
			AND debtortrans.settled=0
			AND debtortrans.cancelled =0 
			";

	if ($_SESSION['SalesmanLogin'] != '') {
		$SQL .= " AND debtortrans.salesperson='" . $_SESSION['SalesmanLogin'] . "'";
	}

	$SQL .= " ORDER BY debtortrans.id";

	$result = DB_query($SQL);

	if (DB_num_rows($result)==0) {
		prnMsg(_('No outstanding receipts or credits to be allocated for this customer'),'info');
		include('includes/footer.inc');
		exit;
	}
	 echo '<table class="selection">';
	echo $TableHeader;
	$k=0;
	while ($myrow = DB_fetch_array($result)) {
		if ($k==1){
			echo '<tr class="EvenTableRows">';
			$k=0;
		} else {
			echo  '<tr class="OddTableRows">';;
			$k++;
		}
		echo '<td>' . _($myrow['typename']) . '</td>
				<td>' . $myrow['name'] . '</td>
				<td>' . $myrow['account_number'] . '</td>
				<td>' . $myrow['transno'] . '</td>
				<td>' . ConvertSQLDate($myrow['trandate']) . '</td>
				<td class="number">' . locale_number_format($myrow['total'],2) . '</td>
				<td class="number">' . locale_number_format($myrow['total']-$myrow['alloc'],2) . '</td>
				<td>FJD</td>
				<td><a href="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8'). '?AllocTrans=' . $myrow['id'] . '">' . _('Allocate') . '</a></td>
			</tr>';
	}
	echo '</table>';
} 





			  
 	echo '</div >';
	?>
						

		
					</div>
				</div>
			</div>
					
					

						<!--end:: Widgets/Stats-->

						<!--Begin::Section-->
						

		<!-- end::Quick Sidebar -->

		<!-- begin::Scroll Top -->
		<div id="m_scroll_top" class="m-scroll-top">
			<i class="la la-arrow-up"></i>
		</div>

		<!-- end::Scroll Top -->

		<!-- begin::Quick Nav -->
		

		<!-- begin::Quick Nav -->
<script src="includes/vendors/owl.carousel/dist/owl.carousel.js" type="text/javascript"></script>

		<!--end::Page Scripts -->
	</body>

	<!-- end::Body -->
</html>
 
      
<?php



/*The module link codes are hard coded in a switch statement below to determine the options to show for each tab */
include('includes/MainMenuLinksArray.php');

if (isset($SupplierLogin) AND $SupplierLogin==1){
	echo '<table class="table_index">
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=1">' . _('View or Amend outstanding offers') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=2">' . _('Create a new offer') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=3">' . _('View any open tenders without an offer') . '</a></p>
			</td>
			</tr>
		</table>';
	include('includes/footer.inc');
	exit;
} elseif (isset($CustomerLogin) AND $CustomerLogin==1){
	echo '<table class="table_index">
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/CustomerInquiry.php?CustomerID=' . $_SESSION['CustomerID'] . '">' . _('Account Status') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SelectOrderItems.php?NewOrder=Yes">' . _('Place An Order') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SelectCompletedOrder.php?SelectedCustomer=' . $_SESSION['CustomerID'] . '">' . _('Order Status') . '</a></p>
			</td>
			</tr>
		</table>';

	include('includes/footer.inc');
	exit;
}

if (isset($_GET['Application'])){ /*This is sent by this page (to itself) when the user clicks on a tab */
	$_SESSION['Module'] = $_GET['Application'];
}








//include('includes/footer.inc');

function GetRptLinks($GroupID) {
/*
This function retrieves the reports given a certain group id as defined in /reports/admin/defaults.php
in the acssociative array $ReportGroups[]. It will fetch the reports belonging solely to the group
specified to create a list of links for insertion into a table to choose a report. Two table sections will
be generated, one for standard reports and the other for custom reports.
*/
	global $db, $RootPath, $ReportList;
	require_once('reportwriter/languages/en_US/reports.php');
	require_once('reportwriter/admin/defaults.php');
	$GroupID=$ReportList[$GroupID];
	$Title= array(_('Custom Reports'), _('Standard Reports and Forms'));

	$sql= "SELECT id,
				reporttype,
				defaultreport,
				groupname,
				reportname
			FROM reports
			ORDER BY groupname,
					reportname";
	$Result=DB_query($sql,'','',false,true);
	$ReportList = '';
	while ($Temp = DB_fetch_array($Result)) $ReportList[] = $Temp;

	$RptLinks = '';
	for ($Def=1; $Def>=0; $Def--) {
        $RptLinks .= '<li class="menu_group_headers">';
        $RptLinks .= '<b>' .  $Title[$Def] . '</b>';
        $RptLinks .= '</li>';
		$NoEntries = true;
		if ($ReportList) { // then there are reports to show, show by grouping
			foreach ($ReportList as $Report) {
				if ($Report['groupname']==$GroupID AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item">';
					$RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/ReportMaker.php?action=go&amp;reportid=' . $Report['id'] . '">' . _($Report['reportname']) . '</a></p>';
					$RptLinks .= '</li>';
					$NoEntries = false;
				}
			}
			// now fetch the form groups that are a part of this group (List after reports)
			$NoForms = true;
			foreach ($ReportList as $Report) {
				$Group=explode(':',$Report['groupname']); // break into main group and form group array
				if ($NoForms AND $Group[0]==$GroupID AND $Report['reporttype']=='frm' AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item">';
					$RptLinks .= '<img src="' . $RootPath . '/css/' . $_SESSION['Theme'] . '/images/folders.gif" width="16" height="13" alt="" />&nbsp;';
					$RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/FormMaker.php?id=' . $Report['groupname'] . '"></p>';
					$RptLinks .= $FormGroups[$Report['groupname']] . '</a>';
					$RptLinks .= '</li>';
					$NoForms = false;
					$NoEntries = false;
				}
			}
		}
		if ($NoEntries) $RptLinks .= '<li class="menu_group_item">' . _('There are no reports to show!') . '</li>';
	}
	return $RptLinks;
}
	
?>
<!-- Modal HTML embedded directly into document -->
<div id="ex1" class="modal">
  <p>Thanks for clicking. That felt good.</p>
  <a href="#" rel="modal:close">Close</a>
</div>


<!-- Modal -->
 <div class="modal fade" id="getCodeModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
   <div class="modal-dialog modal-lg">
      <div class="modal-content">
       <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
         <h4 class="modal-title" id="myModalLabel"> API CODE </h4>
       </div>
       <div class="modal-body" id="getCode" style="overflow-x: scroll;">
       
          
          
       </div>
    </div>
   </div>
 </div>
<script>
jQuery(document).ready(function($){

   // event must be delegated from .xcrud
	
	//check employee for a clash on existing patrol location
$(".xcrud").on("change","#internal",function(){ // !important, delegation from static container
     var internal = $("#internal").val();
	 
	
        if(internal != 0)
       {
		
		 $('#sectors').attr("disabled", true);
		
            $('#patrollocation').attr("disabled",true);
		  $('#account').attr("disabled", true);
		   
		//   $("#account").hide();
       }
	else{
		 $('#sectors').attr("disabled", false);
		
            $('#patrollocation').attr("disabled",false);
		  $('#account').attr("disabled", false)
		//$("#account").show();
	}
     
	  
   });
	
	//check employee for a clash on same employee working at different location but at same time-frame
	//monday shift one and two	
	$(".xcrud").on("change","#monout",function(){ // !important, delegation from static container
     var start_time = $("#monin").val();
	 var end_time = $("#monout").val();
	 var rosterid = $("#rosterid").val();
		 var employeeid = $("#employeeid").val();
		
	
	
		
	
		
	   $.ajax({
      url:'hrms/CheckEmployee-timeclash.php',
      method:"POST",
      data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
		 
		
      success:function(data)
     {
		 	
	   var data = JSON.parse(data);
	    console.log(data);
        if(data != 0)
       {
		  
		   
       alert('CLASH!This employee is already rostered in another location/post at these selected times. Please choose another employee before proceeding. Full Details where they are rostered at :ROSTERID:'+ data);
		    
       }
      }
     })  
	  
   });

	//monday calculations
 
	



	
	
	//tuesdayshift one and two	
	$(".xcrud").on("change","#tuesout",function(){ // !important, delegation from static container
     var start_time = $("#tuesin").val();
	 var end_time = $("#tuesout").val();
	 var rosterid = $("#rosterid").val();
		 var employeeid = $("#employeeid").val();
		
	   $.ajax({
      url:'hrms/CheckEmployee-timeclashtues.php',
      method:"POST",
      data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
		 
		
      success:function(data)
     {
		 	
	   var data = JSON.parse(data);
	    console.log(data);
        if(data != 0)
       {
		  
		   
       alert('CLASH!This employee is already rostered in another location/post at these selected times. Please choose another employee before proceeding. Full Details where they are rostered at :ROSTERID:'+ data);
		    
       }
      }
     })  
	  
   });
	
	//wed shift one and two	
	$(".xcrud").on("change","#wedout",function(){ // !important, delegation from static container
     var start_time = $("#wedin").val();
	 var end_time = $("#wedout").val();
	 var rosterid = $("#rosterid").val();
		 var employeeid = $("#employeeid").val();
		if ( end_time <= start_time){
		   
		   alert('Time logged out has to be greater than Time logged in ');
	   }
		
	   $.ajax({
      url:'hrms/CheckEmployee-timeclashwed.php',
      method:"POST",
      data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
		 
		
      success:function(data)
     {
		 	
	   var data = JSON.parse(data);
	    console.log(data);
        if(data != 0)
       {
		  
		   
       alert('CLASH!This employee is already rostered in another location/post at these selected times. Please choose another employee before proceeding. Full Details where they are rostered at :ROSTERID:'+ data);
		    
       }
      }
     })  
	  
   });
	
	
	//thursday shift one and two	
	$(".xcrud").on("change","#thursout",function(){ // !important, delegation from static container
     var start_time = $("#thursin").val();
	 var end_time = $("#thursout").val();
	 var rosterid = $("#rosterid").val();
		 var employeeid = $("#employeeid").val();
		if ( end_time <= start_time){
		   
		   alert('Time logged out has to be greater than Time logged in ');
	   }
		
	   $.ajax({
      url:'hrms/CheckEmployee-timeclashthurs.php',
      method:"POST",
      data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
		 
		
      success:function(data)
     {
		 	
	   var data = JSON.parse(data);
	    console.log(data);
        if(data != 0)
       {
		  
		   
       alert('CLASH!This employee is already rostered in another location/post at these selected times. Please choose another employee before proceeding. Full Details where they are rostered at :ROSTERID:'+ data);
		    
       }
      }
     })  
	  
   });
	
	//friday shift one and two	
	$(".xcrud").on("change","#friout",function(){ // !important, delegation from static container
     var start_time = $("#friin").val();
	 var end_time = $("#friout").val();
	 var rosterid = $("#rosterid").val();
		 var employeeid = $("#employeeid").val();
		if ( end_time <= start_time){
		   
		   alert('Time logged out has to be greater than Time logged in ');
	   }
		
	   $.ajax({
      url:'hrms/CheckEmployee-timeclashfri.php',
      method:"POST",
      data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
		 
		
      success:function(data)
     {
		 	
	   var data = JSON.parse(data);
	    console.log(data);
        if(data != 0)
       {
		  
		   
       alert('CLASH!This employee is already rostered in another location/post at these selected times. Please choose another employee before proceeding. Full Details where they are rostered at :ROSTERID:'+ data);
		    
       }
      }
     })  
	  
   });
	
	//saturday shift one and two	
	$(".xcrud").on("change","#satout",function(){ // !important, delegation from static container
     var start_time = $("#satin").val();
	 var end_time = $("#satout").val();
	 var rosterid = $("#rosterid").val();
		 var employeeid = $("#employeeid").val();
		if ( end_time <= start_time){
		   
		   alert('Time logged out has to be greater than Time logged in ');
	   }
		
	   $.ajax({
      url:'hrms/CheckEmployee-timeclashsat.php',
      method:"POST",
      data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
		 
		
      success:function(data)
     {
		 	
	   var data = JSON.parse(data);
	    console.log(data);
        if(data != 0)
       {
		  
		   
       alert('CLASH!This employee is already rostered in another location/post at these selected times. Please choose another employee before proceeding. Full Details where they are rostered at :ROSTERID:'+ data);
		    
       }
      }
     })  
	  
   });
	
	//sundayshift one and two	
	$(".xcrud").on("change","#sunout",function(){ // !important, delegation from static container
     var start_time = $("#sunin").val();
	 var end_time = $("#sunout").val();
	 var rosterid = $("#rosterid").val();
		 var employeeid = $("#employeeid").val();
		if ( end_time <= start_time){
		   
		   alert('Time logged out has to be greater than Time logged in ');
	   }
		
	   $.ajax({
      url:'hrms/CheckEmployee-timeclashsun.php',
      method:"POST",
      data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
		 
		
      success:function(data)
     {
		 	
	   var data = JSON.parse(data);
	    console.log(data);
        if(data != 0)
       {
		  
		   
       alert('CLASH!This employee is already rostered in another location/post at these selected times. Please choose another employee before proceeding. Full Details where they are rostered at :ROSTERID:'+ data);
		    
       }
      }
     })  
	  
   });
	
	

	
	
	
   }); 
	
	

	
	
		
		

	
	
</script>


<script type="text/javascript">
jQuery(document).on("ready xcrudafterrequest",function(){
    
});
</script>