<?
/**
 * Edit Page
 *
 * The edit form for adding and editing candidate data
 *
 * @package PHP Competition System
 * @author  Eric GALLENE <okrome@free.fr>
 * @link	http://www.phpcompet.com
 * @version $Id: edit_candidates.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;
	
// list of fields to be read/written from/to html form
$candidate_set_fields    = array('id_compet','id_season','id_club','penality');
$params_set_fields        = array('dom_vic','dom_nul','dom_def','ext_vic','ext_nul','ext_def','dom_vic_ext','dom_nul_ext','dom_def_ext','ext_vic_ext','ext_nul_ext','ext_def_ext','period','period_time','extension','extension_time','accession','barrage','relegation','ar');
// list of fields to be overwritten by refetchAllInfos-Script
$candidate_overwrite_fields    = array('penality');

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


//add Season
if ($addseason) {

	if ($newseason)
    {
	$INSERT = 'INSERT INTO '.TBL_SEASONS.' (season) VALUES ('.$newseason.')';
	$result = runSQL($INSERT);
	redirect('edit_candidates.php?competition='.$mycompet.'&season='.$season);
	}
	else {
	redirect('edit_candidates.php?competition='.$mycompet.'&season='.$season);
	}

}


// save data
if ($save)
{
    if ($noError)
    {
        	$DELETE = 'DELETE FROM '.TBL_CANDIDATES.' WHERE id_compet='.$mycompet.' AND id_season='.$season;
			$result = runSQL($DELETE);
			
			$DELETE = 'DELETE FROM '.TBL_CLMNT.' WHERE id_compet='.$mycompet.' AND id_season='.$season;
			$result = runSQL($DELETE);


			//Insertion in Candidates Table
			$VALUES="";
			// update all fields according to list
			foreach ($candidate as $name)
			{
				if ($VALUES) {$VALUES .= ",";}
				$VALUES .= "(".$mycompet.",".$name.",".$season.",0)";		
			}
			$INSERT = 'INSERT INTO '.TBL_CANDIDATES.' (id_compet, id_club, id_season, penality) VALUES '.$VALUES;
			// insert new record
            $id = runSQL($INSERT);

			//Insertion in Classification Table for first days at 0 points
			$VALUES="";
			// update all fields according to list
			foreach ($candidate as $name)
			{
				if ($VALUES) {$VALUES .= ",";}
				$VALUES .= "(".$mycompet.",".$season.",1,".$name.")";		
			}
			$INSERT = 'INSERT INTO '.TBL_CLMNT.' (id_compet, id_season, id_day, id_team) VALUES '.$VALUES;
			// insert new record
            $id = runSQL($INSERT);
			
        
        $smarty->clear_cache($id);

	   // show the saved competition
	   redirect('show_competitions.php?id='.$mycompet.'&season='.$season);
	   
	}
}

// save data
if ($saveparam)
{
	if ($ar == 'on') {$ar=1;}
	else {$ar=0;}
	$totalresults = runSQL('SELECT count(*) AS num FROM '.TBL_PARAMS.' WHERE id_compet='.$mycompet.' AND id_season='.$season);
	
	// update all fields according to list
    foreach ($params_set_fields as $name)
    {
	
		$$name = removeEvilTags($$name);
        // make sure no formatting contained in basic data
        if ($SETS) $SETS .= ', ';
        $SETS .= "$name = '".addslashes($$name)."'";

    }
	
	$taborder="";
	for ($x=1;$x<5;$x++) {
		if (${'taborder'.$x}) {
			if ($taborder) {$taborder .= ",";}
			$taborder .= ${'taborder'.$x};
		}
	}
	$SETS .= ",taborder = '".addslashes($taborder)."'";

	if ($totalresults[0]['num'])
        {
            $INSERT = 'UPDATE '.TBL_PARAMS.' SET '.$SETS.' WHERE id_compet='.$mycompet.' AND id_season='.$season;
        }
        else
        {
            // insert new record
            $INSERT = 'INSERT INTO '.TBL_PARAMS.' SET '.$SETS.',id_compet='.$mycompet.',id_season='.$season;
            
        }
	runSQL($INSERT);
	redirect('show_competitions.php?id='.$mycompet.'&season='.$season);
}


// load existing data
if ($competition)
{
	if (!$season) {$season       = $config['seasonfilterdefault'];}
	
	// select all fields according to list, plus id
	foreach ($candidate_set_fields as $name)
    {
		if ($SELECT) $SELECT .= ', ';
		$SELECT .= $name;
	}

    $SELECT = 'SELECT '.TBL_CLUBS.'.id, '.$SELECT.', '.TBL_CLUBS.'.shortname as clubname, '.TBL_CLUBS.'.country as country
                 FROM '.TBL_CANDIDATES.', '.TBL_CLUBS.'
                 WHERE id_compet = '.$competition.' AND id_season='.$season.' AND '.TBL_CLUBS.'.id = '.TBL_CANDIDATES.'.id_club ORDER BY clubname';				 
	$candidate = runSQL($SELECT);
	
	// select all fields according to list, plus id
	foreach ($params_set_fields as $name)
    {
		if ($SELECT2) $SELECT2 .= ', ';
		$SELECT2 .= $name;
	}
	
	$SELECT = 'SELECT '.TBL_PARAMS.'.id_compet,'.TBL_PARAMS.'.taborder,'.$SELECT2.'
                 FROM '.TBL_PARAMS.'
                 WHERE id_compet = '.$competition.' AND id_season='.$season;				 
	$params = runSQL($SELECT);
	if ($params[0]['taborder']) {$params[0]['taborder'] = explode(',',$params[0]['taborder']);}

	$SELECT = 'SELECT '.TBL_SEASONS.'.season
                 FROM '.TBL_SEASONS.'
                 WHERE id = '.$season;				 
	$nameseason = runSQL($SELECT);	
	
	$SELECT = 'SELECT id, shortname, longname, aka, active, type, range, oneyear, country, creation, website, imgurl, owner_id, plot
                 FROM '.TBL_COMPETITIONS.'
                 WHERE id = '.$competition;				 
	$competdata = runSQL($SELECT);
	
	// multi-user permissions
    if ($config['multiuser'])
    {
		$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]);
		}	
		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);
        }
    }
	
	if ($config['competitionstats'] && $competdata[0]['active']) {
	$smarty->assign('statsactive', 1);
	}
	$smarty->assign('mycompetition', $competition);
	$smarty->assign('administrable', $administrable);
	$smarty->assign('myseason', $season);
	$smarty->assign('competdata', $competdata[0]);
	$smarty->assign('nameseason', $nameseason[0]);
	$smarty->assign('params', $params[0]);
	
} 


// prepare templates
tpl_page();
tpl_edit_candidate($candidate, $competdata[0]);

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

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

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

?>
