 <?php
include_once ("_dirinfo.php");
include_once (PATH_TO_ROOT."init.php");
include_once (PATH_TO_ROOT."config.php");
include_once (PATH_TO_ROOT."CRM/_CRM_config.php");
include_once(PATH_TO_ROOT."CRM/class/class.Language-Pack.php");
include_once(PATH_TO_ROOT."CRM/class/class.checkString.php");
include_once (PATH_TO_ROOT.'CRM/class/class.logger.php');
$Logger = new LoggerX($db);

//ini_set("display_errors","1");

$LangPack = new LanguagePack($db, $aLanguage);
$table = "_customerActivities";
if($_POST['action'] == "submit"){
	$activityId = StringChecker::Check($_POST['activityId']);
	$inputDate = StringChecker::Check($_POST['inputDate']);
	$comment = StringChecker::Check($_POST['comment']);
	$id = StringChecker::Check($_POST['id']);
	if($activityId != 6){
		$uploadDir = PATH_TO_ROOT."CRM/_files/_customer_".$id."/";
		
		$r = array();
		if(!file_exists($uploadDir)){
			mkdir($uploadDir, 0777);
			$r['makeDir'] = $uploadDir;
		}
		$fileLocation = $uploadDir.$_FILES['uploadFile']['name'];
		
		if(move_uploaded_file($_FILES['uploadFile']['tmp_name'], $fileLocation)){
			$sql = "INSERT INTO ".WARPIT_CRM.".".$table." (customerId, activityId, inputDate, addedDate, fileLocation, comment, addUserId, deleted) 
				VALUES ('".$id."', '".$activityId."', STR_TO_DATE('".$inputDate."', '%d.%m.%Y'), NOW(), '_customer_".$id."/".$_FILES['uploadFile']['name']."', '".$comment."', '".$_SESSION['UserInfo']['id']."', 0)";
				$Logger->Log('activities', 'upload-activity-file', 'customerId, activityId, inputDate, addedDate, fileLocation, comment, addUserId, deleted', 
						  ".WARPIT_CRM.".".$table.", '', StringChecker::Check($sql));
			if($db->SQLexecute($sql)){
				$r['success'] = true;
			}else{
				$r['error'] = "Unable to save to database";
				$r['success'] = false;
			}
		}else{
			$r['error'] = "Unable to upload";
			$r['success'] = false;
		}
	}else{
		$sql = "INSERT INTO ".WARPIT_CRM.".".$table." (customerId, activityId, inputDate, addedDate, fileLocation, comment, addUserId, deleted) 
				VALUES ('".$id."', '".$activityId."', STR_TO_DATE('".$inputDate."', '%d.%m.%Y'), NOW(), '', '".$comment."', '".$_SESSION['UserInfo']['id']."', 0)";
				$Logger->Log('activities', 'upload-activity-file', 'customerId, activityId, inputDate, addedDate, fileLocation, comment, addUserId, deleted', 
						  ".WARPIT_CRM.".".$table.", '', StringChecker::Check($sql));
		if($db->SQLexecute($sql)){
			$r['success'] = true;
		}else{
			$r['error'] = "Unable to save to database";
			$r['success'] = false;
		}
	}
	echo json_encode($r);
}elseif($_POST['action'] == "get"){
	$id = StringChecker::Check($_POST['customerId']);
	$sql = "SELECT a.*, b.description as activity FROM ".WARPIT_CRM.".".$table." as a, ".WARPIT_CRM."._activitiesSpecification as b WHERE a.customerId = ".$id." AND a.activityId = b.id AND a.deleted = 0 ORDER BY inputDate DESC";
	$res = $db->SQLexecute($sql);
	while($row = $db->fetchAssoc($res)){
		$row['fileLocation'] = str_replace("../", "",$row['fileLocation']);
		$temp = explode("/",strrev($row['fileLocation']),2);
		$row['filename'] = strrev($temp[0]);
		$row['addedDate'] = date_format(new DateTime($row['addedDate']),"d.m.Y H:i:s");
		$data[] = $row;
	}
	$r['success'] = true;
	$r['results'] = sizeof($data);
	$r['rows'] = $data != null ? $data : "";
	
	echo json_encode($r);
}elseif($_POST['action'] == "deleteActivity"){
	$id = StringChecker::Check($_POST['id']);
	
	$sql = "SELECT * FROM ".WARPIT_CRM.".".$table." WHERE id = ".$id;
	
	$res = $db->SQLexecute($sql);
	$row = $db->fetchAssoc($res);
	$fileLocation = str_replace("../", "",$row['fileLocation']);
	$temp = explode("/",strrev($fileLocation),2);
	$dirLocation = strrev($temp[1]);
	if(file_exists(PATH_TO_ROOT.$fileLocation)){
		rename(PATH_TO_ROOT.$fileLocation, PATH_TO_ROOT.$dirLocation."/".$id."_deleted_by_".$_SESSION['UserInfo']['id']."_".strrev($temp[0]));
		
	}
	$sql = "UPDATE ".WARPIT_CRM.".".$table." SET deleted = 1, fileLocation = '".$dirLocation."/".$id."_deleted_by_".$_SESSION['UserInfo']['id']."_".strrev($temp[0])."' WHERE id=".$id;

	$db->SQLexecute($sql);
	$Logger->Log('activities', 'delete-activity', 'all', 
				  ".WARPIT_CRM.".".$table.", '', StringChecker::Check($sql));
	
	/*
	$files = @scandir(PATH_TO_ROOT.$dirLocation);
	if(count($files) <= 2){
		rmdir(PATH_TO_ROOT.$dirLocation);
	}*/
	
	
	echo "{success: true}";
}
elseif ($_POST['action'] == "update") {
    
                                
    $sql = "UPDATE ". WARPIT_CRM. "." . $_POST['table']." SET ".$_POST['field']." = '".StringChecker::Check($_POST['value'])."' WHERE ".$_POST['idField']." = ".StringChecker::Check($_POST['id']);
   // print $sql;
    $db->SQLexecute($sql);
    $Logger->Log('activities', 'single-field-update', StringChecker::Check($_POST['field']), 
                  WARPIT_CRM.".".$_POST['table'], StringChecker::Check($_POST['oldValue']), StringChecker::Check($_POST['value']));
    echo "{ success : true }";
}
?>