<?php

$oForm = new cForm();
$oFunctions = new cFunctions($this->oDb, $this->oUrl, $this->oSession, $oForm);

include_once($this->path['plugins'] . "classes/hrac.class.php");

$ret = "";
$ret .= $oForm->submitButton("zadajTrening", "zadaj novy trening", False, "pridajForm");

$ret .= tableHead("Vsetky treningy naseho klubu",Array(
		"por. cislo","Datum","trvanie","popis"
));

$query="SELECT trening.*
		FROM `trening`
		WHERE `trening`.`trener_id`IN ( SELECT id
		FROM `users`
		Where klub_id=?)
		ORDER BY `trening`.`datum`  ASC";


//vytiahnut z session id klubu hraca

$q= $this->oDb->queryWithBids($query, array($_SESSION['klubId']));
$i=1;
while ($bR = $this->oDb->get($q)) {
	$ret.= '<tr>'."\n";
	$ret .= '<td>'.$i. '</td>'."\n";
	$ret .= '<td>'.$bR['datum']. '</td>'."\n";
	$ret .= '<td>'.$bR['trvanie']. '</td>'."\n";
	$ret .= '<td>'.$bR['popis']. '</td>'."\n";
	$ret .='		<td class="buttons">'.buttonDelete($bR['id'],  $this->oUrl->fullHref()). buttonEdit($bR['id'],  $this->oUrl->fullHref()). '</td>'."\n";
	$ret.= '</tr>'."\n";
	$i++;
}
$ret .= '</table>'."\n";


$form = "";
$form .= '<form method="post" action="'.$this->oUrl->href().'" enctype="multipart/form-data"'.'>'."\n";
$form .= $ret;
$form .= '</form>'."\n";


if (isset($_POST) && !empty($_POST) && !empty($_POST['pridajForm']) ) {
	//formular pre pridavanie novych treningov
	$pridaj = ' <script type="text/javascript" src="'.$pluginURI.'js/add.js"></script>';
	$pridaj .= '<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />';
	$pridaj .= '<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>';
	$pridaj .= ' <style>
			.ui-autocomplete {
			max-height: 100px;
			overflow-y: auto;
			overflow-x: hidden;
}

			* html .ui-autocomplete {
			height: 100px;
}
			</style>';
	$pridaj .='<form method="post" action="'.$this->oUrl->href().'" enctype="multipart/form-data"'.'>'."\n";
	$pridaj .= '<fieldset>'."\n";
	$pridaj .= '<legend>Základné údaje o tréningu</legend>'."\n";
	$pridaj .= $oForm->inputBox("datum", "datum", 164);
	$pridaj .=$oForm->inputBox("pocet Kurtov", "pocetK", 64);
	$pridaj .=$oForm->inputBox("Trvanie", "trvanie", 64);
	$pridaj .=$oForm->inputBox("Popis", "popis", 64);
	$pridaj .= '</fieldset>'."\n";

	$pridaj .= '<fieldset>'."\n";
	$pridaj .= '<legend>údaje o účasti</legend>'."\n";
	$pridaj .= '<div id="ucast" > </div>';
	$pridaj .= '<input type="button" name="button_add" id="button_add_hrac" class="submit input_expand"
			value="Pridaj ďalšieho hráča" onclick="addHrac(\'ucast\', \'meno\' );" />'."\n";
	$pridaj .= '</fieldset>'."\n";

	$pridaj .= '<fieldset >'."\n";
	$pridaj .= '<legend>Zápas</legend>'."\n";
	$pridaj .= '<div id="zapasy" >';
	$pridaj .= '<div id="TeamA" >';
	$pridaj .= $oForm->selectBox("TeamA", "teamA0[]", array(
			array("name" => 'Hrac musí byť na treningu',
					"value" => '', )), "");
	$pridaj .= '</div>';
	$pridaj .= '<input type="button" name="button_add_m" id="button_add_teamA" class="submit input_expand"
			value="Pridaj ďalšieho hráča" onclick="addHrac(this, \'teamA\',0 );" /><br>'."\n";
	$pridaj .= '<div id="TeamB" >';
	$pridaj .= $oForm->selectBox("TeamB", "teamB0[]", array(
			array("name" => 'Hrac musí byť na treningu',
					"value" => '', )), "");
	$pridaj .= '</div>';
	$pridaj .=$oForm->inputBox("Score", "score0", 16);
	$pridaj.= $oForm->optionBox("Vytaz", "vytaz0", array(

			array("name" => ' team A',
					"value" => 'A', ),

			array("name" => ' team B',
					"value" => 'B', )
	));

	$pridaj .= '<input type="button" name="button_add_m" id="button_add_teamB" class="submit input_expand"
			value="Pridaj ďalšieho hráča" onclick="addHrac(this, \'teamB\',0 );" /><br>'."\n";
	$pridaj .= '</fieldset>'."\n";
	$pridaj .= '</div>';
	$pridaj .= '<input type="button" name="button_add_m" id="button_add_zapas" class="submit input_expand"
			value="Pridaj ďalši zapas" onclick="addZapas();" /><br>'."\n";

	$pridaj .= $oForm->submitButton("newTrening", "odosli novy trening", False);
	$pridaj .= '<input type="hidden" id="pocetZapasov" value="0" name="pocetZapasov"> ';
	$pridaj.= '</form>'."\n";
	echo $pridaj;
}

