<?php
include('dbconnect.php');
include('functions/scoring.php');

$competitionCode = isset($_GET['competitionCode']) ? trim($_GET['competitionCode']) : null;
if (!$competitionCode) {
	header('Content-Type: application/json');
	echo json_encode(["status" => false, "message" => "Missing competitionCode parameter."]);
	exit;
}

// helper to coalesce and escape
function esc($val) {
	return htmlspecialchars((string)($val ?? ''), ENT_QUOTES, 'UTF-8');
}

$xml = new DOMDocument('1.0', 'UTF-8');
$xml->formatOutput = true;

$root = $xml->createElement('WaterskiScoring');
$root->setAttribute('content', 'Results');
$xml->appendChild($root);

$software = $xml->createElement('Software');
$software->setAttribute('Name', 'WaterskiScoring');
$software->setAttribute('Version', '2025.00');
$software->setAttribute('License', 'IWWF - E&A Waterski confederation');
$root->appendChild($software);

$compQ = "SELECT c.discipline, c.code, c.name, c.organizing_country, c.tournament_type, c.tournament_code, c.venue, c.site_code, c.beginning_date, c.end_date, c.age_group, d.ems_code AS discipline_code 
FROM competitions c
JOIN disciplines d ON c.discipline = d.name
WHERE c.code = ?";
$stmt = $conn->prepare($compQ);
$stmt->bind_param('s', $competitionCode);
$stmt->execute();
$competition = $stmt->get_result()->fetch_assoc() ?: null;
$stmt->close();
if (!$competition) {
	header('Content-Type: application/json');
	echo json_encode(["status" => false, "message" => "Competition not found."]);
	exit;
}

$compNode = $xml->createElement('Competition');
$compNode->setAttribute('discipline', htmlspecialchars($competition['discipline']));
$compNode->setAttribute('code', htmlspecialchars($competition['code']));
$root->appendChild($compNode);

function addEl($doc, $parent, $name, $value) {
	$el = $doc->createElement($name, htmlspecialchars((string)$value));
	$parent->appendChild($el);
	return $el;
}

$d = addEl($xml, $compNode, 'Discipline', $competition['discipline']);
$d->setAttribute('EmsCode', htmlspecialchars($competition['discipline_code']));
addEl($xml, $compNode, 'Code', $competition['code']);
addEl($xml, $compNode, 'Name', $competition['name']);
addEl($xml, $compNode, 'OrganizingCountry', $competition['organizing_country']);
$t = addEl($xml, $compNode, 'TournamentType', $competition['tournament_type']);
$t->setAttribute('EmsCode', htmlspecialchars($competition['tournament_code']));
addEl($xml, $compNode, 'Venue', $competition['venue']);
addEl($xml, $compNode, 'SiteCode', $competition['site_code']);
addEl($xml, $compNode, 'BeginningDate', $competition['beginning_date']);
addEl($xml, $compNode, 'EndDate', $competition['end_date']);
$ag = addEl($xml, $compNode, 'AgeGroup', 'IWWF');
$ag->setAttribute('EmsCode', 'AG01');


// Insert JuryPanel
$juryQ = "SELECT iwwf_id, position, ems_code, last_name, first_name, country FROM officials WHERE competition_code = ? ORDER BY id";
$stmt = $conn->prepare($juryQ);
$stmt->bind_param('s', $competitionCode);
$stmt->execute();
$juryRes = $stmt->get_result();
$stmt->close();
if ($juryRes->num_rows) {
	$juryNode = $xml->createElement('JuryPanel');
	while ($off = $juryRes->fetch_assoc()) {
		$o = $xml->createElement('Official');
		$o->setAttribute('IWWFId', htmlspecialchars($off['iwwf_id']));
		addEl($xml, $o, 'Position', $off['position'])->setAttribute('EmsCode', esc($off['ems_code']));
		addEl($xml, $o, 'LastName', $off['last_name']);
		addEl($xml, $o, 'FirstName', $off['first_name']);
		$qual = addEl($xml, $o, 'Qualification', '');
		$qual->setAttribute('EmsCode', '');
		addEl($xml, $o, 'Country', $off['country']);
		$juryNode->appendChild($o);
	}
	$compNode->appendChild($juryNode);
}

