<?php
/**
 * Edit all data for goals
 *
 * @package PHP Competition System
 * @author  Eric GALLENE <okrome@free.fr>
 * @link	http://www.phpcompet.com
 * @version $Id: edit_goals.php,v 1.00 2006/10/26 21:47:13
 */

require_once './core/functions.php';

if ($save) {

	$SELECT = 'SELECT '.TBL_MATCHS.'.id_candidate_dom, '.TBL_MATCHS.'.id_candidate_ext, '.TBL_MATCHS.'.buts_dom, '.TBL_MATCHS.'.buts_ext
				FROM '.TBL_MATCHS.' 
				WHERE '.TBL_MATCHS.'.id = '.$match.';'; 
	$res   = runSQL($SELECT);

	$VALUES = "";
	if ($res[0]['buts_dom']) {
		for ($x=1; $x<$res[0]['buts_dom']+1; $x++) {
			if (${'dom'.$x}) {
				if ($VALUES) {$VALUES .= ",";}
				$VALUES .= "(".$match.",".${'dom'.$x}.",".$res[0]['id_candidate_dom'].",'".${'mindom'.$x}."','".${'cscdom'.$x}."','".${'pendom'.$x}."')";
			}
		}
	}
	if ($res[0]['buts_ext']) {
		for ($y=1; $y<$res[0]['buts_ext']+1; $y++) {
			if (${'ext'.$y}) {
				if ($VALUES) {$VALUES .= ",";}
				$VALUES .= "(".$match.",".${'ext'.$y}.",".$res[0]['id_candidate_ext'].",'".${'minext'.$y}."','".${'cscext'.$y}."','".${'penext'.$y}."')";
			}
		}
	}

	
	$mymatchdate = getusdate($datematch) . ' ' . $hourmatch . ':00';

	$INSERT = 'UPDATE '.TBL_MATCHS.' SET date_day=\''.$mymatchdate.'\', id_referee=\''.$ref.'\', id_weather=\''.$weather.'\', id_stadium=\''.$stadium.'\', spectators=\''.$spect.'\', temperature=\''.$temp.'\', plot=\''.addslashes($plot).'\' WHERE id = '.$match;
	$id = runSQL($INSERT); 
	
	if ($VALUES) {
	$DELETE = 'DELETE FROM '.TBL_GOALS.' WHERE id_match='.$match.' AND id_club='.$res[0]['id_candidate_dom'];
	$result = runSQL($DELETE);
	
	$DELETE = 'DELETE FROM '.TBL_GOALS.' WHERE id_match='.$match.' AND id_club='.$res[0]['id_candidate_ext'];
	$result = runSQL($DELETE);	
	
	$INSERT = 'INSERT INTO '.TBL_GOALS.' (id_match, id_person, id_club, goal_min, goal_csc, goal_pen) VALUES '.$VALUES;	
	$id = runSQL($INSERT); 
	}
	

// Save cards shown
	$VALUES = "";
	if ($advlines) {
		for ($x=1; $x<$advlines+1; $x++) {
			if (${'advertdom'.$x}) {
				if ($VALUES) {$VALUES .= ",";}
				if(!${'advertdomR'.$x} && !${'advertdomY'.$x}) {${'advertdomY'.$x} = 1;}
				$VALUES .= "(".$match.",".${'advertdom'.$x}.",".$res[0]['id_candidate_dom'].",'".${'advertdommin'.$x}."','".${'advertdomY'.$x}."','".${'advertdomR'.$x}."')";
			}
			if (${'advertext'.$x}) {
				if ($VALUES) {$VALUES .= ",";}
				if(!${'advertextR'.$x} && !${'advertextY'.$x}) {${'advertextY'.$x} = 1;}
				$VALUES .= "(".$match.",".${'advertext'.$x}.",".$res[0]['id_candidate_ext'].",'".${'advertextmin'.$x}."','".${'advertextY'.$x}."','".${'advertextR'.$x}."')";
			}
		}
		if ($VALUES) {
		$DELETE = 'DELETE FROM '.TBL_CARDS.' WHERE id_match='.$match.' AND id_club='.$res[0]['id_candidate_dom'];
		$result = runSQL($DELETE);
		
		$DELETE = 'DELETE FROM '.TBL_CARDS.' WHERE id_match='.$match.' AND id_club='.$res[0]['id_candidate_ext'];
		$result = runSQL($DELETE);
	
		$INSERTCARDS = 'INSERT INTO '.TBL_CARDS.' (id_match, id_person, id_club, card_min, card_yellow, card_red) VALUES '.$VALUES;	
		$id = runSQL($INSERTCARDS);
		}	

	}

// Save substitution shown
	$VALUES = "";
	if ($subslines) {
		for ($x=1; $x<$subslines+1; $x++) {
			if (${'subsdommin'.$x}) {
				if ($VALUES) {$VALUES .= ",";}
				$VALUES .= "(".$match.",".$res[0]['id_candidate_dom'].",".${'subsindom'.$x}.",'".${'subsoutdom'.$x}."','".${'subsdommin'.$x}."')";
			}
			if (${'subsextmin'.$x}) {
				if ($VALUES) {$VALUES .= ",";}
				$VALUES .= "(".$match.",".$res[0]['id_candidate_ext'].",".${'subsinext'.$x}.",'".${'subsoutext'.$x}."','".${'subsextmin'.$x}."')";
			}
		}
		if ($VALUES) {
		$DELETE = 'DELETE FROM '.TBL_SUBS.' WHERE id_match='.$match.' AND id_club='.$res[0]['id_candidate_dom'];
		$result = runSQL($DELETE);
		
		$DELETE = 'DELETE FROM '.TBL_SUBS.' WHERE id_match='.$match.' AND id_club='.$res[0]['id_candidate_ext'];
		$result = runSQL($DELETE);
	
		$INSERTSUBS = 'INSERT INTO '.TBL_SUBS.' (id_match, id_club, id_person_in, id_person_out, subs_min) VALUES '.$VALUES;	
		$id = runSQL($INSERTSUBS);
		}	

	}

	//Additionnal caracs
	$VALUES = "";
	$SELECT = 'SELECT id, lib_key, genre FROM '.TBL_CARACS.' WHERE type = 5';
	$allcaracs = runSQL($SELECT);
	if ($allcaracs) {
		for ($x=0;$x<count($allcaracs);$x++) {
			if ($IN) {$IN .= ', ';}
			else {$IN = '(';}
			$IN .= $allcaracs[$x]['id'];
			if ($VALUES) {$VALUES .= ",";}
			if (${$allcaracs[$x]['lib_key']}) {
				if ($allcaracs[$x]['genre'] == 2) {$caracvalue = getusdate(${$allcaracs[$x]['lib_key']});}
				elseif ($allcaracs[$x]['genre'] == 7) {$caracvalue = upload_carac($allcaracs[$x]['lib_key'],'5',$id);}
				else {$caracvalue = ${$allcaracs[$x]['lib_key']};}
			}
			$VALUES .= "(".$allcaracs[$x]['id'].",".$match.",'".$caracvalue."')";
		}
		$IN .= ')';
		$DELETE = 'DELETE FROM '.TBL_VALUES.' WHERE id_item='.$match.' AND id_carac IN '.$IN;
		runSQL($DELETE);
		$INSERT = 'REPLACE INTO '.TBL_VALUES.' (id_carac, id_item, value) VALUES '.$VALUES;
		runSQL($INSERT);
	}

redirect('edit_goals.php?competition='.$competition.'&season='.$season.'&day='.$day);
}

