<?php

// Get POST data
$data = json_decode(file_get_contents("php://input"));

// Check if both email and password are provided
if (isset($data->email) && isset($data->password)) {
	$email = $data->email;
	$password = $data->password; // assumed to be in MD5 or some other hashed format

	// SQL to find the user by email/password, plus join with 'officials' table
	$sql = "
		SELECT user.id, user.iwwf_id, user.email, 
			   officials.first_name, officials.last_name
		FROM user 
		INNER JOIN officials ON user.iwwf_id = officials.iwwf_id
		WHERE user.email = ? AND user.password = ?
		LIMIT 1
	";
	$stmt = $conn->prepare($sql);
	$stmt->bind_param("ss", $email, $password);
	$stmt->execute();
	$result = $stmt->get_result();

	if ($result->num_rows > 0) {
		// User found
		$user = $result->fetch_assoc();

		// Generate a random bearer token
		// random_bytes(16) yields 16 bytes => 32 hex chars via bin2hex()
		$token = bin2hex(random_bytes(16));

		// Update the user table with this new token
		$updateSql = "UPDATE user SET bearer = ? WHERE id = ?";
		$updateStmt = $conn->prepare($updateSql);
		$updateStmt->bind_param("si", $token, $user["id"]);
		$updateStmt->execute();
		$updateStmt->close();

		// Include the token in the response
		echo json_encode([
			"success" => true,
			"bearer"  => $token,  // The newly generated token
			"user"    => $user    // Includes id, iwwf_id, email, first_name, last_name
		]);
	} else {
		// Invalid credentials
		echo json_encode([
			"success" => false,
			"message" => "Invalid credentials."
		]);
	}

	$stmt->close();
} else {
	// Email or password not provided
	echo json_encode([
		"success" => false,
		"message" => "Email and password are required."
	]);
}

?>