<?php
	require_once ("include/Configuration.inc.php");

	$pdo = null;
	$pdoex = null;

	try
	{
		$pdo = new \PDO("mysql:host=" . System::$Configuration["Database.ServerName"] . ";port=" . System::$Configuration["Database.PortNumber"] . ";dbname=" . System::$Configuration["Database.DatabaseName"], System::$Configuration["Database.UserName"], System::$Configuration["Database.Password"]);
	}
	catch (Exception $ex)
	{
		$pdoex = $ex;
		echo($pdoex); die();
	}
	
	$data = file_get_contents("php://input");
	$json = json_decode($data, true);

	$action = $json["action"];
	if ($action == "createTenant")
	{
		$tenantName = $json["tenantName"];
		$tenantType = $json["tenantType"];
		$tenantCount =  $json["tenantCount"];

		$stmt = $pdo->prepare("INSERT INTO mocha_tenants (tenant_name, global_identifier, effective_date, is_library) VALUES (:tenant_name, mocha_uuid_v4(), NOW(), 0)");
		$stmt2 = $pdo->prepare("INSERT INTO mocha_tenant_references (source_tenant_id, target_tenant_id) VALUES (:source_tenant_id, 1)");
		
		if ($tenantCount == 1)
		{
			$result = $stmt->execute(array
			(
				"tenant_name" => $tenantName
			));

			$lastInsertId = $pdo->lastInsertId();
			$result = $stmt2->execute(array
			(
				":source_tenant_id" => $lastInsertId
			));

			echo ($result);
		}
		else if ($tenantCount > 1)
		{
			for ($i = 0; $i < $tenantCount; $i++)
			{
				$result = $stmt->execute(array
				(
					"tenant_name" => $tenantName . ($i + 1)
				));

				$lastInsertId = $pdo->lastInsertId();
				$result = $stmt2->execute(array
				(
					":source_tenant_id" => $lastInsertId
				));
				
				echo ($result);
			}
		}
	}
	else
	{
		echo("undefined action: '" . $action . "'");
	}
?>