<?php
class Trosk {
	public $modx;
	public $config = array();
	function __construct(modX &$modx,array $config = array()) {
		$this->modx =& $modx;

		$basePath = $this->modx->getOption('trosk.core_path',$config,$this->modx->getOption('core_path').'components/trosk/');
		$assetsUrl = $this->modx->getOption('trosk.assets_url',$config,$this->modx->getOption('assets_url').'components/trosk/');
		$this->config = array_merge(array(
            'basePath' => $basePath,
            'corePath' => $basePath,
            'modelPath' => $basePath.'model/',
            'processorsPath' => $basePath.'processors/',
            'chunksPath' => $basePath.'elements/chunks/',
            'jsUrl' => $assetsUrl.'js/',
            'cssUrl' => $assetsUrl.'css/',
            'assetsUrl' => $assetsUrl,
            'connectorUrl' => $assetsUrl.'connector.php',
		),$config);
		$this->modx->addPackage('trosk',$this->config['modelPath']);
	}

	public function initialize($ctx = 'web') {
		switch ($ctx) {
			case 'mgr':
				$this->modx->lexicon->load('trosk:default');
				if (!$this->modx->loadClass('troskControllerRequest',$this->config['modelPath'].'request/',true,true)) {
					return 'Could not load controller request handler.';
				}
				$this->request = new troskControllerRequest($this);
				return $this->request->handleRequest();
				break;
		}
		return true;
	}

	public function convert($stavka){
		$c=&$stavka->content;
		preg_match_all('[\-\-[0-9a-zA-Z\s]{1,}#]',$c,$matches);
		foreach ($matches[0] as $key=>$name) {
			$name=substr($name,2,-1);
			$param=$this->modx->getObject('params',array('name' => $name));
			$opt=$param->values;
			$vr=explode(',',$opt);
			$sr='<select name="p'.$param->id.'[]">';
			$sr.='<option value="odaberi">odaberi</option>';
			foreach($vr as $val){
				$first=substr($val,0,1);
				if($first=='-') continue;
				if($first!='-')$sr.='<option value="'.$val.'">'.$val.'</option>';
			}
			$sr.='</select>';
			$newValues[]=$sr;
			$matches[0][$key]='/'.$matches[0][$key].'/';
		}
		$c=preg_replace($matches[0],$newValues,$c);
		return $c;
	}

	public function convertEdit($stavka,$editId){
		$c=&$stavka->content;
		preg_match_all('[\-\-[0-9a-zA-Z\s]{1,}#]',$c,$matches);
		foreach ($matches[0] as $key=>$name) {
			$name=substr($name,2,-1);
			$param=$this->modx->getObject('params',array('name' => $name));
			$replaced[]=$param->id;
			$orderVals=array_count_values($replaced);
			$order=$orderVals[$param->id];
			$paramssaved=$this->modx->getObject('paramssaved',array('param_id' => $param->id,'item_id'=>$editId,'order'=>$order));
			$opt=$param->values;
			$vr=explode(',',$opt);
			$sr='<select name="p'.$param->id.'[]">';
			$sr.='<option value="odaberi">odaberi</option>';
			foreach($vr as $val){
				$first=substr($val,0,1);
				if($first=='-') continue;
				$sel='';
				if($val==$paramssaved->value) $sel='selected="selected"';
				if($first!='-')$sr.='<option '.$sel.' value="'.$val.'">'.$val.'</option>';
			}
			$sr.='</select>';
			$newValue=$sr;
			$matches[0][$key]='/'.$matches[0][$key].'/';
			$c=preg_replace($matches[0][$key],$newValue,$c,1);
		}
		//$c=preg_replace($matches[0],$newValues,$c);
		return $c;
	}
	
	
	public function convertMjJed($stavka){
		$mj=&$stavka->link_attributes;
		if(empty($mj)) return '';
		$vr=explode(',',$mj);
		$sr='<select name="mjjed">';
		$sr.='<option value="odaberi">mjerna jedinica</option>';
		foreach($vr as $val){
			$first=substr($val,0,1);
			if($first=='-') continue;
			if($first!='-')$sr.='<option value="'.$val.'">'.$val.'</option>';
		}
		$sr.='</select>';
		return $sr;
	}

