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

$page = (isset($_POST['page']) ? $_POST['page'] : '');
$section = (isset($_POST['section']) ? $_POST['section'] : '');
$variables = getVariables('client',$page);

if (!empty($_POST['op'])) {
	$op = $_POST['op'];
	
	if ($op == 'delete') {
		$editID = $_POST['editID'];
		$query = 'UPDATE clients SET clientType=3 WHERE clientID='. $editID;
		$result = $con->query($query);
	} else {
		$fieldString = '';
		$valueString = '';
		foreach($_POST as $key => $value) {
			if (in_array($key,$variables['excludeArray'])) {
				// Do Not Include in query
			} elseif ($key == 'op') {
				if ($op == "delete") {
					$fieldString .= 'clientStatus,';
					$valueString .= '"1",';
				} else  {
					if ($op == "react") {
						$fieldString .= 'clientStatus,';
						$valueString .= '"2",';
					} else {
						$fieldString .= 'clientStatus,';
						$valueString .= '"'. $_POST['clientStatus'] .'",';
					}
				}
			} elseif ($key == 'compID') {
				$fieldString .= 'subClientOf,';
				$valueString .= '"'. $value .'",';
			} elseif ($key == 'editID') {
				$fieldString .= 'clientID,';
				$valueString .= '"'. $value .'",';
				$udID = $value;
			} elseif ($key == 'ratePercent') {
				$fieldString .= $key .',';
				$valueString .= '"'. $value/100 .'",';
			} elseif (is_array($value)) {
				$fieldString .= $key .',';
				$valueString .= '"'. implode(',',$value) .'",';
			} else {
				$fieldString .= $key .',';
				$valueString .= '"'. $value .'",';
			}
		}
		
		// 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 clients ('. $fieldString .') VALUES ('. $valueString .')';
		//echo $query;
		$result = $con->query($query);
		
		$editID = (!empty($udID) ? $udID : $con->insert_id);
		
		$updateInfo = ''; 
		if (($_POST['op'] == 'add') || ($_POST['op'] == 'edit')) {
			if ($page == 'client') {
				include('../list/list-item/client.php');
				$updateString = $listItem;
			}
		}
		
		/*if (!empty($_REQUEST['loginfo'])) {
			if (empty($_REQUEST['editID']))
				$cID = mysql_insert_id;
			else
				$cID = $_REQUEST['editID'];
			//header("Location: ". $URL ."/admin/loginfo.php?cID=". $cID);
		}*/
	}
	$updateID = (($page == 'dash') ? 'client-'. $editID : 'record-'. $editID);
	$output = (($result) ? array('update'=>$updateID,'updateOP'=>$op,'updateString'=>$updateString,'page'=>$page,'section'=>$section) : 'UPDATE ERROR');
} else {
	$output = 'ERROR'; 	
}

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

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

?>