<?
/**
 * 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_days.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;

//Add day on season competition
if ($add_day) {

	for ($x=1;$x<$num_add_day+1;$x++) {
	$myday = $x+$numdays;
		if ($VALUES) {$VALUES .= ",";}
		$VALUES .= "(".$myday.",'',".$mycompet.",".$season.")";		
	}
	$INSERT = 'INSERT INTO '.TBL_DAYS.' (day, date_day, id_compet, id_season) VALUES '.$VALUES;
	// insert new record
	$id = runSQL($INSERT);
	$smarty->clear_cache($id);
	redirect('edit_days.php?competition='.$mycompet.'&season='.$season);
}

// save data
if ($save)
{
	$SELECT = 'SELECT '.TBL_COMPETITIONS.'.longname, '.TBL_COMPETITIONS.'.type, '.TBL_COMPETITIONS.'.range, '.TBL_COMPETITIONS.'.oneyear, '.TBL_COMPETITIONS.'.owner_id, '.TBL_PARAMS.'.ar 
				FROM '.TBL_COMPETITIONS.' 
				LEFT JOIN '.TBL_PARAMS.' ON '.TBL_COMPETITIONS.'.id = '.TBL_PARAMS.'.id_compet
				WHERE '.TBL_COMPETITIONS.'.id = '.$mycompet;				 
	$competdata = runSQL($SELECT);
	
	$SELECT = 'SELECT count('.TBL_MATCHS.'.id) AS mycount FROM '.TBL_MATCHS.'
			   JOIN '.TBL_DAYS.' ON  '.TBL_MATCHS.'.id_day = '.TBL_DAYS.'.id 
			   WHERE '.TBL_DAYS.'.id_compet = '.$mycompet.' AND '.TBL_DAYS.'.id_season = '.$season;				 
	$nummatchs = runSQL($SELECT);
	$countmatch = $nummatchs[0]['mycount'];

    if ($noError)
    {
			//If creation, need num candidate
			if (!$update || !$countmatch) {
				$totalcandidate = runSQL('SELECT count(*) AS num FROM '.TBL_CANDIDATES.' WHERE id_compet = '.$mycompet.' AND id_season='.$season);
				if ($competdata[0]['type'] == 2) {
					$nummatchbyday = intval($totalcandidate[0]['num']/2);
				}
				else if ($competdata[0]['type'] == 1) {
					if ($totalcandidate[0]['num']%2) {$nummatchbyday = (sqrt($totalcandidate[0]['num'])+1) * 2;}
					else {$nummatchbyday = sqrt($totalcandidate[0]['num']);}
				}
			}
			
			$SELECT = 'SELECT '.TBL_DAYS.'.id, '.TBL_DAYS.'.day FROM '.TBL_DAYS.' WHERE id_compet = '.$mycompet.' AND id_season='.$season.' ORDER BY day DESC';				 
			$days = runSQL($SELECT);
			$numdays=count($days);
			
				for ($x=0; $x<$numdays; $x++)
				{

					$myday = getusdate(${'date'.$days[$x]['id']});
					$INSERT = "UPDATE ".TBL_DAYS." SET date_day='".$myday."' WHERE id = ".$days[$x]['id'];					
					$id = runSQL($INSERT);

					
						 //if its an update
						 if ($update && $countmatch) {
							$myday = $myday . " ".$myhour.":".$mymin.":00";	
							$INSERT = "UPDATE ".TBL_MATCHS." SET date_day='".$myday."' WHERE id_day = ".$days[$x]['id'];
							//echo $INSERT .'<br>';
							$id = runSQL($INSERT);
						 }
						 else {
							$myday = $myday . " ".$myhour.":".$mymin.":00";
							$VALUES = "";
							if ($competdata[0]['type'] == 2) {	
								for ($y=0; $y<$nummatchbyday; $y++) {
									if ($VALUES) {$VALUES .= ",";}
									$VALUES .= "(".$days[$x]['id'].",'".$myday."')";
								}
							}
							else if  ($competdata[0]['type'] == 1) {
								if (!$competdata[0]['ar']) {
									for ($y=0; $y<pow(2, $x); $y++) {
										if ($VALUES) {$VALUES .= ",";}
										$VALUES .= "(".$days[$x]['id'].",'".$myday."')";
									}
								}
								else {
									if ($numdays%2) {$nd = $numdays+1;}
									else {$nd = $numdays;}
									for ($y=0; $y<pow(2, intval(($nd-$days[$x]['day'])/2)); $y++) {
										if ($VALUES) {$VALUES .= ",";}
										$VALUES .= "(".$days[$x]['id'].",'".$myday."')";
									}
								}
							}
						  $INSERT = 'INSERT INTO '.TBL_MATCHS.' (id_day, date_day) VALUES '.$VALUES;
						  // insert new record
						  $id = runSQL($INSERT);
						 }
				}

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


// load existing data
if ($competition)
{
	if (!$season) {$season = $config['seasonfilterdefault'];}


	$SELECT = 'SELECT '.TBL_COMPETITIONS.'.id, '.TBL_COMPETITIONS.'.shortname, '.TBL_COMPETITIONS.'.longname, '.TBL_COMPETITIONS.'.aka, '.TBL_COMPETITIONS.'.active, '.TBL_COMPETITIONS.'.type, 
			  '.TBL_COMPETITIONS.'.range, '.TBL_COMPETITIONS.'.oneyear, '.TBL_COMPETITIONS.'.country, '.TBL_COMPETITIONS.'.creation, '.TBL_COMPETITIONS.'.website, '.TBL_COMPETITIONS.'.imgurl, '.TBL_COMPETITIONS.'.owner_id, '.TBL_COMPETITIONS.'.plot, '.TBL_PARAMS.'.ar 
				FROM '.TBL_COMPETITIONS.' 
				LEFT JOIN '.TBL_PARAMS.' ON '.TBL_COMPETITIONS.'.id = '.TBL_PARAMS.'.id_compet
				WHERE '.TBL_COMPETITIONS.'.id = '.$competition;				 
	$competdata = runSQL($SELECT);

	
	// is it editable/ copyable?
    //$candidate['editable'] = localnet();
    //$candidate['copyable'] = localnet();
    

	// get total amount of results from DB
	$COUNT = 'SELECT count(*) AS num FROM '.TBL_DAYS.' WHERE id_compet = '.$competition.' AND id_season='.$season;
	$totaldays = runSQL($COUNT);
   
	if (!$totaldays[0]['num']) {
		//Num of candidate for competition
		$totalcandidate = runSQL('SELECT count(*) AS num FROM '.TBL_CANDIDATES.' WHERE id_compet = '.$competition.' AND id_season='.$season);

		//if candidates in this season
		if ($totalcandidate[0]['num']) {
			//Is it an AR competition ?	
			$ar = runSQL('SELECT ar FROM '.TBL_PARAMS.' WHERE id_compet = '.$competition.' AND id_season='.$season);
			
			if ($competdata[0]['type'] == 1) {
				$tr = $totalcandidate[0]['num']; $turn=0;
				while ($tr > 1) {$tr=$tr/2; $turn++;}
				
				if ($ar[0]['ar']) {$numdays = $turn * 2;}
				else {$numdays = $turn;}
			}
			else if ($competdata[0]['type'] == 2) {
				if ($ar[0]['ar']) {$numdays = ($totalcandidate[0]['num'] - 1) * 2;}
				else {
					$numdays = $totalcandidate[0]['num'];
				}
			}
			else {
				if ($ar[0]['ar']) {$numdays = intval(sqrt($totalcandidate[0]['num'])) * 2;}
				else {$numdays = sqrt($totalcandidate[0]['num']);}
			}
			//Insert data without date
			for ($x=$numdays; $x>0; $x--) {
				if ($VALUES) {$VALUES .= ",";}
				$VALUES .= "(".$x.",'',".$competition.",".$season.")";		
			}
			$INSERT = 'INSERT INTO '.TBL_DAYS.' (day, date_day, id_compet, id_season) VALUES '.$VALUES;

			// insert new record
			$id = runSQL($INSERT);
		}
					
	}
	else {
		$update = 1;
	}
			
	$SELECT = 'SELECT '.TBL_DAYS.'.id, day, date_day FROM '.TBL_DAYS.' WHERE id_compet = '.$competition.' AND id_season='.$season.' ORDER BY day';				 
	$days = runSQL($SELECT);
	$numdays=count($days);
	
	$SELECT = 'SELECT '.TBL_SEASONS.'.season
                 FROM '.TBL_SEASONS.'
                 WHERE id = '.$season;				 
	$nameseason = runSQL($SELECT);	
	
	
	// multi-user permissions
    if ($config['multiuser'])
    {
		$administrable = check_permission(PERM_ADMIN, $_COOKIE['PCSuserid']);
		$smarty->assign('administrable', $administrable);
		$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('myseason', $season);
	$smarty->assign('nameseason', $nameseason[0]);
	$smarty->assign('days', $days);
	$smarty->assign('competdata', $competdata[0]);
	$smarty->assign('numdays', $numdays);
	$smarty->assign('update', $update);
	
} 


// prepare templates
tpl_page();
tpl_edit_day($days);

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

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

?>
