<?php
if (! defined ( 'sugarEntry' ) || ! sugarEntry)
	die ( '-1' );
if (! $_POST ['job'] || $_POST ['job'] == '')
	die ( '-1' );
switch ($_POST ['job']) {
	case 'getIndeks' :
		getIndeks ( $_POST ['category'] );
		break;
	case 'checkIndeks' :
		checkIndeks ( $_POST ['indeks'], $_POST['category'] );
		break;
}

function getIndeks($category) {
	$db = $GLOBALS ['db'];
	$condition = true;
	
	$query = "SELECT count(id) as c FROM ecmactions WHERE category = '" . $category . "'";
	$r = $db->fetchByAssoc ( $db->query ( $query ) );
	
	if (! $r || ! $r ['c'] || $r ['c'] == '')
		$count = 0;
	else
		$count = intval ( $r ['c'] );
	
	do {
		$count ++;
		
		$tmp = strval ( $count );
		while ( strlen ( $tmp ) < 5 )
			$tmp = '0' . $tmp;
		
		$query2 = "SELECT SUM((SUBSTRING(indeks, 6,5)='" . $tmp . "'))as s FROM ecmactions WHERE category = '" . $category . "'";
		$rs = $db->fetchByAssoc ( $db->query ( $query2 ) );
		if (! $rs || ! $rs ['s'] || $rs ['s'] == '')
			$sum = 0;
		else
			$sum = intval ( $rs ['s'] );
		
		if ($sum == 0) {
			$condition = true;
		} else {
			$condition = false;
		}
	} while ( ! $condition );
	$json = json_encode ( $tmp );
	print $json;
}

function checkIndeks($indeks, $category) {
	$db = $GLOBALS ['db'];
	$query = "SELECT count(id) as c FROM ecmactions WHERE category = '" . $category . "' AND indeks='" . $indeks."'";
	$r = $db->fetchByAssoc ( $db->query ( $query ) );
	
	if (! $r || ! $r ['c'] || $r ['c'] == '')
		$count = 0;
	else
		$count = intval ( $r ['c'] );
	
	if($count > 0 ){
		$json = json_encode (true);
	}else{
		$json = json_encode (false);
	}
	//$json = json_encode ($count);
	print $json;
}
?>