elseif (isset($_POST) && !empty($_POST) && !empty($_POST['datum']) ) {
	//spracovanie a pridanie treningu
	if ($treningId =pridajTrening($this->oDb, $_POST['datum'].' 00:00:04', $_POST['trvanie'], $_POST['trvanie'], $_POST['popis'], $_POST['pocetK'], $_SESSION['id_user'], 0)) {
		if (pridajUcast($this->oDb, $treningId, $_POST['meno'])) {
			for ($i=0; $i<=$_POST['pocetZapasov']; $i++ ){
				//pridat vsetky zapasy
				$zapasId = pridajZapas($this->oDb, $treningId ,$_POST['score'.$i], $_POST['vytaz'.$i] );
				pridajUcastZapas($this->oDb, $zapasId, $_POST['teamA'.$i], $_POST['teamB'.$i] );
				updateRespekt($this->oDb, $this->oDbS, $_POST['vytaz'.$i],$_POST['teamA'.$i], $_POST['teamB'.$i]);
			}
		}else echo 'trening cast nepridana!';
	}else echo 'trening nepridany!';
}
elseif(isset($_POST['action']) && !empty($_POST['action']) ){
	//ide vykonavat edit/delete
	if ($_POST['action']=="edit"){
		//edituj zaznam
		$ret = "";

		$ret = ' <script type="text/javascript" src="'.$pluginURI.'js/add.js"></script>';
		$ret .= '<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />';
		$ret .= '<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>';
		$ret .= ' <style>
				.ui-autocomplete {
				max-height: 100px;
				overflow-y: auto;
				overflow-x: hidden;
	}

				* html .ui-autocomplete {
				height: 100px;
	}
				</style>';

		$ret .= $oForm->submitButton("zadajTrening", "zadaj novy trening", False, "pridajForm");




		$ret .= tableHead("Vsetky treningy naseho klubu",Array(
				"por. cislo","Datum","trvanie","popis"
		));

		$query="SELECT trening.*
				FROM `trening`
				WHERE `trening`.`trener_id`IN ( SELECT id
				FROM `users`
				Where klub_id=?)
				ORDER BY `trening`.`datum`  ASC";

		$q= $this->oDb->queryWithBids($query, array($_SESSION['klubId']));
		$i=1;
		while ($bR = $this->oDb->get($q)) {
			/*
			 * ak je to editovany trening napis nieco ine
			*/
			if ($bR['id']!=$_POST['id']){
				$ret.= '<tr>'."\n";
				$ret .= '<td>'.$i. '</td>'."\n";
				$ret .= '<td>'.$bR['datum']. '</td>'."\n";
				$ret .= '<td>'.$bR['trvanie']. '</td>'."\n";
				$ret .= '<td>'.$bR['popis']. '</td>'."\n";
				$ret .='		<td class="buttons">'.buttonDelete($bR['id'],  $this->oUrl->fullHref()). buttonEdit($bR['id'],  $this->oUrl->fullHref()). '</td>'."\n";
				$ret.= '</tr>'."\n";
				$i++;
			}else {
				$ret.= '<tr>'."\n";
				$ret .= '<td>'.$i. '</td>'."\n";
				$ret .= '<td>'.$oForm->inputBox("", "datum", 64,$bR['datum']). '</td>'."\n";
				$ret .= '<td>'.$oForm->inputBox("", "trvanie", 16,$bR['trvanie']). '</td>'."\n";
				$ret .= '<td>'.$oForm->inputBox("", "popis", 16,$bR['popis']). '</td>'."\n";
				$ret .='		<td class="buttons">'.buttonEdit($bR['id'],  $this->oUrl->fullHref()). '</td>'."\n";
				$ret.= '</tr>'."\n";
				$i++;
			}
		}
		unset($q);
		$ret .= '</table>'."\n";

		/*
		 * vyhlada udaje o useroch co boli na treningu
		*/
		$sql ='Select * FROM `ucast`
				LEFT JOIN `users` on users.id = ucast.hrac_id
				WHERE trening_id =?';
		$q=$this->oDb->queryWithBids($sql, array($_POST['id']));

		$counter=0;

		while ($bR = $this->oDb->get($q)) {
			/*
			 * aby to nevypisal ak tam nebol zapas
			*/
			if ($counter==0){
				$ret .= '<fieldset>'."\n";
				$ret .= '<legend>údaje o účasti</legend>'."\n";
				$ret.='<div id="ucast"> ';
			}

			$ret .= '<label>Meno/priezvisko</label>'.	'<input id="ucast'.$counter.
			'" class="input_large input_autocomplete" type="text" name="meno[]" value="'.$bR['meno'].' '.$bR['priezvisko'].'('.$bR['id'].')" autocomplete="off"><br>';
			$hraci[$counter]["name"]=$bR['meno'].' '.$bR['priezvisko'].'('.$bR['id'].')';
			$hraci[$counter]["value"]=$bR['id'];
			$counter++;

		}

		/*
		 * aby to nevypisal ak tam nebol zapas
		* a ak tam nebol zapas vypisat ze tam nebol zapas
		*/
		if ($counter!=0) {
			$ret .= '</fieldset>'."\n";
		}
		else {
			$ret .= '<h2> Na tomto treningu nie je evidovany ziadny hrac!</h2>';
			$ret.='<div id="ucast"> ';
		}


		$ret .= '<input type="button" name="button_add" id="button_add_hrac" class="submit input_expand"
				value="Pridaj ďalšieho hráča" onclick="addHrac(\'ucast\', \'meno\' );" />'."\n";

		/*
		 * ziskam pocet zapasov na tomto treningu
		*/
		$sql ='select * FROM `zapas`
				WHERE trening_id =?';

		$q=$this->oDb->queryWithBids($sql, array($_POST['id']));
		$i=0;

		while ($bR = $this->oDb->get($q)) {
			//pre kazdy zapas vypis data

			/*
			 * aby to nevypisal ak tam nebol zapas
			*/
			if ($i==0){
				$ret .= '<fieldset>'."\n";
				$ret .= '<legend>Údaje o zápasoch </legend>'."\n";
			}

			//vyber ucastnikov tohoto zapasu za tym A
			$sql ='SELECT * FROM `zapasy_ucast`
					WHERE zapas_id =? AND team="A"';
			$ret .= '<div class="TeamABox" >';
			$q2=$this->oDb->queryWithBids($sql, array($bR['id']));
			while ($teamAS = $this->oDb->get($q2)) {
				$ret .= $oForm->selectBox("TeamA", 'teamB'.$i.'[]', $hraci, $teamAS['hrac_id']);
			}

			//tlacitko na pridanie hraca do tymu
			$ret .= '<input type="button" name="button_add_m" id="button_add_teamA" class="submit input_expand"
					value="Pridaj ďalšieho hráča" onclick="addHrac(this, \'teamA\',0 );" /><br>'."\n";
			$ret .='</div>';
			//vyber ucastnikov tohoto zapasu za tym B
			$sql ='SELECT * FROM `zapasy_ucast`
					WHERE zapas_id =? AND team="B"';
			$q2=$this->oDb->queryWithBids($sql, array($bR['id']));
			$ret .= '<div class="TeamBBox" >';
			while ($teamBS = $this->oDb->get($q2)) {
				$ret .= $oForm->selectBox("TeamB", 'teamB'.$i.'[]', $hraci, $teamBS['hrac_id']);
			}
			//tlacitko na pridanie hraca do tymu
			$ret .= '<input type="button" name="button_add_m" id="button_add_teamA" class="submit input_expand"
					value="Pridaj ďalšieho hráča" onclick="addHrac(this, \'teamA\',0 );" /><br>'."\n";
			$ret .='</div>';
			$ret .= '<div class="scoreBox" >';
			//vypise udaje o zapase
			$ret .=$oForm->inputBox("Score", "score".$i , 16, $bR['vysledok']).'<br>';
			$ret .= '<div class="vytazBox"> ';
			$ret .= $oForm->optionBox("Vytaz", "vytaz".$i, array(

					array("name" => ' team A',
							"value" => 'A', ),

					array("name" => ' team B',
							"value" => 'B', )
			), $bR['vytaz']);
			$ret .='</div>'.'</div>';
			$i++;
			$ret .= '<div class="clear space"> </div>';
		}
		/*
		 * aby to nevypisal ak tam nebol zapas
		* a ak tam nebol zapas vypisat ze tam nebol zapas
		*/
		if ($i!=0) $ret .= '</fieldset>'."\n";
		else $ret .= '<h2> Na tomto treningu nie je evidovany ziadny zapas!</h2>';

		//pridaj novy zapas
		$ret .= '<input type="button" name="button_add_m" id="button_add_zapas" class="submit input_expand"
				value="Pridaj ďalši zapas" onclick="addZapas();" /><br>'."\n";

		//sumbit editu
		$ret .= $oForm->submitButton("editTrening", "uloz zmeny", False, "editForm");

		$formEdit = "";
		$formEdit .= '<form method="post" action="'.$this->oUrl->href().'" enctype="multipart/form-data"'.'>'."\n";
		$formEdit .= $ret;
		$formEdit .= '</form>'."\n";

		echo $formEdit;

	}
	elseif ($_POST['action']=="delete"){
		//vymaz zaznamy o treningu

		/*
		 * vymaz vsetky ucasti na prisluchajuce tomuto treningu
		*/
		$sql='Delete FROM `ucast`
				WHERE trening_id =?';
		$this->oDb->queryWithBids($sql, array($_POST['id']));

		/*
		 * vymaz vsetky ucasti na vsetkych zapasoch co sa konali natomto treningu
		*/
		$sql= 'Delete FROM zapasy_ucast
				WHERE zapas_id
				IN (
				SELECT id
				FROM `zapas`
				WHERE trening_id =?
				)';
		$this->oDb->queryWithBids($sql, array($_POST['id']));

		/*
		 * vymaz vsetky zapasy na tomto treningu
		*/
		$sql='Delete FROM `zapas`
				WHERE trening_id =?';
		$this->oDb->queryWithBids($sql, array($_POST['id']));

		/*
		 * vymaz samotny trening
		*/
		$sql='Delete FROM `trening`
			 where id =?';
		$this->oDb->queryWithBids($sql, array($_POST['id']));

		/*
		 * refresh form
		*/
		echo $form;
	}

}
else echo $form;


