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

// Salt add form submission handling
if (isset($_POST['add'])) {
    $salt_name = $_POST['salt_name'];
    $currentDateTime = date('Y-m-d H:i:s');
    
    // Check if salt_name already exists in the database
    $check_sql = "SELECT * FROM salt WHERE salt_name = '$salt_name'";
    $check_result = mysqli_query($conn, $check_sql);
    
    if (mysqli_num_rows($check_result) > 0) {
        header("Location: add_salt.php?error=Salt Name Already Exists!!!");
        exit();
    }

    // Insert new salt into the database
    $insert_sql = "INSERT INTO salt (salt_name, date_time) VALUES ('$salt_name', '$currentDateTime')";
    $insert_result = mysqli_query($conn, $insert_sql);

    if ($insert_result) {
        header("Location: add_salt.php?success=Salt Added Successfully!!!");
        exit();
    } else {
        header("Location: add_salt.php?error=Failed insertion!!!");
        exit();
    }
}

// Salt status update form submission handling
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $itemId = $_POST['item_id'];
    
    if (isset($_POST['activate'])) {
        $status = 1;
    } elseif (isset($_POST['block'])) {
        $status = 0;
    }
    
    $updateQuery = "UPDATE salt SET status = $status WHERE id = $itemId";
    $updateResult = mysqli_query($conn, $updateQuery);
    
    if ($updateResult) {
        header('Location: add_salt.php?success=Status Updated Successfully!!!');
        exit();
    } else {
        header('Location: add_salt.php?error=Failed to Update Status!!!');
        exit();
    }
}
?>
