<?php
include("connection.php");

if (isset($_POST['submit'])) {
    $product_name = $_POST['product_name'];
    $salt = $_POST['salt'];
    $origin = $_POST['origin'];
    $quantity = $_POST['quantity'];
    $price = $_POST['price'];
    $currentDateTime = date('Y-m-d H:i:s');

    // Check if the product already exists
    $checkDuplicate = "SELECT * FROM product WHERE product_name = '$product_name' AND salt = '$salt' AND origin = '$origin' AND quantity = '$quantity' AND price = '$price'";
    $resultDuplicate = mysqli_query($conn, $checkDuplicate);

    if (mysqli_num_rows($resultDuplicate) > 0) {
        // Product already exists, show a SweetAlert error message
        header("Location: add_product.php?error=Product Already Exists!");
        exit();
    } else {
        // Product does not exist, proceed with insertion
        $sql = "INSERT INTO product (product_name, salt, origin, quantity, price, date_time) VALUES ('$product_name', '$salt', '$origin', '$quantity', '$price', '$currentDateTime')";
        $result = mysqli_query($conn, $sql);

        if ($result) {
            // Product added successfully, show a SweetAlert success message
            header("Location: add_product.php?success=Product Added Successfully!!!");
            exit();
        } else {
            // Failed insertion, show a SweetAlert error message
            header("Location: add_product.php?error=Failed insertion!!!");
            exit();
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $itemId = $_POST['item_id'];

    if (isset($_POST['activate'])) {
        $status = 1;
    } elseif (isset($_POST['block'])) {
        $status = 0;
    }

    $updateQuery = "UPDATE product SET status = $status WHERE id = $itemId";
    mysqli_query($conn, $updateQuery);

    // Redirect back to the view table page
    header('Location: add_product.php?success=Product Status Updated Successfully!!!');
    exit();
}
?>