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

mysqli_begin_transaction($conn);

if (isset($_POST["AddNew_CN"])) 
{
    try
    {
        $keys = [
            "customer_name",
        ];
        $data = getDataFromPost($keys, $_POST);
		
        $checkQuery = "SELECT * FROM customer_names WHERE customer_name = ?";
        $checkResult = executeQuery($conn, $checkQuery, "s", [$data["customer_name"]]);

		if ($checkResult === false) { 
			throw new Exception("Error executing query: " . $conn->error);
		} 

		if ($checkResult->num_rows > 0) { 
            ?>
			<script>
				alert( "This Customer Name already exists in our system." );
			</script>
			<?php
			exit();
        }

        $result = executeQuery($conn, "INSERT INTO customer_names (addedby_user,customer_name) VALUES (?,?)", "ss", [$userName, $data["customer_name"]]);
        
		if ($result === false) { 
			throw new Exception("Error executing query: " . $conn->error);
		} 
    
        mysqli_commit($conn);
		
		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();
    }
}
?>