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

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

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

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

// Quantity 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 quantity SET status = $status WHERE id = $itemId";
    $updateResult = mysqli_query($conn, $updateQuery);
    
    if ($updateResult) {
        header('Location: add_quantity.php?success=Status Updated Successfully!!!');
        exit();
    } else {
        header('Location: add_quantity.php?error=Failed to Update Status!!!');
        exit();
    }
}
?>