function updateRespekt($DB, $oDbS, $vytaz, $teamA, $teamB){
	if ($vytaz=="A"){
		$deltaA="+0.1"; //zatial konstanta
		$deltaB="-0.1"; //zatial konstanta
	}
	else {
		$deltaB="+0.1"; //zatial konstanta
		$deltaA="-0.1"; //zatial konstanta
	}

	$oHrac = new hracClass($DB, $oDbS);

	foreach ($teamA as &$hrac) {
		$oHrac->upravRespektHracovy($hrac, $deltaA);
	}

	foreach ($teamB as &$hrac) {
		$oHrac->upravRespektHracovy($hrac, $deltaB);
	}
	unset($hrac);
}

function tableHead($caption, $array, $operations = TRUE) {
	$zebraCounter = 0;
	$string = '<table cellspacing="1" cellpadding="0">'."\n";
	if (strlen($caption) > 0)
		$string .= '		<caption>'.$caption.'</caption>'."\n";
	$string .= '	<tr>'."\n";
	for ($i=0;$i<count($array);$i++)
		$string .= '		<th>'.$array[$i].'</th>'."\n";
	if ($operations)
		$string .= '		<th></th>'."\n";
	$string .= '	</tr>'."\n";
	return $string;
}

function buttonEdit($id, $url ,$valueOverride="",$extraHidden="") {
	$valueOverride = empty($valueOverride) ? "&nbsp;": $valueOverride;
	$string = '	<input type="hidden" name="action" value="edit" /><input type="hidden" name="id" value="'.$id.'" /><input type="hidden" name="table" value="'.'" />'."\n";
	$string .= '	<input type="hidden" name="submit" value="Edit" />'.$extraHidden.'<input type="submit" name="sub" value="'.$valueOverride.'" class="submit input_edit" />'."\n";
	return HTMLForm($string,$url);
}

