<?
/**
 * Edit Page
 *
 * The edit form for adding and editing teams data
 *
 * @package PHP Competition System
 * @author  Eric GALLENE <okrome@free.fr>
 * @link	http://www.phpcompet.com
 * @version $Id: edit_teams.php,v 1.00 2006/10/26 19:47:13
 */

require_once './core/functions.php';
require_once './core/security.php';

// check for localnet
localnet_or_die();
// multiuser permission check
permission_or_die(PERM_WRITE);
$noError = true;

// get default lookup mode (0=ignore, 1=lookup, 2=overwrite) if not set
if (!isset($lookup)) $lookup = (empty($id)) ? $lookup = 2 : $config['lookupdefault'];

// save data
if ($save)
{
	if ($seasoncopy) {$season = $seasoncopy;}
	$stack[] ='';
	$SELECT = 'SELECT id_person FROM '.TBL_TEAMS.' WHERE id_club='.$myclub.' AND id_season='.$season;
	$result = runSQL($SELECT);		
	foreach ($result as $re) {array_push ($stack, $re['id_person']);}
	
	$todelete = array_diff ($stack, $candidate);
		if ($todelete) {			
			foreach ($todelete as $name) {
				if ($name) {
				$DELETE = 'DELETE FROM '.TBL_TEAMS.' WHERE id_club='.$myclub.' AND id_season='.$season.' AND id_person='.$name;
				$result = runSQL($DELETE);
				}
			}
		}
	$toinsert = array_diff ($candidate, $stack);			
		if ($toinsert) {	
			$VALUES="";
			// update all fields according to list
			foreach ($toinsert as $name)
			{
				if ($VALUES) {$VALUES .= ",";}
				$VALUES .= "(".$name.",".$myclub.",".$season.")";		
			}
			$INSERT = 'INSERT INTO '.TBL_TEAMS.' (id_person, id_club, id_season) VALUES '.$VALUES;
			// insert new record
            $id = runSQL($INSERT);
		}
        $smarty->clear_cache($id);

	   // show the saved club
	   redirect('show_teams.php?id='.$myclub.'&season='.$season);
}



// load existing data
if ($id)
{
	if (!$season) {$season = $config['seasonfilterdefault'];}
	
	//Club information
	$SELECT = 'SELECT '.TBL_CLUBS.'.id, '.TBL_CLUBS.'.shortname, '.TBL_CLUBS.'.longname, '.TBL_CLUBS.'.aka, '.TBL_CLUBS.'.country, '.TBL_CLUBS.'.city, 
			  '.TBL_CLUBS.'.nationalteam, '.TBL_CLUBS.'.imgurl, '.TBL_CLUBS.'.creation, '.TBL_CLUBS.'.website,  '.TBL_CLUBS.'.email, '.TBL_CLUBS.'.adresse, 
			  '.TBL_CLUBS.'.tel, '.TBL_CLUBS.'.fax, '.TBL_CLUBS.'.newspaper, '.TBL_CLUBS.'.owner_id, '.TBL_CLUBS.'.id_stadium as stadium_id, 
			  '.TBL_STADIUMS.'.longname as stadium, '.TBL_CLUBS.'.plot, '.TBL_CLUBS.'.id_president, CONCAT(Pr.lastname, " ", Pr.firstname) AS president
                FROM '.TBL_CLUBS.'
                LEFT JOIN '.TBL_STADIUMS.' ON '.TBL_STADIUMS.'.id = '.TBL_CLUBS.'.id_stadium
				LEFT JOIN '.TBL_PERSONS.' AS Pr ON Pr.id = '.TBL_CLUBS.'.id_president
				WHERE '.TBL_CLUBS.'.id = '.$id.' LIMIT 1;';				 
	$club = runSQL($SELECT);
	
	//Players in the club
	$SELECT = 'SELECT '.TBL_TEAMS.'.id_person as id, '.TBL_PERSONS.'.lastname, '.TBL_PERSONS.'.firstname 
                 FROM '.TBL_TEAMS.'
				 JOIN '.TBL_PERSONS.' ON '.TBL_TEAMS.'.id_person = '.TBL_PERSONS.'.id AND '.TBL_PERSONS.'.type = 1
                 WHERE '.TBL_TEAMS.'.id_season = '.$season.' AND '.TBL_TEAMS.'.id_club = '.$id.' ORDER BY lastname, firstname';				 
	$teamplayers = runSQL($SELECT);	
	$numteamplayers = count($teamplayers);
	$not_in="";
	foreach($teamplayers as $player) {
	if ($not_in) {$not_in.=",";}
	if ($player['id']) {$not_in.=$player['id'];}
	}
	if($not_in) {$NOT_IN = 'AND '.TBL_PERSONS.'.id NOT IN ('.$not_in.')';}
	if($club[0]['nationalteam']) {$NATIO = 'AND '.TBL_PERSONS.'.country = "'.$club[0]["country"].'" AND '.TBL_PERSONS.'.international = 1';}
	

	$SELECT = 'SELECT '.TBL_PERSONS.'.id, '.TBL_PERSONS.'.lastname, '.TBL_PERSONS.'.firstname
	FROM '.TBL_PERSONS.'
	WHERE '.TBL_PERSONS.'.type = 1 '.$NOT_IN.' '.$NATIO.' ORDER BY lastname';
	 
	$players = runSQL($SELECT);	
	$numplayers = count($players);
	
	
	
	
	
	$SELECT = 'SELECT '.TBL_SEASONS.'.season
                 FROM '.TBL_SEASONS.'
                 WHERE '.TBL_SEASONS.'.id = '.$season;				 
	$nameseason = runSQL($SELECT);

	$SELECT = 'SELECT '.TBL_SEASONS.'.id, '.TBL_SEASONS.'.season
                 FROM '.TBL_SEASONS.' ORDER BY '.TBL_SEASONS.'.season ASC';
	$seasonselect = runSQL($SELECT);	
    
	
	// multi-user permissions
    if ($config['multiuser'])
    {
		$administrable = check_permission(PERM_ADMIN, $_COOKIE['PCSuserid']);
		$smarty->assign('administrable', $administrable);
		$owners = split(',', $club[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]);
		}
		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;
			$smarty->assign('prev_id', $prev_id);
			$smarty->assign('next_id', $next_id);
        }
    }
	
	$smarty->assign('numplayers', $numplayers);
	$smarty->assign('numteamplayers', $numteamplayers);
	$smarty->assign('teamplayers', $teamplayers);
	$smarty->assign('nameseason', $nameseason[0]);
	$smarty->assign('myseason', $season);
	$smarty->assign('club', $club[0]);
	$smarty->assign('myclub', $id);
	$smarty->assign('seasonselect', $seasonselect);
	$smarty->assign('clubstats', $config['clubstats']);
	
} 


// prepare templates
tpl_page();
tpl_edit_team($players, $id);

$smarty->assign('http_error', $CLIENTERROR);


// allow XML import
if ($config['xml'] && empty($id)) $smarty->assign('xmlimport', true);

// display templates
tpl_display('edit_teams.tpl');	

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

?>