	public function convertMjJedEdit($stavka,$editId){
		$item=$this->modx->getObject('items',$editId);
		$mj=&$stavka->link_attributes;
		if(empty($mj)) return '';
		$vr=explode(',',$mj);
		$sr='<select name="mjjed">';
		$sr.='<option value="odaberi">mjerna jedinica</option>';
		foreach($vr as $val){
			$first=substr($val,0,1);
			if($first=='-') continue;
			$sel='';
			if($val==$item->mjjed) $sel='selected="selected"';
			if($first!='-')$sr.='<option '.$sel.' value="'.$val.'">'.$val.'</option>';
		}
		$sr.='</select>';
		return $sr;
	}
	
	
	public function saveStavka($stavkaData){
		$modx=$this->modx;
		$project=$modx->getObject('projects',$stavkaData['projectId']);
		if($this->modx->user->id!=$project->createdby) return 'Error user';
		$stavka=$modx->getObject('modResource',$stavkaData['originalId']);
		$c=$stavka->content;
		preg_match_all('[\-\-[0-9a-zA-Z\s]{1,}#]',$c,$matches);
		foreach ($matches[0] as $key=>$name) {
			$name=substr($name,2,-1);
			$param=$this->modx->getObject('params',array('name' => $name));
			$replaced[]=$param->id;
			$value=$_POST['p'.$param->id.''];
			$order=array_count_values($replaced);
			$newValue=$value[$order[$param->id]-1];
			$matches[0][$key]='/'.$matches[0][$key].'/';
			$c=preg_replace($matches[0][$key],$newValue,$c,1);
		}
		$c=strip_tags($c);
		$stavkaSave = $this->modx->newObject('items');
	    $stavkaData['amount']=str_replace (',','.',$stavkaData['amount']);
	    $stavkaData['amount']=round($stavkaData['amount'],2);
	    $stavkaData['amount']=number_format($stavkaData['amount'],2,',','');
	    $stavkaSave->fromArray(array(
			'original_id' => $stavkaData['originalId'],
		    'project_id' => $stavkaData['projectId'],
		    'saved_item'=>$c,
	    	'mjjed'=>$stavkaData['mjjed'],
	    	'amount'=>$stavkaData['amount'],
	    ));
		$order=array_count_values($replaced);
	    foreach ($order as $paramId=>$counter){
		   	$value=$_POST['p'.$paramId.''];
	    	while ($counter>0) {
		   		$param = $modx->newObject('paramssaved');
		   		$valSave=$value[$counter-1];
		   		if($valSave=='odaberi') return 'Error';
			   	$param->fromArray(array(
			   		'param_id'=>$paramId,
			   		'value'=>$valSave,
			   		'order'=>$counter,
			   	));
				$params[]=$param;
				$counter--;
		   	}
		}
		$stavkaSave->addMany($params);
	    if(!$stavkaSave->save()) return 'Error saving';
	    $tpl='fem.trosk.savedStavka';
	    return 'Spremljeno';
	}

	public function updateStavka($stavkaData,$editId){
		$modx=$this->modx;
		$project=$modx->getObject('projects',$stavkaData['projectId']);
		if($this->modx->user->id!=$project->createdby) return 'Error user';
		$stavka=$modx->getObject('modResource',$stavkaData['originalId']);
		$c=$stavka->content;
		preg_match_all('[\-\-[0-9a-zA-Z\s]{1,}#]',$c,$matches);
		foreach ($matches[0] as $key=>$name) {
			$name=substr($name,2,-1);
			$param=$this->modx->getObject('params',array('name' => $name));
			$replaced[]=$param->id;
			$value=$_POST['p'.$param->id.''];
			$order=array_count_values($replaced);
			$newValue=$value[$order[$param->id]-1];
			$matches[0][$key]='/'.$matches[0][$key].'/';
			$c=preg_replace($matches[0][$key],$newValue,$c,1);
		}
		$c=strip_tags($c);
		$stavkaSave = $this->modx->getObject('items',$editId);
		$stavkaData['amount']=str_replace (',','.',$stavkaData['amount']);
	    $stavkaData['amount']=round($stavkaData['amount'],2);
	    $stavkaData['amount']=number_format($stavkaData['amount'],2,',','');
		$stavkaSave->fromArray(array(
			'original_id' => $stavkaData['originalId'],
		    'project_id' => $stavkaData['projectId'],
		    'saved_item'=>$c,
	    	'mjjed'=>$stavkaData['mjjed'],
	    	'amount'=>$stavkaData['amount'],
	    ));
		$order=array_count_values($replaced);
	    foreach ($order as $paramId=>$counter){
		   	$value=$_POST['p'.$paramId.''];
	    	while ($counter>0) {
		   		$param = $modx->getObject('paramssaved',array('param_id'=>$paramId,'item_id'=>$editId,'order'=>$counter));
		   		$valSave=$value[$counter-1];
		   		if($valSave=='odaberi') return 'Error';
			   	$param->fromArray(array(
			   		'value'=>$valSave,
			   	));
				$params[]=$param;
				$counter--;
		   	}
		}
		$stavkaSave->addMany($params);
	    if(!$stavkaSave->save()) return 'Error saving';
	    $tpl='fem.trosk.savedStavka';
	    return 'Izmijenjeno';
	}
	
	
	public function lastNSaved($projectId,$n){
		$tpl='fem.trosk.savedStavka';
		$criteria=$this->modx->newQuery('items');
		$criteria->where(array(
			'project_id' => $projectId,
		));
		$criteria->sortBy('id','DESC');
		$criteria->limit($n);
	    $stavke=$this->modx->getCollection('items',$criteria);
		foreach ($stavke as $stavka) {
			$editUrl=$this->modx->makeUrl(26,'',array(
				'proj_id' => $projectId,
				'edit_id' => $stavka->id,
				'category_id' => $stavka->original_id,
			));
			$stavka->fromArray(array('editUrl'=>$editUrl));
			$stavkaArray = $stavka->toArray();
			$output .= $this->modx->getChunk($tpl,$stavkaArray);
		};
	   	return $output;
	}

