1<?php
2
3include('includes/session.php');
4$Title = _('Claim Petty Cash Expenses From Tab');
5/* webERP manual links before header.php */
6$ViewTopic = 'PettyCash';
7$BookMark = 'ExpenseClaim';
8include('includes/header.php');
9if (isset($_POST['SelectedTabs'])) {
10	$SelectedTabs = mb_strtoupper($_POST['SelectedTabs']);
11} elseif (isset($_GET['SelectedTabs'])) {
12	$SelectedTabs = mb_strtoupper($_GET['SelectedTabs']);
13}
14if (isset($_POST['SelectedIndex'])) {
15	$SelectedIndex = $_POST['SelectedIndex'];
16} elseif (isset($_GET['SelectedIndex'])) {
17	$SelectedIndex = $_GET['SelectedIndex'];
18}
19if (isset($_POST['Days'])) {
20	$Days = filter_number_format($_POST['Days']);
21} elseif (isset($_GET['Days'])) {
22	$Days = filter_number_format($_GET['Days']);
23}
24if (isset($_POST['Cancel'])) {
25	unset($SelectedTabs);
26	unset($SelectedIndex);
27	unset($Days);
28	unset($_POST['Amount']);
29	unset($_POST['Purpose']);
30	unset($_POST['Notes']);
31	unset($_FILES['Receipt']);
32}
33if (isset($_POST['Process'])) {
34	if ($_POST['SelectedTabs'] == '') {
35		echo prnMsg(_('You have not selected a tab to claim the expenses on'), 'error');
36		unset($SelectedTabs);
37	}
38}
39if (isset($_POST['Go'])) {
40	if ($Days <= 0) {
41		prnMsg(_('The number of days must be a positive number'), 'error');
42		$Days = 30;
43	}
44}
45//Define receipt attachment upload functions and variables which are used in various places within script
46$ReceiptSupportedExt = array('png','jpg','jpeg','pdf','doc','docx','xls','xlsx'); //Supported file extensions
47$ReceiptDir = $PathPrefix . 'companies/' . $_SESSION['DatabaseName'] . '/expenses_receipts/'; //Receipts upload directory
48if (isset($_POST['submit'])) {
49	//initialise no input errors assumed initially before we test
50	$InputError = 0;
51	/* actions to take once the user has clicked the submit button
52	ie the page has called itself with some user input */
53	//first off validate inputs sensible
54	if ($_POST['SelectedExpense'] == '') {
55		$InputError = 1;
56		prnMsg(_('You have not selected an expense to claim on this tab'), 'error');
57	} elseif ($_POST['Amount'] == 0) {
58		$InputError = 1;
59		prnMsg(_('The amount must be greater than 0'), 'error');
60	}
61	if (!is_date($_POST['Date'])) {
62		$InputError = 1;
63		prnMsg(_('The date input is not in the correct format'), 'error');
64	}
65	if (isset($SelectedIndex) and $InputError != 1) { //Edit
66		$SQL = "UPDATE pcashdetails
67			SET date = '" . FormatDateForSQL($_POST['Date']) . "',
68				tag = '" . $_POST['Tag'] . "',
69				codeexpense = '" . $_POST['SelectedExpense'] . "',
70				amount = '" . -filter_number_format($_POST['Amount']) . "',
71				notes = '" . $_POST['Notes'] . "'
72			WHERE counterindex = '" . $SelectedIndex . "'";
73		$Msg = _('The expense record on tab') . ' ' . $SelectedTabs . ' ' . _('has been updated');
74		$Result = DB_query($SQL);
75		foreach ($_POST as $Index => $Value) {
76			if (substr($Index, 0, 5) == 'index') {
77				$Index = $Value;
78				$SQL = "UPDATE pcashdetailtaxes SET pccashdetail='" . $_POST['PcCashDetail' . $Index] . "',
79													calculationorder='" . $_POST['CalculationOrder' . $Index] . "',
80													description='" . $_POST['Description' . $Index] . "',
81													taxauthid='" . $_POST['TaxAuthority' . $Index] . "',
82													purchtaxglaccount='" . $_POST['TaxGLAccount' . $Index] . "',
83													taxontax='" . $_POST['TaxOnTax' . $Index] . "',
84													taxrate='" . $_POST['TaxRate' . $Index] . "',
85													amount='" . -$_POST['TaxAmount' . $Index] . "'
86												WHERE counterindex='" . $Index ."'";
87				$Result = DB_query($SQL);
88			}
89		}
90		if (isset($_FILES['Receipt']) and $_FILES['Receipt']['name'] != '') {
91			$UploadOriginalName = $_FILES['Receipt']['name'];
92			$UploadTempName = $_FILES['Receipt']['tmp_name'];
93			$UploadSize = $_FILES['Receipt']['size'];
94			$UploadType = $_FILES['Receipt']['type'];
95			$UploadError = $_FILES['Receipt']['error'];
96			$UploadTheFile = 'Yes'; //Assume all is well to start off with, but check for the worst
97			$ReceiptSupportedMime = array('image/png','image/jpeg','application/pdf','application/msword','application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); //list of support mime types, corresponding to the list of support file extensions in $ReceiptSupportedExt
98			if ($UploadSize > ($_SESSION['MaxImageSize'] * 1024)) { //Server-side file size check. This will usually be caught by $UploadError == 2 (MAX_FILE_SIZE), but we must not trust the user.
99				prnMsg(_('The uploaded file exceeds the maximum file size of') . ' ' . $_SESSION['MaxImageSize'] . 'KB', 'warn');
100				$UploadTheFile = 'No';
101			} elseif (!in_array($UploadType, $ReceiptSupportedMime) and $UploadError != 2) { //File type check. If $UploadError == 2, then $UploadType will be empty.
102				prnMsg(_('File type not accepted. Only the following file types can be attached') . ': ' . implode(', ', $ReceiptSupportedExt), 'warn');
103				$UploadTheFile = 'No';
104			} elseif ($UploadError == 1 ) {  //upload_max_filesize error check
105				prnMsg(_('The uploaded file exceeds the upload_max_filesize directive in php.ini. Please contact your system administrator.'), 'warn');
106				$UploadTheFile ='No';
107			} elseif ($UploadError == 2 ) {  //Client-side file size error check (MAX_FILE_SIZE)
108				prnMsg(_('The uploaded file exceeds the maximum file size of') . ' ' . $_SESSION['MaxImageSize'] . 'KB', 'warn');
109				$UploadTheFile ='No';
110			} elseif ($UploadError == 3 ) {  //Partial upload error check
111				prnMsg( _('The uploaded file was only partially uploaded. Please try again.'), 'warn');
112				$UploadTheFile ='No';
113			} elseif ($UploadError == 4 ) {  //No file uploaded error check
114				prnMsg( _('No file was uploaded'), 'warn');
115				$UploadTheFile ='No';
116			} elseif ($UploadError == 5 ) {  //Undefined error check
117				prnMsg( _('Undefined error'), 'warn');
118				$UploadTheFile ='No';
119			} elseif ($UploadError == 6 ) {  //Temp directory error check
120				prnMsg( _('A necessary temporary folder is missing. Please contact your system administrator.'), 'warn');
121				$UploadTheFile ='No';
122			} elseif ($UploadError == 7 ) {  //Disk write failure error check
123				prnMsg( _('Cannot write file to disk. Please contact your system administrator.'), 'warn');
124				$UploadTheFile ='No';
125			} elseif ($UploadError == 8 ) {  //Upload stopped by PHP extension error check
126				prnMsg( _('The file upload was stopped by a PHP extension. Please contact your system administrator.'), 'warn');
127				$UploadTheFile ='No';
128			}
129			if ($UploadTheFile == 'Yes') { //Passed all the above validation
130				$ReceiptSQL = "SELECT hashfile,
131								extension
132								FROM pcreceipts
133								WHERE pccashdetail='" . $SelectedIndex . "'
134								LIMIT 1";
135					$ReceiptResult = DB_query($ReceiptSQL);
136					$ReceiptRow = DB_fetch_assoc($ReceiptResult);
137				if (DB_num_rows($ReceiptResult) > 0) { //If expenses record already has an uploaded receipt
138					//Delete existing receipt files from directory
139					$ReceiptHash = $ReceiptRow['hashfile'];
140					$ReceiptExt = $ReceiptRow['extension'];
141					$ReceiptFileName = $ReceiptHash . '.' . $ReceiptExt;
142					$ReceiptPath = $ReceiptDir . $ReceiptFileName;
143					unlink($ReceiptPath);
144					//Upload the new receipt file.
145					if (!file_exists($ReceiptDir)) { //Create the receipts directory if it doesn't already exist
146					mkdir($ReceiptDir, 0775, true);
147					}
148					$ReceiptHash = md5(md5_file($UploadTempName) . microtime()); //MD5 hash of uploaded file with timestamp
149					$ReceiptExt = strtolower(pathinfo($UploadOriginalName, PATHINFO_EXTENSION)); //Grab the file extension of the uploaded file
150					$ReceiptFileName = $ReceiptHash . '.' . $ReceiptExt; //Rename the uploaded file with the expenses index number
151					$ReceiptPath = $ReceiptDir . $ReceiptFileName;
152					move_uploaded_file($UploadTempName, $ReceiptPath); //Move the uploaded file from the temp directory to the receipts directory
153					//Update receipt file info in database
154					$ReceiptSQL = "UPDATE pcreceipts SET hashfile='" . $ReceiptHash . "',
155													type='" . $UploadType . "',
156													extension='" . $ReceiptExt . "',
157													size=" . $UploadSize . "
158												WHERE pccashdetail='" . $SelectedIndex . "'";
159					$ReceiptResult = DB_query($ReceiptSQL);
160				} else { //If expenses record does not already have an uploaded receipt
161					if (!file_exists($ReceiptDir)) { //Create the receipts directory if it doesn't already exist
162					mkdir($ReceiptDir, 0775, true);
163					}
164					$ReceiptExt = strtolower(pathinfo($UploadOriginalName, PATHINFO_EXTENSION)); //Grab the file extension of the uploaded file
165					$ReceiptHash = md5(md5_file($UploadTempName) . microtime()); //MD5 hash of uploaded file with timestamp
166					$ReceiptFileName = $ReceiptHash . '.' . $ReceiptExt; //Rename the uploaded file with the expenses index number
167					$ReceiptPath = $ReceiptDir . $ReceiptFileName;
168					move_uploaded_file($UploadTempName, $ReceiptPath); //Move the uploaded file from the temp directory to the receipts directory
169					$ReceiptSQL = "INSERT INTO pcreceipts (counterindex,
170													pccashdetail,
171													hashfile,
172													type,
173													extension,
174													size
175												) VALUES (
176													NULL,
177													'" . $SelectedIndex . "',
178													'" . $ReceiptHash . "',
179													'" . $UploadType . "',
180													'" . $ReceiptExt . "',
181													" . $UploadSize . "
182													)";
183					$ReceiptResult = DB_query($ReceiptSQL);
184				}
185			}
186		}
187		prnMsg($Msg, 'success');
188	} elseif ($InputError != 1) {
189		// First check the type is not being duplicated
190		// Add new record on submit
191		$SQL = "INSERT INTO pcashdetails (counterindex,
192										tabcode,
193										tag,
194										date,
195										codeexpense,
196										amount,
197										authorized,
198										posted,
199										purpose,
200										notes)
201								VALUES (NULL,
202										'" . $_POST['SelectedTabs'] . "',
203										'" . $_POST['Tag'] . "',
204										'" . FormatDateForSQL($_POST['Date']) . "',
205										'" . $_POST['SelectedExpense'] . "',
206										'" . -filter_number_format($_POST['Amount']) . "',
207										0,
208										0,
209										'" . $_POST['Purpose'] . "',
210										'" . $_POST['Notes'] . "'
211										)";
212		$Msg = _('The expense claim on tab') . ' ' . $_POST['SelectedTabs'] . ' ' . _('has been created');
213		$Result = DB_query($SQL);
214		$SelectedIndex = DB_Last_Insert_ID('pcashdetails', 'counterindex');
215		foreach ($_POST as $Index => $Value) {
216			if (substr($Index, 0, 5) == 'index') {
217				$Index = $Value;
218				$SQL = "INSERT INTO pcashdetailtaxes (counterindex,
219														pccashdetail,
220														calculationorder,
221														description,
222														taxauthid,
223														purchtaxglaccount,
224														taxontax,
225														taxrate,
226														amount
227												) VALUES (
228														NULL,
229														'" . $SelectedIndex . "',
230														'" . $_POST['CalculationOrder' . $Index] . "',
231														'" . $_POST['Description' . $Index] . "',
232														'" . $_POST['TaxAuthority' . $Index] . "',
233														'" . $_POST['TaxGLAccount' . $Index] . "',
234														'" . $_POST['TaxOnTax' . $Index] . "',
235														'" . $_POST['TaxRate' . $Index] . "',
236														'" . -$_POST['TaxAmount' . $Index] . "'
237												)";
238				$Result = DB_query($SQL);
239			}
240		}
241		if (isset($_FILES['Receipt']) and $_FILES['Receipt']['name'] != '') {
242			$UploadOriginalName = $_FILES['Receipt']['name'];
243			$UploadTempName = $_FILES['Receipt']['tmp_name'];
244			$UploadSize = $_FILES['Receipt']['size'];
245			$UploadType = $_FILES['Receipt']['type'];
246			$UploadError = $_FILES['Receipt']['error'];
247			$UploadTheFile = 'Yes'; //Assume all is well to start off with, but check for the worst
248			$ReceiptSupportedMime = array('image/png','image/jpeg','application/pdf','application/msword','application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); //list of support mime types, corresponding to the list of support file extensions in $ReceiptSupportedExt
249			if ($UploadSize > ($_SESSION['MaxImageSize'] * 1024)) { //Server-side file size check. This will usually be caught by $UploadError == 2 (MAX_FILE_SIZE), but we must not trust the user.
250				prnMsg(_('The uploaded file exceeds the maximum file size of') . ' ' . $_SESSION['MaxImageSize'] . 'KB', 'warn');
251				$UploadTheFile = 'No';
252			} elseif (!in_array($UploadType, $ReceiptSupportedMime) and $UploadError != 2) { //File type check. If $UploadError == 2, then $UploadType will be empty.
253				prnMsg(_('File type not accepted. Only the following file types can be attached') . ': ' . implode(', ', $ReceiptSupportedExt), 'warn');
254				$UploadTheFile = 'No';
255			} elseif ($UploadError == 1 ) {  //upload_max_filesize error check
256				prnMsg(_('The uploaded file exceeds the upload_max_filesize directive in php.ini. Please contact your system administrator.'), 'warn');
257				$UploadTheFile ='No';
258			} elseif ($UploadError == 2 ) {  //Client-side file size error check (MAX_FILE_SIZE)
259				prnMsg(_('The uploaded file exceeds the maximum file size of') . ' ' . $_SESSION['MaxImageSize'] . 'KB', 'warn');
260				$UploadTheFile ='No';
261			} elseif ($UploadError == 3 ) {  //Partial upload error check
262				prnMsg( _('The uploaded file was only partially uploaded. Please try again.'), 'warn');
263				$UploadTheFile ='No';
264			} elseif ($UploadError == 4 ) {  //No file uploaded error check
265				prnMsg( _('No file was uploaded'), 'warn');
266				$UploadTheFile ='No';
267			} elseif ($UploadError == 5 ) {  //Undefined error check
268				prnMsg( _('Undefined error'), 'warn');
269				$UploadTheFile ='No';
270			} elseif ($UploadError == 6 ) {  //Temp directory error check
271				prnMsg( _('A necessary temporary folder is missing. Please contact your system administrator.'), 'warn');
272				$UploadTheFile ='No';
273			} elseif ($UploadError == 7 ) {  //Disk write failure error check
274				prnMsg( _('Cannot write file to disk. Please contact your system administrator.'), 'warn');
275				$UploadTheFile ='No';
276			} elseif ($UploadError == 8 ) {  //Upload stopped by PHP extension error check
277				prnMsg( _('The file upload was stopped by a PHP extension. Please contact your system administrator.'), 'warn');
278				$UploadTheFile ='No';
279			}
280			if ($UploadTheFile == 'Yes') { //Passed all the above validation
281				if (!file_exists($ReceiptDir)) { //Create the receipts directory if it doesn't already exist
282				mkdir($ReceiptDir, 0775, true);
283				}
284				$ReceiptHash = md5(md5_file($UploadTempName) . microtime()); //MD5 hash of uploaded file with timestamp
285				$ReceiptExt = strtolower(pathinfo($UploadOriginalName, PATHINFO_EXTENSION)); //Grab the file extension of the uploaded file
286				$ReceiptFileName = $ReceiptHash . '.' . $ReceiptExt; //Rename the uploaded file with the expenses index number
287				$ReceiptPath = $ReceiptDir . $ReceiptFileName;
288				move_uploaded_file($UploadTempName, $ReceiptPath); //Move the uploaded file from the temp directory to the receipts directory
289				$ReceiptSQL = "INSERT INTO pcreceipts (counterindex,
290												pccashdetail,
291												hashfile,
292												type,
293												extension,
294												size
295											) VALUES (
296												NULL,
297												'" . $SelectedIndex . "',
298												'" . $ReceiptHash . "',
299												'" . $UploadType . "',
300												'" . $ReceiptExt . "',
301												" . $UploadSize . "
302												)";
303				$ReceiptResult = DB_query($ReceiptSQL);
304			}
305		}
306		prnMsg($Msg, 'success');
307	}
308	if ($InputError != 1) {
309		unset($_POST['SelectedExpense']);
310		unset($_POST['Amount']);
311		unset($_POST['Tag']);
312		unset($_POST['Date']);
313		unset($_POST['Purpose']);
314		unset($_POST['Notes']);
315		unset($_FILES['Receipt']);
316	}
317} elseif (isset($_GET['delete'])) {
318	$ReceiptSQL = "SELECT hashfile,
319					extension
320					FROM pcreceipts
321					WHERE pccashdetail='" . $SelectedIndex . "'
322					LIMIT 1";
323		$ReceiptResult = DB_query($ReceiptSQL);
324		$ReceiptRow = DB_fetch_assoc($ReceiptResult);
325	if (DB_num_rows($ReceiptResult) > 0) {
326	//Delete receipt files from directory
327	$ReceiptHash = $ReceiptRow['hashfile'];
328	$ReceiptExt = $ReceiptRow['extension'];
329	$ReceiptFileName = $ReceiptHash . '.' . $ReceiptExt;
330	$ReceiptPath = $ReceiptDir . $ReceiptFileName;
331	unlink($ReceiptPath);
332	//Delete receipt file info from database
333	$SQL = "DELETE FROM pcreceipts
334			WHERE pccashdetail='" . $SelectedIndex . "'";
335	$ErrMsg = _('Petty Cash Expense record could not be deleted because');
336	$Result = DB_query($SQL, $ErrMsg);
337	}
338	//Delete expenses record & associated taxes
339	$SQL = "DELETE FROM pcashdetails, pcashdetailtaxes
340				USING pcashdetails
341				INNER JOIN pcashdetailtaxes
342				ON pcashdetails.counterindex = pcashdetailtaxes.pccashdetail
343				WHERE pcashdetails.counterindex = '" . $SelectedIndex . "'";
344	$Result = DB_query($SQL, $ErrMsg);
345	prnMsg(_('The expense record on tab') . ' ' . $SelectedTabs . ' ' . _('has been deleted'), 'success');
346	unset($_GET['delete']);
347} //end of get delete
348if (!isset($SelectedTabs)) {
349	/* It could still be the first time the page has been run and a record has been selected for modification - SelectedTabs will exist because it was sent with the new call. If its the first time the page has been displayed with no parameters
350	then none of the above are true and the list of sales types will be displayed with
351	links to delete or edit each. These will call the same page again and allow update/input
352	or deletion of the records*/
353	echo '<p class="page_title_text">
354			<img src="', $RootPath, '/css/', $_SESSION['Theme'], '/images/money_add.png" title="', _('Payment Entry'), '" alt="" />', ' ', $Title, '
355		</p>';
356	echo '<form method="post" action="', htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8'), '" enctype="multipart/form-data">';
357	echo '<input type="hidden" name="FormID" value="', $_SESSION['FormID'], '" />';
358	echo '<table class="selection">
359			<tr>
360				<td>', _('Clain expenses on petty cash tab'), ':</td>
361				<td><select required="required" name="SelectedTabs">';
362	$SQL = "SELECT tabcode
363		FROM pctabs
364		WHERE usercode='" . $_SESSION['UserID'] . "'";
365	$Result = DB_query($SQL);
366	echo '<option value="">', _('Not Yet Selected'), '</option>';
367	while ($MyRow = DB_fetch_array($Result)) {
368		if (isset($_POST['SelectTabs']) and $MyRow['tabcode'] == $_POST['SelectTabs']) {
369			echo '<option selected="selected" value="', $MyRow['tabcode'], '">', $MyRow['tabcode'], '</option>';
370		} else {
371			echo '<option value="', $MyRow['tabcode'], '">', $MyRow['tabcode'], '</option>';
372		}
373	} //end while loop
374	echo '</select>
375			</td>
376		</tr>';
377	echo '</table>'; // close main table
378	echo '<div class="centre">
379			<input type="submit" name="Process" value="', _('Accept'), '" />
380			<input type="submit" name="Cancel" value="', _('Cancel'), '" />
381		</div>';
382	echo '</form>';
383} else { // isset($SelectedTabs)
384	echo '<div class="centre">
385			<a href="', htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8'), '">', _('Select another tab'), '</a>
386		</div>';
387	echo '<p class="page_title_text">
388			<img src="', $RootPath, '/css/', $_SESSION['Theme'], '/images/money_add.png" title="', _('Petty Cash Claim Entry'), '" alt="" />', ' ', $Title, '
389		</p>';
390	if (!isset($_GET['edit']) or isset($_POST['GO'])) {
391		if (!isset($Days)) {
392			$Days = 30;
393		}
394		/* Retrieve decimal places to display */
395		$SQLDecimalPlaces = "SELECT decimalplaces
396					FROM currencies,pctabs
397					WHERE currencies.currabrev = pctabs.currency
398						AND tabcode='" . $SelectedTabs . "'";
399		$Result = DB_query($SQLDecimalPlaces);
400		$MyRow = DB_fetch_array($Result);
401		$CurrDecimalPlaces = $MyRow['decimalplaces'];
402		echo '<form method="post" action="', htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8'), '" enctype="multipart/form-data">';
403		echo '<input type="hidden" name="FormID" value="', $_SESSION['FormID'], '" />';
404		echo '<br /><table class="selection">';
405		echo '<tr>
406				<td>' . _('Petty Cash Tab') . ':</td>
407				<td>' . $SelectedTabs . '</td>
408			  </tr>';
409		echo '</table>';
410
411		//Limit expenses history to X days
412		echo '<table class="selection">
413				<tr>
414					<td>', _('Detail of Tab Movements For Last '), ':
415						<input type="hidden" name="SelectedTabs" value="' . $SelectedTabs . '" />
416						<input type="text" class="number" name="Days" value="', $Days, '" required="required" maxlength="3" size="4" /> ', _('Days'), '
417						<input type="submit" name="Go" value="', _('Go'), '" />
418					</td>
419				</tr>
420			</table>';
421		if (isset($_POST['Cancel'])) {
422			unset($_POST['SelectedExpense']);
423			unset($_POST['Amount']);
424			unset($_POST['Date']);
425			unset($_POST['Purpose']);
426			unset($_POST['Notes']);
427			unset($_FILES['Receipt']);
428		}
429		$SQL = "SELECT counterindex,
430						tabcode,
431						tag,
432						date,
433						codeexpense,
434						amount,
435						authorized,
436						posted,
437						purpose,
438						notes
439					FROM pcashdetails
440					WHERE tabcode='" . $SelectedTabs . "'
441						AND date >=DATE_SUB(CURDATE(), INTERVAL " . $Days . " DAY)
442					ORDER BY date,
443							counterindex ASC";
444		$Result = DB_query($SQL);
445		echo '<table class="selection">
446				<thead>
447					<tr>
448						<th class="ascending">', _('Date of Expense'), '</th>
449						<th class="ascending">', _('Expense Code'), '</th>
450						<th class="ascending">', _('Gross Amount'), '</th>
451						<th>', _('Tax'), '</th>
452						<th>', _('Tax Group'), '</th>
453						<th>', _('Tag'), '</th>
454						<th>', _('Business Purpose'), '</th>
455						<th>', _('Notes'), '</th>
456						<th>', _('Receipt Attachment'), '</th>
457						<th class="ascending">', _('Date Authorised'), '</th>
458					</tr>
459				</thead>
460				<tbody>';
461
462		while ($MyRow = DB_fetch_array($Result)) {
463			$SQLDes = "SELECT description
464						FROM pcexpenses
465						WHERE codeexpense='" . $MyRow['codeexpense'] . "'";
466			$ResultDes = DB_query($SQLDes);
467			$Description = DB_fetch_array($ResultDes);
468
469			if (!isset($Description[0])) {
470				$ExpenseCodeDes = 'ASSIGNCASH';
471			} else {
472					$ExpenseCodeDes = $MyRow['codeexpense'] . ' - ' . $Description[0];
473			}
474
475			if ($MyRow['authorized'] == '0000-00-00') {
476				$AuthorisedDate = _('Unauthorised');
477			} else {
478				$AuthorisedDate = ConvertSQLDate($MyRow['authorized']);
479			}
480
481			//Generate download link for expense receipt, or show text if no receipt file is found.
482			$ReceiptSQL = "SELECT hashfile,
483								extension
484								FROM pcreceipts
485								WHERE pccashdetail='" . $MyRow['counterindex'] . "'";
486					$ReceiptResult = DB_query($ReceiptSQL);
487					$ReceiptRow = DB_fetch_array($ReceiptResult);
488			if (DB_num_rows($ReceiptResult) > 0) { //If receipt exists in database
489				$ReceiptHash = $ReceiptRow['hashfile'];
490				$ReceiptExt = $ReceiptRow['extension'];
491				$ReceiptFileName = $ReceiptHash . '.' . $ReceiptExt;
492				$ReceiptPath = $ReceiptDir . $ReceiptFileName;
493				$ReceiptText = '<a href="' . $ReceiptPath . '" download="ExpenseReceipt-' . mb_strtolower($SelectedTabs) . '-[' . $MyRow['date'] . ']-[' . $MyRow['counterindex'] . ']">' . _('Download attachment') . '</a>';
494			} elseif ($ExpenseCodeDes == 'ASSIGNCASH') {
495				$ReceiptText = '';
496			} else {
497				$ReceiptText = _('No attachment');
498			}
499
500			$TagSQL = "SELECT tagdescription FROM tags WHERE tagref='" . $MyRow['tag'] . "'";
501			$TagResult = DB_query($TagSQL);
502			$TagRow = DB_fetch_array($TagResult);
503			if ($MyRow['tag'] == 0) {
504				$TagRow['tagdescription'] = _('None');
505			}
506			$TagTo = $MyRow['tag'];
507			if ($ExpenseCodeDes == 'ASSIGNCASH') {
508				$TagDescription = '';
509			} else {
510				$TagDescription = $TagTo . ' - ' . $TagRow['tagdescription'];
511			}
512
513			$TaxesDescription = '';
514			$TaxesTaxAmount = '';
515			$TaxSQL = "SELECT counterindex,
516								pccashdetail,
517								calculationorder,
518								description,
519								taxauthid,
520								purchtaxglaccount,
521								taxontax,
522								taxrate,
523								amount
524							FROM pcashdetailtaxes
525							WHERE pccashdetail='" . $MyRow['counterindex'] . "'";
526			$TaxResult = DB_query($TaxSQL);
527			while ($MyTaxRow = DB_fetch_array($TaxResult)) {
528				$TaxesDescription .= $MyTaxRow['description'] . '<br />';
529				$TaxesTaxAmount .= locale_number_format($MyTaxRow['amount'], $CurrDecimalPlaces) . '<br />';
530			}
531			if (($MyRow['authorized'] == '0000-00-00') and ($ExpenseCodeDes != 'ASSIGNCASH')) {
532				// only movements NOT authorised can be modified or deleted
533				echo '<tr class="striped_row">
534						<td>', ConvertSQLDate($MyRow['date']), '</td>
535						<td>', $ExpenseCodeDes, '</td>
536						<td class="number">', locale_number_format($MyRow['amount'], $CurrDecimalPlaces), '</td>
537						<td class="number">', $TaxesTaxAmount, '</td>
538						<td>', $TaxesDescription, '</td>
539						<td>', $TagDescription, '</td>
540						<td>', $MyRow['purpose'], '</td>
541						<td>', $MyRow['notes'], '</td>
542						<td>', $ReceiptText, '</td>
543						<td>', $AuthorisedDate, '</td>
544						<td><a href="', htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '?SelectedIndex=', $MyRow['counterindex'], '&SelectedTabs=' . $SelectedTabs . '&amp;Days=' . $Days . '&amp;edit=yes">' . _('Edit') . '</a></td>
545						<td><a href="', htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '?SelectedIndex=', $MyRow['counterindex'], '&amp;SelectedTabs=' . $SelectedTabs . '&amp;Days=' . $Days . '&amp;delete=yes" onclick=\'return confirm("' . _('Are you sure you wish to delete this expense?') . '");\'>' . _('Delete') . '</a></td>
546					</tr>';
547			} else {
548				echo '<tr class="striped_row">
549						<td>', ConvertSQLDate($MyRow['date']), '</td>
550						<td>', $ExpenseCodeDes, '</td>
551						<td class="number">', locale_number_format($MyRow['amount'], $CurrDecimalPlaces), '</td>
552						<td class="number">', $TaxesTaxAmount, '</td>
553						<td>', $TaxesDescription, '</td>
554						<td>', $TagDescription, '</td>
555						<td>', $MyRow['purpose'], '</td>
556						<td>', $MyRow['notes'], '</td>
557						<td>', $ReceiptText, '</td>
558						<td>', $AuthorisedDate, '</td>
559					</tr>';
560			}
561		}
562		//END WHILE LIST LOOP
563		$SQLAmount = "SELECT sum(amount)
564					FROM pcashdetails
565					WHERE tabcode='" . $SelectedTabs . "'";
566		$ResultAmount = DB_query($SQLAmount);
567		$Amount = DB_fetch_array($ResultAmount);
568		if (!isset($Amount['0'])) {
569			$Amount['0'] = 0;
570		}
571		echo '</tbody>
572				<tfoot>
573					<tr>
574					<td colspan="2" class="number">', _('Current balance'), ':</td>
575					<td class="number">', locale_number_format($Amount['0'], $CurrDecimalPlaces), '</td>
576					</tr>
577				</tfoot>';
578		echo '</table>';
579		echo '</form>';
580	}
581	if (!isset($_GET['delete'])) {
582		echo '<form method="post" action="', htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8'), '" enctype="multipart/form-data">';
583		echo '<input type="hidden" name="FormID" value="', $_SESSION['FormID'], '" />';
584		if (isset($_GET['edit'])) {
585			$SQL = "SELECT counterindex,
586							tabcode,
587							tag,
588							date,
589							codeexpense,
590							amount,
591							authorized,
592							posted,
593							purpose,
594							notes
595						FROM pcashdetails
596						WHERE counterindex='" . $SelectedIndex . "'";
597			$Result = DB_query($SQL);
598			$MyRow = DB_fetch_array($Result);
599			$_POST['Date'] = ConvertSQLDate($MyRow['date']);
600			$_POST['SelectedExpense'] = $MyRow['codeexpense'];
601			$_POST['Amount'] = -$MyRow['amount'];
602			$_POST['Purpose'] = $MyRow['purpose'];
603			$_POST['Notes'] = $MyRow['notes'];
604			$_POST['Tag'] = $MyRow['tag'];
605			echo '<input type="hidden" name="SelectedTabs" value="', $SelectedTabs, '" />';
606			echo '<input type="hidden" name="SelectedIndex" value="', $SelectedIndex, '" />';
607			echo '<input type="hidden" name="Days" value="', $Days, '" />';
608		} //end of Get Edit
609		if (!isset($_POST['Date'])) {
610			$_POST['Date'] = Date($_SESSION['DefaultDateFormat']);
611		}
612		echo '<table class="selection">';
613		if (isset($_GET['SelectedIndex'])) {
614			echo '<tr>
615					<th colspan="2"><h3>', _('Update Expense'), '</h3></th>
616				</tr>';
617		} else {
618			echo '<tr>
619					<th colspan="2"><h3>', _('New Expense'), '</h3></th>
620				</tr>';
621		}
622		echo '<tr>
623				<td>', _('Date of Expense'), ':</td>
624				<td>
625					<input type="text" class="date" name="Date" size="11" required="required" maxlength="10" value="', $_POST['Date'], '" />
626				</td>
627			</tr>
628			<tr>
629				<td>', _('Expense Code'), ':</td>
630				<td>
631						<select required="required" name="SelectedExpense">';
632		DB_free_result($Result);
633		$SQL = "SELECT pcexpenses.codeexpense,
634					pcexpenses.description,
635					pctabs.defaulttag
636			FROM pctabexpenses, pcexpenses, pctabs
637			WHERE pctabexpenses.codeexpense = pcexpenses.codeexpense
638				AND pctabexpenses.typetabcode = pctabs.typetabcode
639				AND pctabs.tabcode = '" . $SelectedTabs . "'
640			ORDER BY pcexpenses.codeexpense ASC";
641		$Result = DB_query($SQL);
642		echo '<option value="">', _('Not Yet Selected'), '</option>';
643		while ($MyRow = DB_fetch_array($Result)) {
644			if (isset($_POST['SelectedExpense']) and $MyRow['codeexpense'] == $_POST['SelectedExpense']) {
645				echo '<option selected="selected" value="', $MyRow['codeexpense'], '">', $MyRow['codeexpense'], ' - ', $MyRow['description'], '</option>';
646			} else {
647				echo '<option value="', $MyRow['codeexpense'], '">', $MyRow['codeexpense'], ' - ', $MyRow['description'], '</option>';
648			}
649			$DefaultTag = $MyRow['defaulttag'];
650		} //end while loop
651		echo '</select>
652				</td>
653			</tr>';
654		if (!isset($_POST['Amount'])) {
655			$_POST['Amount'] = 0;
656		}
657		echo '<tr>
658				<td>', _('Gross Amount'), ':</td>
659				<td><input type="text" class="number" name="Amount" size="12" required="required" maxlength="11" value="', $_POST['Amount'], '" /></td>
660			</tr>';
661		if (isset($_GET['edit'])) {
662			$SQL = "SELECT counterindex,
663							pccashdetail,
664							calculationorder,
665							description,
666							taxauthid,
667							purchtaxglaccount,
668							taxontax,
669							taxrate,
670							amount
671						FROM pcashdetailtaxes
672						WHERE pccashdetail='" . $SelectedIndex . "'";
673			$TaxesResult = DB_query($SQL);
674			while ($MyTaxRow = DB_fetch_array($TaxesResult)) {
675				echo '<input type="hidden" name="index', $MyTaxRow['counterindex'], '" value="', $MyTaxRow['counterindex'], '" />';
676				echo '<input type="hidden" name="PcCashDetail', $MyTaxRow['counterindex'], '" value="', $MyTaxRow['pccashdetail'], '" />';
677				echo '<input type="hidden" name="CalculationOrder', $MyTaxRow['counterindex'], '" value="', $MyTaxRow['calculationorder'], '" />';
678				echo '<input type="hidden" name="Description', $MyTaxRow['counterindex'], '" value="', $MyTaxRow['description'], '" />';
679				echo '<input type="hidden" name="TaxAuthority', $MyTaxRow['counterindex'], '" value="', $MyTaxRow['taxauthid'], '" />';
680				echo '<input type="hidden" name="TaxGLAccount', $MyTaxRow['counterindex'], '" value="', $MyTaxRow['purchtaxglaccount'], '" />';
681				echo '<input type="hidden" name="TaxOnTax', $MyTaxRow['counterindex'], '" value="', $MyTaxRow['taxontax'], '" />';
682				echo '<input type="hidden" name="TaxRate', $MyTaxRow['counterindex'], '" value="', $MyTaxRow['taxrate'], '" />';
683				echo '<tr>
684						<td>', $MyTaxRow['description'], ' - ', ($MyTaxRow['taxrate'] * 100), '%</td>
685						<td><input type="text" class="number" size="12" name="TaxAmount', $MyTaxRow['counterindex'], '" value="', -$MyTaxRow['amount'], '" /></td>
686					</tr>';
687			}
688		} else {
689			$SQL = "SELECT taxgrouptaxes.calculationorder,
690							taxauthorities.description,
691							taxgrouptaxes.taxauthid,
692							taxauthorities.purchtaxglaccount,
693							taxgrouptaxes.taxontax,
694							taxauthrates.taxrate
695						FROM taxauthrates
696						INNER JOIN taxgrouptaxes
697							ON taxauthrates.taxauthority=taxgrouptaxes.taxauthid
698						INNER JOIN taxauthorities
699							ON taxauthrates.taxauthority=taxauthorities.taxid
700						INNER JOIN taxgroups
701							ON taxgroups.taxgroupid=taxgrouptaxes.taxgroupid
702						INNER JOIN pctabs
703							ON pctabs.taxgroupid=taxgroups.taxgroupid
704						WHERE taxauthrates.taxcatid = " . $_SESSION['DefaultTaxCategory'] . "
705							AND pctabs.tabcode='" . $SelectedTabs . "'
706						ORDER BY taxgrouptaxes.calculationorder";
707			$TaxResult = DB_query($SQL);
708			$i = 0;
709			while ($MyTaxRow = DB_fetch_array($TaxResult)) {
710				echo '<input type="hidden" name="index', $i, '" value="', $i, '" />';
711				echo '<input type="hidden" name="CalculationOrder', $i, '" value="', $MyTaxRow['calculationorder'], '" />';
712				echo '<input type="hidden" name="Description', $i, '" value="', $MyTaxRow['description'], '" />';
713				echo '<input type="hidden" name="TaxAuthority', $i, '" value="', $MyTaxRow['taxauthid'], '" />';
714				echo '<input type="hidden" name="TaxGLAccount', $i, '" value="', $MyTaxRow['purchtaxglaccount'], '" />';
715				echo '<input type="hidden" name="TaxOnTax', $i, '" value="', $MyTaxRow['taxontax'], '" />';
716				echo '<input type="hidden" name="TaxRate', $i, '" value="', $MyTaxRow['taxrate'], '" />';
717				echo '<tr>
718						<td>', $MyTaxRow['description'], ' - ', ($MyTaxRow['taxrate'] * 100), '%:</td>
719						<td><input type="text" class="number" size="12" name="TaxAmount', $i, '" value="0" /></td>
720					</tr>';
721				++$i;
722			}
723		}
724
725		//Select the tag
726		echo '<tr>
727				<td>', _('Tag'), ':</td>
728				<td><select name="Tag">';
729		$SQL = "SELECT tagref,
730					tagdescription
731			FROM tags
732			ORDER BY tagref";
733		$Result = DB_query($SQL);
734		if (!isset($_POST['Tag'])) {
735			$_POST['Tag'] = $DefaultTag;
736		}
737		echo '<option value="0">0 - ', _('None'), '</option>';
738		while ($MyRow = DB_fetch_array($Result)) {
739			if ($_POST['Tag'] == $MyRow['tagref']) {
740				echo '<option selected="selected" value="', $MyRow['tagref'], '">', $MyRow['tagref'], ' - ', $MyRow['tagdescription'], '</option>';
741			} else {
742				echo '<option value="', $MyRow['tagref'], '">', $MyRow['tagref'], ' - ', $MyRow['tagdescription'], '</option>';
743			}
744		}
745		echo '</select>
746				</td>
747			</tr>';
748		// End select tag
749
750		//For the accept attribute of the file element, prefix dots to the front of each supported file extension.
751		$ReceiptSupportedExtDotPrefix = array_map(function($ReceiptSupportedExt) {
752			return '.' . $ReceiptSupportedExt;
753		}, $ReceiptSupportedExt);
754		echo '<tr>
755				<td>', _('Attach Receipt'), ':</td>
756				<td>
757				<input type="hidden" name="MAX_FILE_SIZE" value="' . $_SESSION['MaxImageSize'] * 1024 . '" />
758				<input type="file" name="Receipt" id="Receipt" accept="' . implode(',', $ReceiptSupportedExtDotPrefix) . '" title="', _('Accepted file types'), ': ', implode(', ', $ReceiptSupportedExt), '" />
759				</td>
760			</tr>';
761
762		if (!isset($_POST['Purpose'])) {
763			$_POST['Purpose'] = '';
764		}
765		echo '<tr>
766				<td>', _('Business Purpose'), ':</td>
767				<td>
768					<input type="text" name="Purpose" size="50" maxlength="49" required="required" value="', $_POST['Purpose'], '" />
769				</td>
770			</tr>';
771
772		if (!isset($_POST['Notes'])) {
773			$_POST['Notes'] = '';
774		}
775		echo '<tr>
776				<td>', _('Notes'), ':</td>
777				<td>
778					<input type="text" name="Notes" size="50" maxlength="49" value="', $_POST['Notes'], '" />
779				</td>
780			</tr>';
781
782		echo '</table>'; // close main table
783		echo '<input type="hidden" name="SelectedTabs" value="', $SelectedTabs, '" />';
784		echo '<input type="hidden" name="Days" value="', $Days, '" />';
785		echo '<div class="centre">
786				<input type="submit" name="submit" value="', _('Accept'), '" />
787				<input type="submit" name="Cancel" value="', _('Cancel'), '" />
788			</div>';
789		echo '</form>';
790	} // end if user wish to delete
791}
792include('includes/footer.php');
793?>