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

$fieldArray = array('campid','camp_date','camp_type','camp_name','camp_desc','camp_contacts','display','date_updated');
$excludeArray = array('camp_date','date_updated');

if (!empty($_POST['op'])) {
	$op = $_POST['op'];
	
	if ($op == 'delete') {
		$editID = $_POST['editID'];
		$query = 'UPDATE marketing_campaigns SET display=0 WHERE campid='. $editID;
		$result = $con->query($query);
	} else {
		$fieldString = '';
		$valueString = '';
		foreach($_POST as $key => $value) {
			if (in_array($key,$fieldArray)) {
				// Do Not Include in query
				if ($key == 'display') {
					if ($op == "delete") {
						$fieldString .= 'display,';
						$valueString .= '0,';
					} else  {
						if ($op == "react") {
							$fieldString .= 'display,';
							$valueString .= '1,';
						} else {
							$fieldString .= 'display,';
							$valueString .= $_POST['display'] .",";
						}
					}
				} else {
					$fieldString .= $key .',';
					if(in_array($key,$excludeArray))
						$valueString .= "'". $value ."',";
					elseif(is_array($value))
						$valueString .= "'". implode(',',$value) ."',";
					elseif($key == 'date_updated')
						$valueString .= "'". $today ."',";
					else
						$valueString .= "'". sanitize_html_string($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 marketing_campaigns ('. $fieldString .') VALUES ('. $valueString .')';
		$result = $con->query($query);
		
		$editID = (!empty($editID) ? $editID : $con->insert_id); 
	}
	$updateID = (($page == 'dash') ? 'campaign-'. $editID : 'record-'. $editID);	
	$output = (($result) ? array('update'=>$updateID,'updateOP'=>$op,'updateString'=>$updateString,'section'=>$_POST['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));


?>