// get data (id may be empty on a empty database)
if (!empty($competition) && !empty($season))
{
	
	$SELECT = 'SELECT '.TBL_DAYS.'.id FROM '.TBL_DAYS.' WHERE id_compet = '.$competition.' AND id_season='.$season;				 
	$days = runSQL($SELECT);
	$numdays=count($days);

if (!$match) {
	if (!$day) {
	$SELECT = 'SELECT '.TBL_DAYS.'.id, '.TBL_DAYS.'.day FROM '.TBL_DAYS.' WHERE '.TBL_DAYS.'.date_day < NOW() AND '.TBL_DAYS.'.id_season = '.$season.' AND '.TBL_DAYS.'.id_compet = '.$competition.' ORDER BY '.TBL_DAYS.'.date_day DESC LIMIT 1';
	$lastday = runSQL($SELECT);
	$day = $lastday[0]['day'];
	}

	$SELECT = 'SELECT '.TBL_MATCHS.'.id, '.TBL_MATCHS.'.id_candidate_dom, C1.shortname AS domclub, C1.imgurl AS domimg, '.TBL_MATCHS.'.id_candidate_ext, C2.shortname AS extclub, C2.imgurl AS extimg, '.TBL_MATCHS.'.id_day, '.TBL_MATCHS.'.date_day, '.TBL_MATCHS.'.buts_dom, '.TBL_MATCHS.'.buts_ext, '.TBL_MATCHS.'.plot
				FROM '.TBL_MATCHS.' 
				JOIN '.TBL_DAYS.' ON '.TBL_MATCHS.'.id_day = '.TBL_DAYS.'.id 
				JOIN '.TBL_CLUBS.' AS C1 ON '.TBL_MATCHS.'.id_candidate_dom = C1.id 
				JOIN '.TBL_CLUBS.' AS C2 ON '.TBL_MATCHS.'.id_candidate_ext = C2.id 
				WHERE '.TBL_DAYS.'.id_compet = '.$competition.' AND '.TBL_DAYS.'.id_season = '.$season.' AND '.TBL_DAYS.'.day = '.$day.';'; 
	$res   = runSQL($SELECT);
	// get the item
    $matchs = $res;

	$SELECT = 'SELECT '.TBL_PERSONS.'.id AS id_person,'.TBL_PERSONS.'.position, '.TBL_PERSONS.'.firstname AS firstname, '.TBL_PERSONS.'.lastname AS lastname, '.TBL_LINEUP.'.id_club, '.TBL_LINEUP.'.type, '.TBL_LINEUP.'.captain 
			   FROM '.TBL_LINEUP.'
			   JOIN '.TBL_PERSONS.' ON '.TBL_LINEUP.'.id_person = '.TBL_PERSONS.'.id
			   WHERE '.TBL_LINEUP.'.id_match = '.$res[0]['id'].' ORDER BY '.TBL_PERSONS.'.lastname';				 
	$rooster = runSQL($SELECT);		
	
	$nummatchs = count($res);

}
else {
	$SELECT = 'SELECT '.TBL_MATCHS.'.id, '.TBL_MATCHS.'.id_candidate_dom, C1.shortname AS domclub, C1.imgurl AS domimg, '.TBL_MATCHS.'.id_candidate_ext, C2.shortname AS extclub, C2.imgurl AS extimg, '.TBL_MATCHS.'.id_day, '.TBL_MATCHS.'.date_day, '.TBL_MATCHS.'.buts_dom, '.TBL_MATCHS.'.buts_ext, '.TBL_MATCHS.'.id_referee, '.TBL_MATCHS.'.id_stadium, '.TBL_MATCHS.'.spectators, '.TBL_MATCHS.'.id_weather, '.TBL_MATCHS.'.temperature, '.TBL_MATCHS.'.plot
				FROM '.TBL_MATCHS.' 
				JOIN '.TBL_DAYS.' ON '.TBL_MATCHS.'.id_day = '.TBL_DAYS.'.id 
				JOIN '.TBL_CLUBS.' AS C1 ON '.TBL_MATCHS.'.id_candidate_dom = C1.id 
				JOIN '.TBL_CLUBS.' AS C2 ON '.TBL_MATCHS.'.id_candidate_ext = C2.id 
				WHERE '.TBL_DAYS.'.id_compet = '.$competition.' AND '.TBL_DAYS.'.id_season = '.$season.' AND '.TBL_DAYS.'.day = '.$day.' AND '.TBL_MATCHS.'.id = '.$match.';'; 
	$res   = runSQL($SELECT);

	$SELECT = 'SELECT '.TBL_PERSONS.'.id AS id_person,'.TBL_PERSONS.'.position, '.TBL_PERSONS.'.firstname AS firstname, '.TBL_PERSONS.'.lastname AS lastname, '.TBL_LINEUP.'.id_club, '.TBL_LINEUP.'.type, '.TBL_LINEUP.'.captain 
			   FROM '.TBL_LINEUP.'
			   JOIN '.TBL_PERSONS.' ON '.TBL_LINEUP.'.id_person = '.TBL_PERSONS.'.id
			   WHERE '.TBL_LINEUP.'.id_match = '.$match.' ORDER BY '.TBL_PERSONS.'.lastname';				 
	$rooster = runSQL($SELECT);

	// get the item	
	$matchs = $res;
	$matchs[0]['carac_ads'] = get_carac('5',$match);
	$nummatchs = count($res);
}

	$SELECT = 'SELECT id, shortname, longname, aka, active, oneyear, type, range, country, creation, website, imgurl, owner_id, plot
                 FROM '.TBL_COMPETITIONS.'
                 WHERE id = '.$competition;				 
	$competdata = runSQL($SELECT);
	
	$SELECT = 'SELECT '.TBL_SEASONS.'.season
                 FROM '.TBL_SEASONS.'
                 WHERE id = '.$season;				 
	$nameseason = runSQL($SELECT);
	
	$allcandidates = runSQL('SELECT '.TBL_CLUBS.'.id, '.TBL_CLUBS.'.shortname, '.TBL_CLUBS.'.id_stadium
					 FROM '.TBL_CANDIDATES.'
					 JOIN '.TBL_CLUBS.' ON '.TBL_CANDIDATES.'.id_club = '.TBL_CLUBS.'.id 			
					 WHERE id_compet ='.$competition.' AND id_season='.$season.' ORDER BY '.TBL_CLUBS.'.shortname');
	
    // existing id?
    if (!count($res)) redirect('competitions.php');
	
    // is it editable/ copyable?
	$administrable = check_permission(PERM_ADMIN, $_COOKIE['PCSuserid']);

	$owners = split(',', $competdata[0]['owner_id']);
	foreach($owners as $owner) {
		if($owner == $_COOKIE['PCSuserid']) {
			$editable = 1;
			$smarty->assign('editable', $editable);
		}
	}
	if (!$administrable && !$editable) {
		errorpage("Access denied",$lang[accessdenied]);
	}	    
    // multi-user permissions
    if ($config['multiuser'])
    {
        $administrable = check_permission(PERM_ADMIN, $_COOKIE['PCSuserid']);
		$owners = split(',', $res[0]['owner_id']);
		foreach($owners as $owner) {
			if($owner == $_COOKIE['PCSuserid']) {
				$editable = 1;
			}
		}
		if ($config['activecomments']) {
	    $smarty->assign('commentable', check_permission(PERM_MKCOMMENT, $_COOKIE['PCSuserid']));
		}
		if ($config['activegallery']) {
	    $smarty->assign('seegallery', check_permission(PERM_GALLERY, $_COOKIE['PCSuserid']));
		}
    }


    // previous/next buttons
    $ids = $_SESSION['pcs']['query_result'];
    if (is_array($ids))
    {
        if (($key = array_search($competition, $ids)) !== false)
        {
            $prev_id = ($key > 0) ? $ids[$key-1] : 0;
            $next_id = ($key < count($ids)-1) ? $ids[$key+1] : 0;
        }
    }
}

if (!$season) {$season = $config['seasonfilterdefault'];}
if (!$advlines) {$advlines  = $config['advlines'];}
if (!$subslines) {$subslines  = $config['subslines'];}
if ($config['competitionstats'] && $competdata[0]['active']) {
$smarty->assign('statsactive', 1);
}

$smarty->assign('advlines', $advlines);
$smarty->assign('subslines', $subslines);
$smarty->assign('competition', $competition);
$smarty->assign('namecompet', $competdata[0]);
$smarty->assign('rooster', $rooster);
$smarty->assign('day', $day);
$smarty->assign('allcandidates', $allcandidates);
$smarty->assign('season', $season);
$smarty->assign('haveseason', $season);
$smarty->assign('administrable', $administrable);
$smarty->assign('editable', $editable);
$smarty->assign('commentable', $commentable);
$smarty->assign('prev_id', $prev_id);
$smarty->assign('next_id', $next_id);
$smarty->assign('seegallery', $seegallery);
$smarty->assign('nummatchs', $nummatchs);
$smarty->assign('numdays', $numdays);
$smarty->assign('nameseason', $nameseason[0]);
$smarty->assign('competdata', $competdata[0]);

// prepare templates
tpl_page('detailview', $matchs['name']);
tpl_edit_goals($matchs,$competition,$season,$match);

// caching enabled?
if ($config['http_caching'])
{
    require_once('./core/httpcache.php');
    httpCacheCaptureStart();
}

// display templates
smarty_display('header.tpl');
if (!$config['http_caching']) flush();

smarty_display('edit_goals.tpl', $competition);
smarty_display('footer.tpl');

// caching enabled?
if ($config['http_caching'])
{
    httpCacheOutput('edit_goals'.$competition.$season, httpCacheCaptureEnd());
}

?>
