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

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

if (!empty($_POST['op'])) {
	$op = $_POST['op'];
	
	if ($op == 'delete') {
		$editID = $_POST['editID'];
		$query = 'UPDATE tasks SET display=0 WHERE taskID='. $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 .= 'display,';
					$valueString .= '"0",';
				} else  {
					if ($op == "react") {
						$fieldString .= 'display,';
						$valueString .= '"1",';
					} else {
						$fieldString .= 'display,';
						$valueString .= '"'. $_POST['display'] .'",';
					}
				}
			} else {
				if ($key == 'editID') {
					$key = 'taskID';
					$udID  = $value;
				}
				$fieldString .= $key .',';
				$valueString .= '"'. $value .'",';
				if (in_array($key,$variables['displayArray'])) {
					if ($key == 'projectID') {
						$client = ((!empty($value)) ? getProjClient($value,$con) : '');
						$updateArray['client'] = $value;
					} else {
						$updateArray[$key] = $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 tasks ('. $fieldString .') VALUES ('. $valueString .')';
		//echo $query; 
		$result = $con->query($query);
		$editID = (!empty($udID) ? $udID : $con->insert_id);
		
		if ($op != 'delete') {
			if (($page == 'dash')  && (checkTaskDisplay($_POST['taskStatus'],$con)==0)) {
				$op = 'delete';
			} else {	
				$updateInfo = ''; 
				if (($_POST['op'] == 'add') || ($_POST['op'] == 'edit')) {
					$ajaxUpdate = true; 
					if ($page == 'task') {
						include('../list/list-item/task.php');
						$updateString = $listItem;
					} elseif ($page == 'dash') {
						include('../../pages/dashboard/inc/list-item/task.php');
						$updateString = $listItem;
					}
				}
			}
		}
	}
	$updateID = (($page == 'dash') ? 'task-'. $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));

?>