<?php
$ctxs = !empty($ctxs) ? $ctxs : $modx->context->get('key');
if (!is_array($ctxs)) $ctxs = explode(',',$ctxs);

if (!$modx->user->hasSessionContext($ctxs)) {
	$data['message']='Error user is messing something log';
	return json_encode($data);
}
$trosk = $modx->getService('trosk','Trosk',$modx->getOption('doodles.core_path',null,$modx->getOption('core_path').'components/trosk/').'model/trosk/',$scriptProperties);
if (!($trosk instanceof Trosk)) return '';

$projectId=$_REQUEST['proj_id'];
if(!empty($projectId)){
	$project=$modx->getObject('projects',$projectId);
	if($modx->user->id!=$project->createdby){
		$data['message']='Error user is messing something proj';
		return json_encode($data);
	}
	$editId=$_REQUEST['edit_id'];
	if(!empty($editId)){
		$item=$modx->getObject('items',$editId);
		if($item->project_id!=$project->id){
			$data['message']='Error user is messing something proj';
			return json_encode($data);
		}
	}
}
	
$action=$_REQUEST['action'];

switch ($action){
	case 'save_stavka':
		$originalId = $_POST['original_id'];
		$projectId = $_POST['project_id'];
		$mjjed = $_POST['mjjed'];
		$amount = $_POST['amount'];
		$stavkaData=array(
			'originalId'=>$originalId,
			'projectId'=>$projectId,
			'mjjed'=>$mjjed,
			'amount'=>$amount,
		);
		if(empty($originalId) or empty($projectId) or empty($amount)or empty($mjjed)){
			$data['message']='Popunite sva polja';
			return json_encode($data);
		} 
		if($mjjed=='odaberi'){
			$data['message']='Popunite sva polja';
			return json_encode($data);
		}
		/*
		for ($i = 0; $i < 200; $i++) {
			$data['message']=$trosk->saveStavka($stavkaData);
		}
		*/
		$data['message']=$trosk->saveStavka($stavkaData);
		$data['lastn']=$trosk->lastNSaved($projectId,3);
		return json_encode($data);
		break;
	case 'update_stavka':
		$originalId = $_POST['original_id'];
		$projectId = $_POST['project_id'];
		$editId = $_POST['edit_id'];
		$mjjed = $_POST['mjjed'];
		$amount = $_POST['amount'];
		$stavkaData=array(
			'originalId'=>$originalId,
			'projectId'=>$projectId,
			'mjjed'=>$mjjed,
			'amount'=>$amount,
		);
		if(empty($originalId) or empty($projectId) or empty($amount)or empty($mjjed)){
			$data['message']='Popunite sva polja';
			return json_encode($data);
		} 
		if($mjjed=='odaberi'){
			$data['message']='Popunite sva polja';
			return json_encode($data);
		}
		$data['message']=$trosk->updateStavka($stavkaData,$editId);
		$data['lastn']=$trosk->lastNSaved($projectId,3);
		return json_encode($data);
		break;
	case 'delete_stavka':
		$stavkaId=$_POST['stav_id'];
		$projectId = $_POST['proj_id'];
		if(empty($stavkaId) or empty($projectId)){
			$data['message']='Error';
			return json_encode($data);
		}
		$data['message']=$trosk->stavkaDelete($stavkaId);
		$data['lastn']=$trosk->lastNSaved($projectId,3);
		return json_encode($data);
		break;
	default:
		break;
}
exit();
	