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

$deleteSuccess = false;

mysqli_begin_transaction($conn);

if (isset($_POST["esDelete"]) && isset($_POST["es_id"]) && !empty($_POST["es_id"]))
{
	try {
		$result = executeQuery($conn, "SELECT * FROM egg_standards WHERE id = ?", "s", [$_POST["es_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 egg_standards 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["bdDelete"]) && isset($_POST["bd_id"]) && !empty($_POST["bd_id"])) {
    try {
        $result = executeQuery($conn, "SELECT * FROM batch_details WHERE id = ?", "s", [$_POST["bd_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 batch_details SET Status = FALSE, 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"]);
}
?>