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

$deleteSuccess = false;

if (isset($_GET["p"])) {
    $page = $_GET["p"];
    if ($userType == 2 || isset($superUser)) {
        $dbTable = ($page === "ipep") ? "predata_ip" : 
                   (($page === "ipes") ? "predata_ew" : 
                   (($page === "ipfd") ? "predata_fd" : 
                   (($page === "iptemp") ? "predata_temp" : "table-error")));
    } elseif ($userType == 1 || $userType == 3) {
        $dbTable = ($page === "ipep") ? "input_production" : 
                   (($page === "ipes") ? "egg_weight" : 
                   (($page === "ipfd") ? "feed_delivery" : 
                   (($page === "iptemp") ? "input_temp" : "table-error")));
    } else {
        $dbTable = "table-error";
    }
} else {
    $dbTable = "table-error";
}

mysqli_begin_transaction($conn);

if (isset($_POST["ipDelete"]) && isset($_POST["ip_id"]) && !empty($_POST["ip_id"]))
{
	try
	{
		$result = executeQuery($conn, "SELECT * FROM {$dbTable} WHERE id=?", "s", [$_POST["ip_id"]]);
		
		if ($result === false) { 
			throw new Exception("Error executing query: " . $conn->error);
		} 
		
		if ($result->num_rows > 0)
		{
			$id = $result->fetch_assoc()["id"];

			// Flag the record as deleted
            $deleteResult = executeQuery($conn, "UPDATE {$dbTable} 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>
        $( ".dispMessage" ).append( "<div class='alert alert-danger d-flex align-items-center shadow' role='alert'><h4>Deleted Successfully!</h4></div>" );
    </script>
    <?php
    unset($_SESSION["deleteSuccess"]);
}
?>