<?php
function elements_modsnippet_31($scriptProperties= array()) {
global $modx;
if (is_array($scriptProperties)) {
extract($scriptProperties, EXTR_SKIP);
}
$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 '';
    
	$tpl='fem.trosk.listCategories';
	$tplStavka='fem.trosk.stavkaForm';
	$tplStavkaEdit='fem.trosk.stavkaFormEdit';
	$projectId=$_REQUEST['proj_id'];
	$categoryId=$_REQUEST['category_id'];
	$editId=$_REQUEST['edit_id'];
	if(empty($categoryId)) $categoryId=2;
	$childIds=$modx->getChildIds($categoryId,1);
	if(empty($childIds)){
		if(empty($editId)){
			$stavka=$modx->getObject('modResource',$categoryId);
			if(empty($stavka->content)) return 'Empty';
			$trosk->convert($stavka);
			$mjjed=$trosk->convertMjJed($stavka);
			$stavka->fromArray(array(
				'original_id'=>$categoryId,
				'project_id'=>$projectId,
				'mjjed'=>$mjjed,
			));
	      	$stavkaArray = $stavka->toArray();
			return $modx->getChunk($tplStavka,$stavkaArray);
		} else {
			$stavka=$modx->getObject('modResource',$categoryId);
			if(empty($stavka->content)) return 'Empty';
			$trosk->convertEdit($stavka,$editId);
			$mjjed=$trosk->convertMjJedEdit($stavka,$editId);
			$item=$modx->getObject('items',$editId);
			$stavka->fromArray(array(
				'original_id'=>$categoryId,
				'project_id'=>$projectId,
				'mjjed'=>$mjjed,
				'edit_id'=>$editId,
				'amount'=>$item->amount,
			));
	      	$stavkaArray = $stavka->toArray();
			return $modx->getChunk($tplStavkaEdit,$stavkaArray);
		}
	}
	$criteria=$modx->newQuery('modResource');
    $criteria->where(array(
         'id:IN' => $childIds,
    ));
    $criteria->sortby('menuindex','ASC');
    $categories=$modx->getCollection('modResource',$criteria);
    $i=0;
    $output='';
    foreach ($categories as $category) {
      $catUrl=$modx->makeUrl(26,'',array('category_id' => $category->id,'proj_id'=>$projectId));  
      $category->fromArray(array(
        'catUrl'=>$catUrl,
      ));
      $categoryArray = $category->toArray();
      $output .= $modx->getChunk($tpl,$categoryArray);
    };
    return $output;
}
