<?php
require_once("dbconn.php");
require_once("phpFunctions.php");

$deleteSuccess = false;

mysqli_begin_transaction($conn);

if (isset($_POST["Delete_DR"]) && isset($_POST["drsi_id"]) && !empty($_POST["drsi_id"]))
{
	try
	{
		$result = executeQuery($conn, "SELECT * FROM transactions WHERE id = ?", "s", [$_POST["drsi_id"]]);
		
		if ($result === false) { 
			throw new Exception("Error executing query: " . $conn->error);
		} 
		
		if ($result->num_rows > 0)
		{
			$id = $result->fetch_assoc()["id"];
            $deleteResult = executeQuery($conn, "UPDATE transactions SET is_deleted = TRUE WHERE id = ?", "s", [$id]);
			
			if ($deleteResult === false) { 
				throw new Exception("Error executing query: " . $conn->error);
			} else {
				$deleteSuccess = true;
			}

			mysqli_commit($conn);
			
			if ($deleteSuccess) 
			{
				$_SESSION["deleteSuccess"] = true;
				
				header("Location: " . $_SERVER["REQUEST_URI"]);
				exit();
			}
		}
	}
	catch (Exception $e) 
    {
        mysqli_rollback($conn);
		// Log the error message
        error_log($e->getMessage());
		// Redirect to an error page or display an error message
        //header("Location: error_page.php");
        //exit();
    }
}

if (isset($_POST["Delete_PL"]) && isset($_POST["pl_id"]) && !empty($_POST["pl_id"]))
{
	try
	{
		$result = executeQuery($conn, "SELECT * FROM pricelist WHERE id = ?", "s", [$_POST["pl_id"]]);
		
		if ($result === false) { 
			throw new Exception("Error executing query: " . $conn->error);
		} 
		
		if ($result->num_rows > 0)
		{
			$id = $result->fetch_assoc()["id"];
            $deleteResult = executeQuery($conn, "UPDATE pricelist SET is_deleted = TRUE WHERE id = ?", "s", [$id]);
			
			if ($deleteResult === false) { 
				throw new Exception("Error executing query: " . $conn->error);
			} else {
				$deleteSuccess = true;
			}

			mysqli_commit($conn);
			
			if ($deleteSuccess) 
			{
				$_SESSION["deleteSuccess"] = true;
				
				header("Location: " . $_SERVER["REQUEST_URI"]);
				exit();
			}
		}
	}
	catch (Exception $e) 
    {
        mysqli_rollback($conn);
		// Log the error message
        error_log($e->getMessage());
		// Redirect to an error page or display an error message
        //header("Location: error_page.php");
        //exit();
    }
}

if (isset($_SESSION["deleteSuccess"])) 
{
    ?>
    <script>
        alert( "Deleted Successfully!" );
    </script>
    <?php
    unset($_SESSION["deleteSuccess"]);
}
?>