<?php
chdir(dirname(__FILE__));
require "../lib/connection.php";
require_once "../lib/GJPCheck.php";
require_once "../lib/exploitPatch.php";
require_once "../lib/mainLib.php";
$gs = new mainLib();
$stars = ExploitPatch::remove($_POST["stars"]);
$feature = ExploitPatch::remove($_POST["feature"]);
$levelID = ExploitPatch::remove($_POST["levelID"]);
$accountID = GJPCheck::getAccountIDOrDie();
$difficulty = $gs->getDiffFromStars($stars);
if($gs->checkPermission($accountID, "actionRateStars")) {
	$gs->featureLevel($accountID, $levelID, $feature);
	$gs->verifyCoinsLevel($accountID, $levelID, 1);
	$gs->rateLevel($accountID, $levelID, $stars, $difficulty["diff"], $difficulty["auto"], $difficulty["demon"]);

	// --- Discord rate/unrate notification -------------------------
	try {
		$levelRow = $db->prepare("SELECT levelName, userID, downloads, likes, requestedStars, levelDesc FROM levels WHERE levelID = :levelID");
		$levelRow->execute([':levelID' => $levelID]);
		$levelData = $levelRow->fetch();

		$creatorQuery = $db->prepare("SELECT userName FROM users WHERE userID = :userID");
		$creatorQuery->execute([':userID' => $levelData['userID'] ?? 0]);
		$creatorName = $creatorQuery->fetchColumn() ?: "Unknown";

		$raterQuery = $db->prepare("SELECT userName FROM accounts WHERE accountID = :accountID");
		$raterQuery->execute([':accountID' => $accountID]);
		$raterName = $raterQuery->fetchColumn() ?: "Someone";

		$notifyPayload = json_encode([
			'action' => ((int)$stars === 0) ? 'unrated' : 'rated',
			'raterName' => $raterName,
			'levelID' => $levelID,
			'levelName' => $levelData['levelName'] ?? 'Unnamed',
			'creatorName' => $creatorName,
			'difficultyText' => $difficulty['name'] ?? 'N/A',
			'stars' => $stars,
			'downloads' => $levelData['downloads'] ?? 0,
			'likes' => $levelData['likes'] ?? 0,
			'requestedStars' => $levelData['requestedStars'] ?? 0,
			'description' => $levelData['levelDesc'] ?? '',
		]);

		$ch = curl_init('http://127.0.0.1:8090/rate-notify');
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $notifyPayload);
		curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
		curl_setopt($ch, CURLOPT_TIMEOUT, 3);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_exec($ch);
		curl_close($ch);
	} catch (\Throwable $e) {
		// Never let a notification failure break the actual rate command
	}

	exit('1');
} elseif($gs->checkPermission($accountID, "actionSuggestRating")) {
	$gs->suggestLevel($accountID, $levelID, $difficulty["diff"], $stars, $feature, $difficulty["auto"], $difficulty["demon"]);
	exit('1');
} else exit('-2');
?>