<?php

/**
 * We'll handle:
 *   GET  => tv.php?competitionCode=XYZ   (fetch row or create)
 *   POST => { competitionCode, key, value } (update or create row)
 */

function respond($success, $dataOrError = null) {
	if ($success) {
		echo json_encode([
			'success' => true,
			'data' => $dataOrError
		]);
	} else {
		echo json_encode([
			'success' => false,
			'error' => $dataOrError
		]);
	}
	exit;
}

// Common valid columns
$validColumns = ['athlete','profile','startlist','results','schedule','automate'];

// -------------------------
// 1) Handle GET
// -------------------------
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
	if (!isset($_GET['competitionCode'])) {
		respond(false, "Missing competitionCode in query");
	}
	$competitionCode = $_GET['competitionCode'];

	// Check if row exists
	$checkSql = "SELECT * FROM tv WHERE competition_code = ? LIMIT 1";
	$stmt = $conn->prepare($checkSql);
	if (!$stmt) {
		respond(false, "Prepare failed: " . $conn->error);
	}
	$stmt->bind_param('s', $competitionCode);
	$stmt->execute();
	$result = $stmt->get_result();
	
	if ($row = $result->fetch_assoc()) {
		// Row found
		$stmt->close();
		respond(true, [
			'athlete'  => (int)$row['athlete'],
			'results'  => (int)$row['results'],
			'startlist'=> (int)$row['startlist'],
			'profile'  => (int)$row['profile'],
			'schedule' => (int)$row['schedule'],
			'automate' => (int)$row['automate']
		]);
	} else {
		// No row => create all 0
		$stmt->close();
		$insertSql = "INSERT INTO tv 
			(competition_code, athlete, results, startlist, profile, schedule, automate)
			VALUES (?, 0, 0, 0, 0, 0, 0)";
		$insertStmt = $conn->prepare($insertSql);
		if (!$insertStmt) {
			respond(false, "Prepare insert failed: " . $conn->error);
		}
		$insertStmt->bind_param('s', $competitionCode);
		if (!$insertStmt->execute()) {
			$insertStmt->close();
			respond(false, "Insert failed: " . $conn->error);
		}
		$insertStmt->close();
		// Return the newly created row
		respond(true, [
			'athlete'  => 0,
			'results'  => 0,
			'startlist'=> 0,
			'profile'  => 0,
			'schedule' => 0,
			'automate' => 0
		]);
	}
}

// -------------------------
// 2) Handle POST
// -------------------------
elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
	$input = json_decode(file_get_contents('php://input'), true);
	if (!$input) {
		respond(false, "Invalid JSON body");
	}

	$competitionCode = $input['competitionCode'] ?? null;
	$key = $input['key'] ?? null;      
	$value = $input['value'] ?? null;  // 0 or 1 ?

	// Basic checks
	if (!$competitionCode || !$key || !in_array($value, [0,1])) {
		respond(false, "Missing or invalid fields (need competitionCode, key, value 0/1).");
	}
	// Ensure $key is valid
	if (!in_array($key, $validColumns)) {
		respond(false, "Invalid key column");
	}

	// Check if row exists
	$checkSql = "SELECT id FROM tv WHERE competition_code = ? LIMIT 1";
	$stmt = $conn->prepare($checkSql);
	if (!$stmt) {
		respond(false, "Prepare check failed: " . $conn->error);
	}
	$stmt->bind_param('s', $competitionCode);
	$stmt->execute();
	$res = $stmt->get_result();

	// If row not exist => create
	if (!$res->fetch_assoc()) {
		$stmt->close();
		$insertSql = "INSERT INTO tv (competition_code, $key) VALUES (?, ?)";
		$insertStmt = $conn->prepare($insertSql);
		if (!$insertStmt) {
			respond(false, "Prepare insert failed: " . $conn->error);
		}
		$insertStmt->bind_param('si', $competitionCode, $value);
		if (!$insertStmt->execute()) {
			$insertStmt->close();
			respond(false, "Insert failed: " . $conn->error);
		}
		$insertStmt->close();
		// newly inserted row is done
		// if $value=1 => also set all others=0, except the key column
		if ($value === 1) {
			zeroOtherColumns($conn, $competitionCode, $key);
		}
		respond(true);
	}
	$stmt->close();

	// Row exists => update
	// If we set this key=1 => set all others=0 first
	if ($value === 1) {
		zeroOtherColumns($conn, $competitionCode, $key);
	}

	// Then set $key = $value
	$updateSql = "UPDATE tv SET $key = ? WHERE competition_code = ?";
	$updateStmt = $conn->prepare($updateSql);
	if (!$updateStmt) {
		respond(false, "Prepare update failed: " . $conn->error);
	}
	$updateStmt->bind_param('is', $value, $competitionCode);
	if (!$updateStmt->execute()) {
		$updateStmt->close();
		respond(false, "Update failed: " . $conn->error);
	}
	$updateStmt->close();

	respond(true);
}

// If we get here, unknown method
respond(false, "Unsupported request method");

// ----------------------------------------------------------
// Function: zeroOtherColumns
//   sets all columns to 0 except for $key
// ----------------------------------------------------------
function zeroOtherColumns($conn, $competitionCode, $excludeKey) {
	// Build a dynamic query that sets all valid columns = 0 except $excludeKey
	$valid = ['athlete','profile','startlist','results','schedule','automate'];
	// Remove the $excludeKey from the set
	$colsToZero = array_diff($valid, [$excludeKey]);
	// e.g. if excludeKey='athlete', then $colsToZero = ['profile','startlist','results','schedule','automate']

	// We'll build a snippet like: "profile=0, startlist=0, results=0, schedule=0, automate=0"
	$assignments = [];
	foreach ($colsToZero as $col) {
		$assignments[] = "$col=0";
	}
	$assignStr = implode(", ", $assignments);
	// e.g. "profile=0, startlist=0, results=0, schedule=0, automate=0"

	// Now do: "UPDATE tv SET profile=0, startlist=0... WHERE competition_code=?"
	$sql = "UPDATE tv SET $assignStr WHERE competition_code = ?";
	$stmt = $conn->prepare($sql);
	if (!$stmt) {
		respond(false, "zeroOtherColumns: prepare failed: " . $conn->error);
	}
	$stmt->bind_param('s', $competitionCode);
	if (!$stmt->execute()) {
		$stmt->close();
		respond(false, "zeroOtherColumns: execute failed: " . $conn->error);
	}
	$stmt->close();
}
?>