<?php
/**
 * Plugin Name: Consumables Excel Importer
 * Description: Import Excel/CSV items into Consumables Tracker.
 * Version: 1.0
 * Author: Afif Azmi
 */

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

add_action('admin_menu', function(){
    add_submenu_page(
        'ct_items',
        'Import Items',
        'Import Items',
        'manage_options',
        'ct_import_items',
        'ct_import_items_page'
    );
});

function ct_import_items_page(){
?>

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

<form method="post" enctype="multipart/form-data">
<input type="file" name="import_file" accept=".csv" required>
<?php submit_button("Import File"); ?>
</form>

<?php

if(isset($_FILES['import_file'])){

global $wpdb;

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

$file = $_FILES['import_file']['tmp_name'];

$handle = fopen($file, "r");

$row = 0;
$imported = 0;

while(($data = fgetcsv($handle,1000,",")) !== FALSE){

$row++;

if($row == 1) continue; // skip header

$item_code = sanitize_text_field($data[0]);
$item_name = sanitize_text_field($data[1]);
$unit = sanitize_text_field($data[2]);
$balance = floatval($data[3]);

$exists = $wpdb->get_var(
$wpdb->prepare(
"SELECT id FROM $table WHERE item_code=%s",
$item_code
)
);

if(!$exists){

$wpdb->insert($table,[
'item_code'=>$item_code,
'item_name'=>$item_name,
'unit'=>$unit,
'balance'=>$balance,
'active'=>1
],['%s','%s','%s','%f','%d']);

$imported++;

}

}

fclose($handle);

echo "<div class='updated'><p>$imported items imported successfully.</p></div>";

}

?>

</div>

<?php
}