	public function stavkaDelete($stavkaId){
		$stavka=$this->modx->getObject('items',$stavkaId);
		if(empty($stavka)) return '';
		if($stavka->remove()) return 'Obrisano';
		return 'Nije';
	}
	
	public function getTroskName($projId){
		$project=$this->modx->getObject('projects',$projId);
		return $project->name;
	}
	
	public function renderTrosk($projectId,$stream){
		$children=$this->modx->getChildIds(2,1);
		$num='';
		$toc=array();
		$output=$this->build($children, $num, $projectId,$stream,$toc);
		if($stream=='pdf') $output='<table border="0" cellspacing="5">'.$output.'</table>';
		$render['output']=$output;
		$render['toc']=$toc;
		//var_dump($toc);
		return $render;
	}
	
	private function build($children, $num, $projectId,$stream,&$toc){
			if($stream=='html') $tpl='fem.trosk.renderSavedStavka';
			if($stream=='pdf') $tpl='fem.trosk.renderPdfStavka';
			$modx=& $this->modx;
			$j=0;
			$i=0;
			foreach ($children as $id) {
				$decadents=$modx->getChildIds($id,15);
				if(empty($decadents)){
					continue;
				} 
				$criteria=$modx->newQuery('items');
				$criteria->where(array(
					'original_id:IN' => $decadents,
					'project_id'=>$projectId,
				));
				$ima=$modx->getCount('items',$criteria);
				if($ima>0){
					$childs=$modx->getchildIds($id,1);
					$cat=$modx->getObject('modResource',$id);
					$criteria=$modx->newQuery('items');
					$criteria->where(array(
						'original_id:IN' => $childs,
						'project_id'=>$projectId,
					));
					$stavke=$modx->getCollection('items',$criteria);
					$stavkeOutput='';
					if($j>0){
						$num=substr($num,0,-2);
					}
					$j++;
					$i++;
					$num.=$i.'.';
					if(!empty($stavke)) {
						$s=0;
						foreach ($stavke as $stavka) {
							$s++;
							$numStavka=$num.$s.'.';
							$stavkaUrl=$modx->makeUrl(25,'',array(
								'proj_id' => $projectId,
								'stav_id' => $stavka->id,
								'del' => 1,
							));
							$editUrl=$modx->makeUrl(26,'',array(
								'proj_id' => $projectId,
								'edit_id' => $stavka->id,
								'category_id' => $stavka->original_id,
							));
							$stavka->fromArray(array(
								'num'=>$numStavka,
								'stavkaUrl'=>$stavkaUrl,
								'editUrl'=>$editUrl,
							));
							//$stavka->amount=number_format($stavka->amount,2,'.',',');
							//$stavka->amount=number_format(33.24,3);
							$stavkaArray=$stavka->toArray();
							$stavkeOutput.=$modx->getChunk($tpl,$stavkaArray);
						}
					}
					if($stream=='html'){
						if(!empty($stavkeOutput)){
							$output.='<div style="float:left;width:100%"><div style="float:left;width:15%">'.$num.'</div>'.'<div style="float:left;width:85%">'.$cat->pagetitle.'</div></div>'.$stavkeOutput.$this->build($childs, $num, $projectId,$stream,$toc);
							$toc[]=''.$num.' '.$cat->pagetitle;
						}
						if(empty($stavkeOutput)){
							$toc[]=''.$num.' '.$cat->pagetitle;
							$output.='<div style="float:left;width:15%">'.$num.'</div>'.'<div style="float:left;width:85%">'.$cat->pagetitle.'</div>'.$this->build($childs, $num, $projectId,$stream,$toc);
						}
					};
					if($stream=='pdf'){
						if(!empty($stavkeOutput)){
							$toc[]=''.$num.' '.$cat->pagetitle;
							$output.='<tr><td width="60">'.$num.'</td>'.'<td width="500">'.$cat->pagetitle.$cat->content.'<br /></td></tr>'.$stavkeOutput.$this->build($childs, $num, $projectId,$stream,$toc);
						}
						if(empty($stavkeOutput)){
							$toc[]=''.$num.' '.$cat->pagetitle;
							$output.='<tr><td width="60">'.$num.'</td>'.'<td width="500">'.$cat->pagetitle.$cat->content.'<br /></td></tr>'.$this->build($childs, $num, $projectId,$stream,$toc);
						}
					};
				} else {continue;}
			}
			return $output;
	}

