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

if (!empty($_POST['op'])) {
	$insertFields = '';
	$insertValues = ''; 
	foreach($_POST as $key => $value) {
		if (($key == 'op')||($key == 'submit')||($key == 'adminType')) {
			// Do not include in update string
		} elseif (substr($key, 0, 4) == "inv_") {
			$updateArray = explode('_',$key);
			list($inv,$updateID) = $updateArray;
			$query = "UPDATE payments SET invoiceDate='". $value ."' WHERE paymentID=" . $updateID;
			$result = $con->query($query);
		} elseif (substr($key, 0, 4) == "amt_") {
			$updateArray = explode('_',$key);
			list($amt,$updateID) = $updateArray;
			$query = "UPDATE payments SET paymentAmount='". $value ."' WHERE paymentID=" . $updateID;
			$result = $con->query($query);
		} elseif (substr($key, 0, 4) == "pmt_") {
			$updateArray = explode('_',$key);
			list($pmt,$updateID) = $updateArray;
			$query = "UPDATE payments SET paymentStatus='". $value ."' WHERE paymentID=" . $updateID;
			$result = $con->query($query);
		} elseif (substr($key, 0, 4) == "dat_") {
			$updateArray = explode('_',$key);
			list($dat,$updateID) = $updateArray;
			$query = "UPDATE payments SET paymentDate='". $value ."' WHERE paymentID=" . $updateID;
			$result = $con->query($query);
		} elseif (substr($key, 0, 5) == "note_") {
			$updateArray = explode('_',$key);
			list($note,$updateID) = $updateArray;
			$query = "UPDATE payments SET paymentNote='". $value ."' WHERE paymentID=" . $updateID;
			$result = $con->query($query);
		} else {
			$insertFields .= $key .',';
			$insertValues .= '"' . $value .'",';
		}
	}
	
	// Remove Last comma from string to avoid mySQL errors
	$insertFields = substr($insertFields, 0, strlen($insertFields)-1);
	$insertValues = substr($insertValues, 0, strlen($insertValues)-1);
	
	$insertTest = str_replace('"','',$insertValues);
	$insertTest = str_replace(',','',$insertTest);

	if (!is_numeric($insertTest)) {
		$query = 'INSERT INTO payments ('. $insertFields .') VALUES (' . $insertValues . ')';
		//echo '<p>'. $query . '</p>';
		$result = $con->query($query);
	}
	$output = (($result) ? 'SUCCESS' : 'ERROR');
} else {
	$output = 'ERROR'; 	
}

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

?>