<?php
	//echo "deletegroup"; exit;
	function ReportError($e, $mysqliMessage = ""){
		echo "<div style='background-color:#CCCCCC;
											border:1px dotted red;
											width:300px;
											height:380px;
											margin:0;
											padding:5px;
											word-wrap: break-word;
											display:block;
											position:fixed;
											top:15%;
											left:20%;
											font-family:Verdana,Geneva,sans-serif;
											font-size:70%;
											font-weight:bold;'>";
			echo "Error: ".$e->getMessage()."<br />";
			echo "File: ".basename($e->getFile())."<br />";
			echo "Line: ".$e->getLIne()."<br />";
			if ($mysqliMessage != "") {
				echo mysqli_connect_error();
			}
		echo "</div>\n";
	}
		
	chdir('../');

	include('includes/include_all.inc.php');

	try {
		$pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
		$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	} catch(PDOException $e) {
		die("Connection failed: " . $e->getMessage());
	}

	//Create User object
	$obj_users = new Users($pdo);

	if(!$obj_users->checkUserLoginOrNot()){
		header('Location: '.BASEURL.'login.php');
		exit();
	} 

	if($_SESSION['user_type']!='super' && $_SESSION['user_type']!='admin'){ 
		session_destroy();
		header('Location: '.BASEURL.'login.php');
		exit();
	}

	if(isset($_GET["id"]) && !empty($_GET["id"])) {
		$groupId = (int)$_GET['id'];
	} else {
		header('Location: '.BASEURL.'admin/index.php');
		exit();
	}

	$groupname = $_GET["groupname"];

	try {
		$pdo->beginTransaction();

		$deleteQuery = "DELETE FROM wp_groups WHERE id = :groupId";
		$stmt = $pdo->prepare($deleteQuery);
		$stmt->bindParam(':groupId', $groupId, PDO::PARAM_INT);
		$stmt->execute();

		$getUserIds = "SELECT id FROM wp_users WHERE user_group = :groupname";
		$stmt = $pdo->prepare($getUserIds);
		$stmt->bindParam(':groupname', $groupname, PDO::PARAM_STR);
		$stmt->execute();

		$userIds = $stmt->fetchAll(PDO::FETCH_COLUMN);

		if (!empty($userIds)) {
			$placeholders = implode(',', array_fill(0, count($userIds), '?'));

			$deleteCasesQuery = "DELETE FROM wp_groupusers_data WHERE user_id IN ($placeholders)";
			$stmt = $pdo->prepare($deleteCasesQuery);
			$stmt->execute($userIds);

			$deleteUsersQuery = "DELETE FROM wp_users WHERE user_group = :groupname";
			$stmt = $pdo->prepare($deleteUsersQuery);
			$stmt->bindParam(':groupname', $groupname, PDO::PARAM_STR);
			$stmt->execute();
		}

		$pdo->commit();
	} catch (Exception $e) {
		$pdo->rollBack();
		ReportError($e);
		header('Location: '.BASEURL.'admin/index.php');
		exit();
	}

	header('Location: '.BASEURL.'admin/index.php');
?>


