<?php
require_once 'includes/auth.php';
require_role(['admin']); // bulk-insert into the catalog — admin only

require_once 'db.php';

// Path to your CSV or Excel import
$csvFile = 'items.csv';

if (!file_exists($csvFile)) {
    die("<div style='font-family:sans-serif; padding:20px; background:#f8d7da; color:#721c24; border-radius:5px;'>
            <strong>File not found!</strong><br>
            Place <code>items.csv</code> in this folder to run the import.
         </div>");
}

$handle = fopen($csvFile, "r");
$header = fgetcsv($handle, 1000, ","); // Skip header row

$stmt = $pdo->prepare("INSERT INTO tbl_master_items (item_name, description_template, reference_standards, inspection_procedure, certificate_period_months, category, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)");

$count = 0;
$pdo->beginTransaction();
$currentUserId = current_user()['id'] ?? null;

while (($data = fgetcsv($handle, 4000, ",")) !== FALSE) {
    $itemName   = trim($data[0] ?? '');
    $desc       = trim($data[1] ?? '');
    $standards  = trim($data[2] ?? '');
    $procedure  = trim($data[3] ?? '');
    $period     = floatval($data[4] ?? 6);
    $category   = trim($data[6] ?? 'LLG');

    if (!empty($itemName)) {
        $stmt->execute([$itemName, $desc, $standards, $procedure, (int)$period, $category, $currentUserId]);
        $count++;
    }
}

$pdo->commit();
fclose($handle);

echo "<div style='font-family:sans-serif; padding:20px; background:#d4edda; color:#155724; border-radius:5px;'>
        <h3>Import Complete!</h3>
        <p>Successfully inserted <strong>{$count}</strong> items into <code>tbl_master_items</code>.</p>
        <a href='master_items.php' style='text-decoration:none; background:#28a745; color:white; padding:10px 15px; border-radius:4px; font-weight:bold;'>Go to Master Bank Management</a>
      </div>";