// Fetch events
$eventQ = "SELECT id, event_code, event_name, ems_code, class FROM events WHERE competition_code = ? ORDER BY event_code";
$stmt = $conn->prepare($eventQ);
$stmt->bind_param('s', $competitionCode);
$stmt->execute();
$eventRes = $stmt->get_result();
$stmt->close();

	$clsNode = $xml->createElement('Classifications');


if ($eventRes->num_rows) {
	while ($eventRow = $eventRes->fetch_assoc()) {

// Fetch categories for this event
	$catQ = "SELECT DISTINCT c.code AS category_code, c.name AS category_name, c.ems_code AS category_ems_code
			   FROM runs r
			   JOIN schedule sch ON r.schedule = sch.id
			   JOIN athletes a ON r.athlete = a.id
			   JOIN categories c ON a.category_in_competition = c.code AND a.gender = c.gender
			   WHERE a.event_code = ? AND a.competition_code = ?
			   ORDER BY c.code";
	$stmt2 = $conn->prepare($catQ);
	$stmt2->bind_param('ss', $eventRow['event_code'], $competitionCode);	$stmt2->execute();
	$catRes = $stmt2->get_result();
	$stmt2->close();

if ($catRes->num_rows) {
	$i = 1;
	while ($cat = $catRes->fetch_assoc()) {
		$cn = $xml->createElement('Classification');
		$cn->setAttribute('Type', 'Individual');
		$cn->setAttribute('ID', $i);

		$sel = $xml->createElement('Selection');
		$cats = $xml->createElement('Categories');
		$catEl = $xml->createElement('Category', htmlspecialchars($cat['category_name']));
		$catEl->setAttribute('EmsCode', htmlspecialchars($cat['category_ems_code']));
		$cats->appendChild($catEl);
		$sel->appendChild($cats);
		$cn->appendChild($sel);

		$eventTag = $xml->createElement('Event', htmlspecialchars((string)$eventRow['event_name']));
		$eventTag->setAttribute('EmsCode', htmlspecialchars((string)$eventRow['event_code']));
		$cn->appendChild($eventTag);

		$displayName = htmlspecialchars((string)$eventRow['event_name']) . ' ' . $cat['category_name'] . ' Results';
		addEl($xml, $cn, 'DisplayName', $displayName);

		$drNode = $xml->createElement('DisplayRounds');
		$r = $xml->createElement('Round', 'Score'); $r->setAttribute('Round','1');
		$p = $xml->createElement('Points', 'Points'); $p->setAttribute('Visible','false');
		$oa = $xml->createElement('Overall', 'Overall'); $oa->setAttribute('Visible','false');
		$t = $xml->createElement('TeamOverall', 'Team'); $t->setAttribute('Visible','false');
		$drNode->appendChild($r);
		$drNode->appendChild($p);
		$drNode->appendChild($oa);
		$drNode->appendChild($t);
		$cn->appendChild($drNode);

		$athCls = $xml->createElement('Athletes');
		$aQ = "SELECT a.fed_id, a.last_name, a.first_name, a.country, a.gender, a.year_of_birth, a.final_placement, a.event_code, a.id AS id,
		r.six_star, r.five_star, r.four_star, r.three_star, r.two_star, r.one_star, a.category_in_competition,
		c.ems_code
		FROM athletes a
		JOIN ranking_points r ON a.final_placement = r.rank
		JOIN categories c ON a.category_in_competition = c.code AND a.gender = c.gender 
		WHERE competition_code = ? AND c.ems_code = ? AND a.event_code = ? 
		ORDER BY final_placement ASC";
		$stmt2 = $conn->prepare($aQ);
		$stmt2->bind_param('sss', $competitionCode, $cat['category_ems_code'], $eventRow['event_code']);
		$stmt2->execute();
		$athClsRes = $stmt2->get_result();
		$stmt2->close();

		while ($aRow = $athClsRes->fetch_assoc()) {
			$ac = $xml->createElement('Athlete');
			$ac->setAttribute('IWWFId', htmlspecialchars($aRow['fed_id']));
			addEl($xml, $ac, 'Place', $aRow['final_placement']);
			addEl($xml, $ac, 'LastName', $aRow['last_name']);
			addEl($xml, $ac, 'FirstName', $aRow['first_name']);
			addEl($xml, $ac, 'DisplayName', $aRow['last_name']. ' ' .$aRow['first_name']);
			$co = addEl($xml, $ac, 'CategoryInCompetition', $cat['category_name']);
			$co->setAttribute('EmsCode', htmlspecialchars($cat['category_ems_code']));
			addEl($xml, $ac, 'TeamMember', 'false');
			addEl($xml, $ac, 'WildCard', 'false');
			$dt = addEl($xml, $ac, 'DisplayTeam', '*'.$aRow['country']);
			$dt->setAttribute('Type', 'Country');
			addEl($xml, $ac, 'Country', $aRow['country']);
			$dv = addEl($xml, $ac, 'Division', '0');
			$dv->setAttribute('Event', htmlspecialchars((string)$eventRow['event_code']));
			
			// --- inside your athlete loop, after creating $scNode ---
			$scNode = $xml->createElement('Runs');
			
			// query every run score for this athlete and this event
			$scoreQ = "
				SELECT
				  hs.round       AS Round,
				  sch.event      AS Event,
				  r.run          AS Run,
				  r.id           AS Run_Id,
				  hs.qualify     AS Qualify
				FROM runs r
				JOIN schedule sch      ON r.schedule = sch.id
				JOIN heatsystem hs     ON sch.heatsystem = hs.id
				WHERE r.athlete = ? 
				  AND sch.event = ?
				ORDER BY hs.round DESC
			";
			$stmtScores = $conn->prepare($scoreQ);
			$stmtScores->bind_param('is', $aRow['id'], $eventRow['id']);
			$stmtScores->execute();
			$scoresRes = $stmtScores->get_result();
			
			$points = [];
			while ($sr = $scoresRes->fetch_assoc()) {
				if ($sr['Qualify'] == 0) {
					$points[] = getFinalScore($sr['Run_Id'], $conn, $competitionCode);
				}
			}
			
			// now pick out the highest
			if (!empty($points)) {
				$highestPoint = max($points);
				$highestPointFormatted = number_format($highestPoint, 2, '.', '');
			} else {
				$highestPointFormatted = '00.00'; // or null, or whatever default you prefer
			}
			
			// $highestPoint now contains the highest score from the array
			
			$stmtScores->close();
			
			// now attach it to the athlete
			$ac->appendChild($scNode);
					
			$scNode = $xml->createElement('Scores');
			$p = $xml->createElement('Score');
			$p->setAttribute('ID',$aRow['id']);
			$p->setAttribute('Round','1');  
			$p->setAttribute('Event',htmlspecialchars((string)$eventRow['event_code']));
			$p->setAttribute('DisplayScore',$highestPointFormatted); 
			$p->setAttribute('Score',$highestPointFormatted);
			$p->setAttribute('Class',htmlspecialchars((string)$eventRow['ems_code']));
			//$p->setAttribute('Class','');
			$scNode->appendChild($p);
			$ac->appendChild($scNode);
			
			$athCls->appendChild($ac);
		}
		$cn->appendChild($athCls);
		$clsNode->appendChild($cn);
		$i++;
	}
	$compNode->appendChild($clsNode);
}

}
}


header('Content-Type: application/xml');
echo $xml->saveXML();
?>

