<?php
include 'db.php';
include 'auth.php';
require_right('Item List');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['import_file'])) {
    $file = $_FILES['import_file']['tmp_name'];
    if (($handle = fopen($file, 'r')) !== false) {
        $header = fgetcsv($handle); // Skip header row

        while (($data = fgetcsv($handle, 1000, ",")) !== false) {
            if (count($data) < 16) continue; // Skip incomplete rows

            [$item_code, $sku_number, $name, $category_id, $sub_category_id, $retail_price, $cost_price,
             $reorder_quantity, $reorder_level, $tax_type, $tax_rate_id, $item_type, $bulk_qty,
             $bulk_price, $pkg_qty, $uom_id] = $data;

            $stmt = $conn->prepare("INSERT INTO items (item_code, sku_number, name, category_id, sub_category_id,
                retail_price, cost_price, reorder_quantity, reorder_level, tax_type, tax_rate_id, item_type,
                bulk_qty, bulk_price, pkg_qty, uom_id)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

            $stmt->bind_param("sssiiiddiisidddi",
                $item_code, $sku_number, $name, $category_id, $sub_category_id, $retail_price,
                $cost_price, $reorder_quantity, $reorder_level, $tax_type, $tax_rate_id,
                $item_type, $bulk_qty, $bulk_price, $pkg_qty, $uom_id
            );

            $stmt->execute();
        }

        fclose($handle);
        header("Location: item_list.php?imported=1");
        exit;
    } else {
        header("Location: item_list.php?import_error=1");
        exit;
    }
}
header("Location: item_list.php");
exit;
