In the pasted code is my "Category" menu code. (1) Fix: When i update a category name and successfully adit it, it doesnt disappear from the form. After succesful edit/updtae that category name must disappear from the form (2) Fix: the time that is being show in both "Date Created" and Date Updated is wrong. Date Created: time when i create that category Date Updtaed time when i updtae that category and when im not yet updtaing thatctegory it should show "Never". What is happening right now is that when im updating a category, the time in "Date Crated " is the same in time in Date Updtaed. It must be when im updating, the time in Date Created must not chnage the time i created that, and the only will change is the time in Date Updtaed. Here is the code: <?php
session_start();
global $wpdb;
$table_name = 'categories'; // Adjust if you use prefixes: $wpdb->prefix . 'categories';
$inventory_history_table_name = 'inventory_history';
$message = ''; // For success/error messages
$message_type = ''; // 'success' or 'error'
$editing_category = null; // Initialize editing category variable
function log_category_action($action_type, $category_name, $description) {
global $wpdb;
$history_table_name = 'inventory_history'; // Change according to your table name
$username = isset($_SESSION['username']) ? $_SESSION['username'] : '';
// Get current user
$result = $wpdb->insert(
$history_table_name,
array(
'username' => $username,
'action_type' => $action_type,
'item_type' => 'category',
'item_name' => $category_name,
'description' => $description,
'timestamp' => current_time('mysql') // Current time
),
array('%s', '%s', '%s', '%s', '%s', '%s')
);
return $result !== false; // Return true if inserted successfully
}
// --- Handle Add/Edit Category Form Submission ---
if (isset($_POST['save_category']) && isset($_POST['_wpnonce_category_form']) && wp_verify_nonce($_POST['_wpnonce_category_form'], 'save_category_action')) {
$category_name = isset($_POST['category_name']) ? sanitize_text_field($_POST['category_name']) : '';
$edit_category_id = isset($_POST['edit_category_id']) ? absint($_POST['edit_category_id']) : 0;
if (!empty($category_name)) {
// Check if category already exists (excluding current edited category)
$existing_check = $wpdb->prepare(
"SELECT id FROM $table_name WHERE LOWER(name) = LOWER(%s) AND id != %d",
$category_name,
$edit_category_id
);
$existing_category = $wpdb->get_var($existing_check);
if ($existing_category) {
$message = 'Error: Category "' . esc_html($category_name) . '" already exists.';
$message_type = 'error';
} else {
if ($edit_category_id) {
// Fetch the original name before updating
$original_category_name = $wpdb->get_var($wpdb->prepare(
"SELECT name FROM $table_name WHERE id = %d",
$edit_category_id
));
// UPDATE existing category
$updated = $wpdb->update(
$table_name,
[
'name' => $category_name,
'updated_at' => current_time('mysql') // Add current timestamp
],
['id' => $edit_category_id],
['%s', '%s'],
['%d']
);
if ($updated !== false) {
$message = 'Category updated successfully!';
$message_type = 'success';
$editing_category = null; // Reset editing state
$_POST['category_name'] = '';
// Log the action with the original category name in description
log_category_action('update', $original_category_name, "Category '{$original_category_name}' updated to '{$category_name}'.");
} else {
$message = 'Error updating category. ' . $wpdb->last_error;
$message_type = 'error';
}
} else {
// INSERT new category
$inserted = $wpdb->insert(
$table_name,
['name' => $category_name, 'created_at' => current_time('mysql')],
['%s', '%s']
);
if ($inserted) {
$message = 'Category added successfully!';
$message_type = 'success';
log_category_action('add', $category_name, "Category '{$category_name}' was added.");
} else {
$message = 'Error adding category. ' . $wpdb->last_error;
$message_type = 'error';
}
}
}
} else {
$message = 'Category name cannot be empty.';
$message_type = 'error';
}
}
// --- Handle Edit Category Action (Prepare form) ---
if (isset($_GET['action']) && $_GET['action'] === 'edit_category' && isset($_GET['id']) && isset($_GET['_wpnonce']) && wp_verify_nonce($_GET['_wpnonce'], 'edit_category_' . absint($_GET['id']))) {
$category_id_to_edit = absint($_GET['id']);
if ($category_id_to_edit) {
$editing_category = $wpdb->get_row(
$wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $category_id_to_edit),
ARRAY_A
);
if (!$editing_category) {
$message = 'Category not found for editing.';
$message_type = 'error';
}
}
}
// --- Handle Cancel Edit Action ---
if (isset($_GET['action']) && $_GET['action'] === 'cancel_edit') {
$editing_category = null;
wp_redirect(remove_query_arg(array('action', 'id', '_wpnonce')));
exit;
}
// --- Handle Delete Category Action ---
if (isset($_GET['action']) && $_GET['action'] === 'delete_category' && isset($_GET['id']) && isset($_GET['_wpnonce']) && wp_verify_nonce($_GET['_wpnonce'], 'delete_category_' . absint($_GET['id']))) {
$category_id_to_delete = absint($_GET['id']);
if ($category_id_to_delete) {
// First get the category details before deleting
$category_to_delete = $wpdb->get_row(
$wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $category_id_to_delete),
ARRAY_A
);
if ($category_to_delete) {
// Log the action before deleting
log_category_action('delete', $category_to_delete['name'], "Category '{$category_to_delete['name']}' was deleted.");
$deleted = $wpdb->delete(
$table_name,
['id' => $category_id_to_delete],
['%d']
);
if ($deleted) {
$message = 'Category deleted successfully!';
$message_type = 'success';
wp_redirect(remove_query_arg(array('action', 'id', '_wpnonce')));
exit;
} else {
$message = 'Error deleting category.';
$message_type = 'error';
}
} else {
$message = 'Category not found.';
$message_type = 'error';
}
}
}
// --- Fetch Categories ---
$categories = [];
if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)) == $table_name) {
$categories = $wpdb->get_results("SELECT * FROM {$table_name} ORDER BY name ASC", ARRAY_A);
} else {
$message = "Error: Categories table '{$table_name}' not found.";
$message_type = 'error';
}
$search_term = '';
if (isset($_POST['search_term'])) {
$search_term = sanitize_text_field($_POST['search_term']);
$categories = $wpdb->get_results(
$wpdb->prepare("SELECT * FROM {$table_name} WHERE name LIKE %s ORDER BY name ASC", '%' . $wpdb->esc_like($search_term) . '%'),
ARRAY_A
);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Categories Management</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f7f9;
color: #333;
font-size: 16px;
}
.dashboard-container {
display: flex;
}
.sidebar {
width: 240px;
background-color: #D1B48C;
color: #000000;
height: 100vh;
position: fixed;
left: 0;
top: 0;
overflow-y: auto;
box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
z-index: 1000;
}
.sidebar-header {
padding: 20px;
text-align: center;
}
.sidebar-header .inventory-name {
font-size: 17px;
font-weight: bold;
color: #000;
}
.sidebar-menu {
padding: 0;
}
.sidebar-menu ul {
list-style: none;
margin: 0;
padding: 0;
}
.sidebar-menu li a {
display: flex;
align-items: center;
padding: 12px 20px;
text-decoration: none;
color: #000;
transition: 0.3s;
font-size: 16px;
}
.sidebar-menu li a i {
margin-right: 12px;
width: 20px;
text-align: center;
}
.sidebar-menu li a:hover {
background-color: #ffffff;
color: #000;
}
.header {
position: fixed;
top: 0;
left: 240px;
right: 0;
display: flex;
justify-content: space-between;
align-items: center;
background-color: #77693A;
padding: 10px 30px;
height: 60px; /* Fixed height */
z-index: 999;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.header-left .date-time {
font-size: 15px; /* Slightly smaller */
color: #fff; /* Darker color */
font-weight: 500; /* Slightly bolder */
}
.header-right {
display: flex;
align-items: center;
/* Removed gap here, gap is now on .user-info */
font-size: 16px; /* Slightly smaller */
color: #ffffff;
}
.header-right .user-info {
display: flex;
align-items: center; /* Center items horizontally */
gap: 1px; /* Small gap between icon and text */
}
.user-dropdown {
position: relative;
display: inline-block;
cursor: pointer;
}
.user-dropdown-content {
display: none;
position: absolute;
right: 0;
background-color: #D1B48C;
min-width: 100px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
border-radius: 4px;
}
.user-dropdown-header {
padding: 8px 12px;
background-color: ; #D1B48C
border-bottom: 1px solid #e9ecef;
display: flex;
align-items: center;
gap: 8px;
}
.user-dropdown-header i {
font-size: 20px;
color: #000000;
}
.user-dropdown-content.user-info {
display: flex;
align-items: right;
gap: 1px;
color: #000000;
}
.user-dropdown-content a {
display: flex;
padding: 8px 15px;
align-items: center;
color: #000000;
text-decoration: none;
font-size: 16px;
transition: all 0.2s;
}
.user-dropdown-content a i {
font-size: 16px; /* Adjust logout icon size separately */
margin-right: 8px; /* Space between icon and text */
}
.user-dropdown-content a:hover {
text-decoration: underline;
color: #000000;
}
.user-dropdown:hover .user-dropdown-content {
display: block;
}
.user-dropdown-content.user-info i {
font-size: 16px;
align-items: center;
}
.header-right i {
color: #ffffff; /* Icon color */
font-size:40px; /* Larger icon */
/* Remove margin-right when stacked */
}
.header-right span {
font-size: 15px; /* Smaller font for username */
color: #ffffff;
}
.main-content {
margin-left: 240px;
padding: 80px 20px 20px 20px;
flex-grow: 1;
}
.notice-wrap { margin-bottom: 15px; }
.notice { padding: 12px 18px; border-radius: 4px; border-left: 4px solid; font-size: 1.05em; }
.notice-error { background-color: #f8d7da; border-color: #dc3545; color: #721c24; }
.notice-success { background-color: #d4edda; border-color: #28a745; color: #155724; }
.category-content { display: flex; flex-wrap: wrap; gap: 25px; }
.category-form-container { flex: 1 1 400px; max-width: 500px; background-color: #fff; padding: 25px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); border: 1px solid #eee; box-sizing: border-box; height: fit-content; }
.category-form-container h2 { margin-top: 0; margin-bottom: 20px; color: #2f4050; border-bottom: 1px solid #eee; padding-bottom: 12px; font-size: 20px; }
.category-form-container form { display: flex; flex-direction: column; }
.category-form-container input[type="text"], .category-form-container input[type="number"], .category-form-container input[type="file"], .category-form-container select { padding: 10px 12px; margin-bottom: 18px; border: 1px solid #ddd; border-radius: 4px; font-size: 1em; width: 100%; box-sizing: border-box; font-family: inherit; }
.category-form-container button[type="submit"] { padding: 12px 18px; color: #000000; border: none; border-radius: 4px; cursor: pointer; font-size: 1.05em; transition: background-color 0.3s ease; display: inline-block; text-align: center; background-color: #D1B48C; margin-right: 10px; }
.category-form-container button[type="submit"]:hover { background-color: #be9b7b; }
.category-form-container .button-cancel {padding: 12px 18px;color: #000000;border: none;border-radius: 4px;cursor: pointer;font-size: 1.05em; transition: background-color 0.3s ease;display: inline-block;text-align: center;background-color: #D1B48C;text-decoration: none;margin-right: 10px;}
.category-form-container .button-cancel:hover { background-color: #be9b7b;}
.category-list-container { flex: 2 1 600px; background-color: #fff; padding: 25px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); border: 1px solid #eee; box-sizing: border-box; height: fit-content; }
.category-list-container h2 { margin-top: 0; margin-bottom: 20px; color: #2f4050; border-bottom: 1px solid #eee; padding-bottom: 12px; font-size: 20px; }
.category-list-container table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
.category-list-container th, #category-list-container td { padding: 10px 12px; text-align: left; border-bottom: 1px solid #eee; }
.category-list-container th { background-color: #f9f9f9; font-weight: bold; color: #555; }
.category-list-container tbody tr:hover { background-color: #f5f5f5; }
.category-actions a, .category-actions button { text-decoration: none; padding: 5px 10px; border-radius: 4px; color: #000000; font-size: 15px; white-space: nowrap; border: none; cursor: pointer; }
.category-list-container input[name="search_term"] {
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 1em;
width: 70%;
}
.category-list-container button[type="submit"] {
padding: 10px 20px;
background-color: #D1B48C;
color: #000;
border: none;
border-radius: 4px;
font-size: 1em;
cursor: pointer;
transition: background-color 0.3s ease;
}
.category-list-container button[type="submit"]:hover {
background-color: #be9b7b;
}
</style>
</head>
<body>
<div class="dashboard-container">
<aside class="sidebar">
<div class="sidebar-header">
<div class="inventory-name">ArKi Inventory</div>
</div>
<div class="sidebar-menu">
<ul>
<li><a href="http://localhost/inventory/index.php/admin-page/"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li>
<?php
$current_username = isset($_SESSION['username']) ? $_SESSION['username'] : '';
if ($current_username === 'admin'):
?>
<li><a href="http://localhost/inventory/index.php/usersmanagement/"><i class="fas fa-users-cog"></i> User Management</a></li>
<li class="active"><a href="http://localhost/inventory/index.php/category-page/"><i class="fas fa-list"></i> Categories</a></li>
<li><a href="http://localhost/inventory/index.php/products/"><i class="fas fa-boxes"></i> Products</a></li>
<li><a href="http://localhost/inventory/index.php/order/"><i class="fas fa-shopping-cart"></i> Orders</a></li>
<li><a href="http://localhost/inventory/index.php/view-order/"><i class="fas fa-eye"></i> View Orders</a></li>
<li><a href="http://localhost/inventory/index.php/sales/"><i class="fas fa-chart-line"></i> Sales & Report</a></li>
<li><a href="http://localhost/inventory/index.php/report/"><i class="fas fa-file-alt"></i> Inventory Report</a></li>
<li><a href="http://localhost/inventory/index.php/history/"><i class="fas fa-history"></i> Inventory History</a></li>
<?php else : ?>
<li class="active"><a href="http://localhost/inventory/index.php/category-page/"><i class="fas fa-list"></i> Categories</a></li>
<li><a href="http://localhost/inventory/index.php/products/"><i class="fas fa-boxes"></i> Products</a></li>
<li><a href="http://localhost/inventory/index.php/order/"><i class="fas fa-shopping-cart"></i> Orders</a></li>
<?php endif; ?>
</ul>
</div>
</aside>
<main class="main-content">
<header class="header">
<div class="header-left">
<span class="date-time" id="current-date-time"></span>
</div>
<div class="header-right">
<!-- Updated user info with dropdown -->
<div class="user-dropdown">
<div class="user-info">
<span id="current-username-header">
<?php echo esc_html($current_username); ?>
<i class="fas fa-user-circle"></i>
</span>
</div>
<div class="user-dropdown-content">
<div class="user-dropdown-header">
<i class="fas fa-user-circle"style="color:#000000;"></i>
<span style="color:#000000;"><?php echo esc_html($current_username); ?></span>
</div>
<a href="http://localhost/inventory/index.php/sign-in2/" onclick="return confirm('Are you sure you want to log out?');">
<i class="fas fa-sign-out-alt" style="font-size: 16px; color:#000000;"></i>Logout
</a>
</div>
</div>
</div>
</header>
<h1>Categories Management</h1>
<hr/>
<?php if (!empty($message)): ?>
<div class="notice-wrap">
<div class="notice notice-<?php echo $message_type; ?>">
<p><?php echo esc_html($message); ?></p>
</div>
</div>
<?php endif; ?>
<div class="category-content">
<div class="category-form-container">
<h2><?php echo $editing_category ? 'Edit Category' : 'Add New Category'; ?></h2>
<form method="post" action="">
<?php wp_nonce_field('save_category_action', '_wpnonce_category_form'); ?>
<input type="hidden" name="edit_category_id" value="<?php echo esc_attr($editing_category['id'] ?? ''); ?>">
<label for="category_name">Category Name:</label>
<input type="text" id="category_name" name="category_name"
value="<?php echo esc_attr($editing_category['name'] ?? ''); ?>"
required placeholder="Enter category name">
<button type="submit" name="save_category">
<?php echo $editing_category ? 'Update Category' : 'Add Category'; ?>
</button>
<?php if ($editing_category): ?>
<a href="<?php echo esc_url(add_query_arg(['action' => 'cancel_edit'])); ?>" class="button-cancel">Cancel</a>
<?php endif; ?>
</form>
</div>
<div class="category-list-container">
<h2>Existing Categories</h2>
<form method="post" action="">
<input type="text" name="search_term" value="<?php echo esc_attr($search_term); ?>" placeholder="Search Categories..." />
<button type="submit">Search</button>
</form>
<?php if (empty($categories)): ?>
<p>No categories found.</p>
<?php else: ?>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Date Created</th>
<th>Date Updated</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($categories as $category): ?>
<tr data-category-id="<?php echo esc_attr($category['id']); ?>">
<td><?php echo esc_html($category['id']); ?></td>
<td>
<span class="category-name-display">
<span class="category-name"><?php echo esc_html($category['name']); ?></span>
</span>
<span class="category-name-edit" style="display: none;">
<input type="text" class="edit-category-input" value="<?php echo esc_attr($category['name']); ?>">
</span>
</td>
<td><?php echo esc_html(date('Y-m-d H:i A', strtotime($category['created_at']))); ?></td>
<td><?php echo esc_html(date('Y-m-d H:i A', strtotime($category['created_at']))); ?></td>
<td class="category-actions">
<a href="<?php echo esc_url(add_query_arg([
'action' => 'edit_category',
'id' => $category['id'],
'_wpnonce' => wp_create_nonce('edit_category_' . $category['id'])
])); ?>" class="edit"><i class="fas fa-edit"></i>Edit</a>
<a href="<?php echo esc_url(add_query_arg([
'action' => 'delete_category',
'id' => $category['id'],
'_wpnonce' => wp_create_nonce('delete_category_' . $category['id'])
])); ?>" class="delete" onclick="return confirm('Are you sure you want to delete this category?');"><i class="fas fa-trash-alt"></i>Delete</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
</div>
</main>
</div>
<script>
function updateDateTime() {
const now = new Date();
const options = {
weekday: 'short', year: 'numeric', month: 'short',
day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit'
};
document.getElementById("current-date-time").textContent = now.toLocaleDateString('en-US', options);
}
setInterval(updateDateTime, 1000);
updateDateTime();
</script>
</body>
</html>