<?php
session_start();
global $ROOT, $PATH, $phpself;
$ROOT = $_SERVER['DOCUMENT_ROOT'];
$PATH = '../../';  
$phpself = basename(__FILE__);
require_once($PATH . 'globals/globals.php');
$adminAct = $_REQUEST['adminType']; 
$admin = 'expense';
$updateString = ''; 
$udID = ''; 

if (!empty($_POST['op'])) {
	$op = $_POST['op'];
	
	if ($op == 'delete') {
		$editID = $_POST['editID'];
		$query = 'UPDATE expenses SET expDisp=0 WHERE expID='. $editID;
		$result = $con->query($query);
	} else {
		$fieldString = '';
		$valueString = '';
		foreach($_POST as $key => $value) {
			
			if (($key == 'submit')||($key == 'expDisp')||($key == 'expReimbursable')||($key == 'adminType')) {
				// Do Not Include in query
			}
			elseif ($key == 'op') {
				if ($op == "delete") {
					$fieldString .= 'expDisp,';
					$valueString .= '"0",';
				} else  {
					if ($op == "react") {
						$fieldString .= 'expDisp,';
						$valueString .= '"1",';
					} else {
						$fieldString .= 'expDisp,';
						$valueString .= '"'. $_POST['expDisp'] .'",';
					}
				}
			} else {
				if ($key == 'editID') {
					$key = 'expID';
					$udID = $value; 
				} elseif ($key == 'compID')
					$key = 'clientID';
				$fieldString .= $key .',';
				$valueString .= '"'. $value .'",';
			}
		}
		
		// Expense Reimbursable
		if (empty($_POST['expReimbursable'])) {
			$fieldString .= 'expReimbursable,';	
			$valueString .= '"0",';
		}
		else {
			$fieldString .= 'expReimbursable,';	
			$valueString .= '"'. $_POST['expReimbursable'] .'",';
		}
		
		// Remove Last comma from string to avoid mySQL errors
		$fieldString = substr($fieldString,0,strlen($fieldString)-1);
		$valueString = substr($valueString,0,strlen($valueString)-1);
		
		$query = 'REPLACE INTO expenses ('. $fieldString .') VALUES ('. $valueString .')';
		$result = $con->query($query);
		$editID = (!empty($udID) ? $udID : $con->insert_id);
	}
	$updateID = (($page == 'dash') ? 'expense-'. $editID : 'record-'. $editID);
	$output = (($result) ? array('update'=>$updateID,'updateOP'=>$op,'updateString'=>$updateString) : 'UPDATE ERROR'); 
} else {
	$output = 'ERROR'; 	
}

if ($con) $con->close(); 

header('Content-Type: application/json; charset=utf-8', true); 
echo json_encode(array("output"=>$output));

?>