<?php
/**
 * Plugin Name: Consumables Item Deleter
 * Description: Delete items from Consumables Tracker.
 * Version: 1.0
 * Author: Afif Azmi
 */

if (!defined('ABSPATH')) exit;

/* Add submenu under Consumables */
add_action('admin_menu', function(){

    add_submenu_page(
        'ct_items',
        'Delete Items',
        'Delete Items',
        'manage_options',
        'ct_delete_items',
        'ct_delete_items_page'
    );

});

/* Page content */
function ct_delete_items_page(){

global $wpdb;

$table = $wpdb->prefix.'consumables_items';

/* Handle delete */
if(isset($_GET['delete_id'])){

    $id = intval($_GET['delete_id']);

    $wpdb->delete(
        $table,
        ['id'=>$id],
        ['%d']
    );

    echo "<div class='updated'><p>Item deleted successfully.</p></div>";

}

/* Get items */
$items = $wpdb->get_results("SELECT * FROM $table ORDER BY item_name ASC");

?>

<div class="wrap">
<h1>Delete Consumable Items</h1>

<table class="widefat fixed striped">
<thead>
<tr>
<th>Code</th>
<th>Name</th>
<th>Unit</th>
<th>Balance</th>
<th>Action</th>
</tr>
</thead>

<tbody>

<?php foreach($items as $item): ?>

<tr>
<td><?php echo esc_html($item->item_code); ?></td>
<td><?php echo esc_html($item->item_name); ?></td>
<td><?php echo esc_html($item->unit); ?></td>
<td><?php echo esc_html($item->balance); ?></td>

<td>

<a 
class="button button-danger"
href="?page=ct_delete_items&delete_id=<?php echo $item->id; ?>"
onclick="return confirm('Delete this item permanently?');"
>
Delete
</a>

</td>

</tr>

<?php endforeach; ?>

</tbody>
</table>

</div>

<?php
}