function buttonDelete($id, $url) {
	$string = '	<input type="hidden" name="action" value="delete" /><input type="hidden" name="id" value="'.$id.'" /><input type="hidden" name="table" value="'.'" />'."\n";
	$string .= '	<input type="hidden" name="submit" value="Delete" /><input type="submit" name="sub" value="" class="submit input_delete" onclick="if (confirm(\'Vymazať tento záznam?\')) return true; else return false;" />'."\n";
	return HTMLForm($string,$url);
}

function HTMLForm($content, $action, $class="") {
	$ret = "";
	$ret .= '<form method="post" action="'.$action.'" enctype="multipart/form-data"'.($class ? ' class="'.$class.'"' : "").'>'."\n";
	$ret .= $content;
	$ret .= '</form>'."\n";
	return $ret;
}

function pridajTrening($db,$datum, $trvanie, $popis, $popis, $pocKurtov, $trenerId, $vymazany){
	$sql="INSERT INTO `trening` (`datum`, `trvanie`, `popis`, `poc_kurtov`, `trener_id`, `uid`, `vymazany`, `last_mod`)
			VALUES (?, ?, ?, ?, ?, ?, ?, ?);";
	$uid = uniqid();
	$db->queryWithBids($sql, array($datum, $trvanie, $popis, $pocKurtov, $trenerId,$uid, $vymazany, date('Y-m-d H:i:s')));
	return $db->insertID();
}

