<?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 = 'user';
$updateString = ''; 
$udID = ''; 

$fieldArray = array('userID','clientID','userAuth','userName','userPassword','userPass','userSalt','userFirstName','userLastName','userEmail','userStatus','userActiveDate','userExpireDate','userLastLogin');
$excludeArray = array('op','submit','adminType','userSalt','userPass');

if (!empty($_POST['op'])) {
	$op = $_POST['op'];
	
	if ($op == 'delete') {
		$editID = $_POST['editID'];
		$query = 'UPDATE users SET userStatus=0 WHERE userID='. $editID;
		$result = $con->query($query);
	} else {
		foreach($_POST as $key => $value) {
			if (in_array($key,$excludeArray)) {
				// Do Not Include in query
			} elseif ($key == 'newPass') {
				if (!empty($value)) {
					$secPW = generateHashWithSalt($value);	
					$fieldArr[] = 'userSalt';
					$valueArr[] = "'". $secPW['salt'] ."'";
					$fieldArr[] = 'userPass';
					$valueArr[] = "'". $secPW['pw'] ."'";
				} else {
					$fieldArr[] = 'userSalt';
					$valueArr[] = "'". $_POST['userSalt'] ."'";
					$fieldArr[] = 'userPass';
					$valueArr[] = "'". $_POST['userPass'] ."'";
				}
			} else {
				if ($key == 'editID') {
					$key = 'userID'; 
					$udID = $value; 
				} elseif ($key == 'authID') {
					$key = 'userAuth'; 
				} elseif ($key == 'compID') {
					$key = 'clientID'; 
				} else {
					if ($key == 'userStatus') {
						if ($op == "delete")
							$value = 0;
						elseif ($op == "react")
							$value = 1;
						else
							$value = $_POST[$value];
					}
				}
				$fieldArr[] = $key;
				$valueArr[] = "'". $value ."'";
			}
		}
		$fieldString = implode(',',$fieldArr);
		$valueString = implode(',',$valueArr);
		
		$query = 'REPLACE INTO users ('. $fieldString .') VALUES ('. $valueString .')';
		$result = $con->query($query);
		$editID = (!empty($udID) ? $udID : $con->insert_id);
	}
	$updateID = (($page == 'dash') ? 'user-'. $editID : 'record-'. $editID);
	$output = (($result) ? array('update'=>$updateID,'updateOP'=>$op,'updateString'=>$updateString) : 'UPDATE ERROR');
} else {
	$output = 'ERROR 2'; 	
}

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

?>