	public function xlsRenderTrosk($projectId,$stream){
		$children=$this->modx->getChildIds(2,1);
		$num='';
		$brojevi=array();
		$stavke=array();
		$mjjeds=array();
		$kols=array();
		$output=$this->xlsBuild($children,$num,$projectId,$brojevi,$stavke,$mjjeds,$kols);
		//var_dump($brojevi);
		return $brojevi;
	}
	
	private function xlsBuild($children,$num,$projectId,&$brojevi,&$stavke,&$mjjeds,&$kols){
			$modx=& $this->modx;
			$j=0;
			$i=0;
			foreach ($children as $id) {
				$decadents=$modx->getChildIds($id,15);
				if(empty($decadents)){
					continue;
				} 
				$criteria=$modx->newQuery('items');
				$criteria->where(array(
					'original_id:IN' => $decadents,
					'project_id'=>$projectId,
				));
				$ima=$modx->getCount('items',$criteria);
				if($ima>0){
					$childs=$modx->getchildIds($id,1);
					$cat=$modx->getObject('modResource',$id);
					$criteria=$modx->newQuery('items');
					$criteria->where(array(
						'original_id:IN' => $childs,
						'project_id'=>$projectId,
					));
					$stavke=$modx->getCollection('items',$criteria);
					$stavkeOutput='';
					if($j>0){
						$num=substr($num,0,-2);
					}
					$j++;
					$i++;
					$num.=$i.'.';
					if(empty($cat->content)){
						$brojevi[]=$num.'|'.$cat->pagetitle.'||';
					} else {
						$napomena=strip_tags($cat->content);
						$brojevi[]=$num.'|'.$cat->pagetitle."\n\n".$napomena.'||';  
					}
					if(!empty($stavke)) {
						$s=0;
						foreach ($stavke as $stavka) {
							$s++;
							$numStavka=$num.$s.'.';
							$brojevi[]=$numStavka.'|'.$stavka->saved_item.'|'.$stavka->mjjed.'|'.$stavka->amount.'';
						}
					}
				$this->xlsBuild($childs,$num,$projectId,$brojevi,$stavke,$mjjeds,$kols);
				} else {continue;}
			}
			return 1;
	}
	
	public function bannerCount($banner,$tpl){
		$counter = $this->modx->getObject('modTemplateVar', array('name'=>'brPrikazi'));
		$counterValue=$banner->getTVValue('brPrikazi');
		if($counterValue!='n'){
		  $counterNewValue = $counterValue - 1;
		  $counter->setValue($banner->get('id'), $counterNewValue);
		  $counter->save();
		};
		$clickerValue=$banner->getTVValue('brClick');
		if(($counterValue<2)and($counterValue!='n')and($clickerValue<1)and($clickerValue!='n')){
			$banner->set('published',0);
			$banner->save();
		}
		$link=$banner->getTVValue('link');
		$bannerUrl=$link;
		if($clickerValue!='n'){
			$bannerUrl=$this->modx->makeUrl(37,'',array(
				'banner_id' => $banner->id,
				'link' => $link,
			));
		}
		$banner->fromArray(array(
			'img'=>$banner->getTVValue('slika'),
			'bannerUrl'=>$bannerUrl,
		));
		$bannerArray=$banner->toArray();
		return $this->modx->getChunk($tpl,$bannerArray);
	} 

}
?>