function pridajUcast($db,$treningId, $ucast){
	foreach ($ucast as  &$clovekId) {
		$clovekId=substr ($clovekId, strpos($clovekId,"(")+1,strpos($clovekId,")")-strpos($clovekId,"(")-1);
		$sql= 'INSERT INTO `ucast` (
				`trening_id` ,
				`hrac_id`
				)
				VALUES (?, ?);';
		if (!$db->queryWithBids($sql, array($treningId,$clovekId))) return -1;
	}
	unset($clovek);
	return 1;
}

function pridajZapas($db, $treningId , $vysledok, $vytaz){
	$sql="INSERT INTO `zapas` (
			`id` ,
			`trening_id` ,
			`vysledok` ,
			`vytaz`
			)
			VALUES ( NULL , ?, ? , ?);";
	$uid = uniqid();
	$db->queryWithBids($sql, array($treningId , $vysledok, $vytaz));
	return $db->insertID();
}


function pridajUcastZapas($db, $zapasId, $teamA, $teamB ){

	/*
	 * teamA
	*/
	foreach ($teamA as  &$clovekId) {
		$sql= 'INSERT INTO `zapasy_ucast` (
				`zapas_id` ,
				`hrac_id` ,
				`team`
				)
				VALUES (
				?, ?, "A"
				);';
		if (!$db->queryWithBids($sql, array($zapasId,$clovekId))) return -1;
	}
	unset($clovek);

	/*
	 * teamB
	*/
	foreach ($teamB as  &$clovekId) {
		$sql= 'INSERT INTO `zapasy_ucast` (
				`zapas_id` ,
				`hrac_id` ,
				`team`
				)
				VALUES (
				?, ?, "B"
				);';
		if (!$db->queryWithBids($sql, array($zapasId,$clovekId))) return -1;
	}
	unset($clovek);
	return 1;
}

?>
<script>
$(function() {
	kontrolaCislo('#pocetK');
	kontrolaCislo('#trvanie');
});
</script>
