<?php
require_once('includes/load.php');
page_require_level(2);

if (isset($_FILES['importFile']) && $_FILES['importFile']['error'] == UPLOAD_ERR_OK && $_FILES['importFile']['size'] > 0) {
    $file = $_FILES['importFile']['tmp_name'];

    $handle = fopen($file, 'r');
    if ($handle !== false) {
        fgetcsv($handle); // Skip header line

        while (($data = fgetcsv($handle, 1000, ',')) !== false) {
            // Extract data from CSV
            $part_number = mysqli_real_escape_string($db->link, $data[0]);
            $product_name = mysqli_real_escape_string($db->link, $data[1]);
            $category_name = mysqli_real_escape_string($db->link, $data[2]);
            $quantity = mysqli_real_escape_string($db->link, $data[3]);
            $uom = mysqli_real_escape_string($db->link, $data[4]);
            $buy_price = mysqli_real_escape_string($db->link, $data[5]);
            $product_added = mysqli_real_escape_string($db->link, $data[6]);

            // Get category ID
            $category_id = get_category_id($category_name);
            if ($category_id === null) {
                $msg = "Error: Category '$category_name' not found.";
                $_SESSION['msg'] = $msg;
                redirect('product.php', false);
            }

            // Perform database insertion
            $sql = "INSERT INTO products (part_number, name, quantity, uom, buy_price, date, categorie_id) 
                    VALUES ('$part_number', '$product_name', '$quantity', '$uom', '$buy_price', '$product_added', '$category_id')";
            if ($db->query($sql)) {
                $msg = "Products imported successfully.";
                $_SESSION['msg'] = $msg;
            } else {
                $msg = "Error: " . $db->error;
                $_SESSION['msg'] = $msg;
            }
        }

        fclose($handle);
    } else {
        $msg = "Failed to open the CSV file.";
        $_SESSION['msg'] = $msg;
    }
} else {
    $msg = "Error uploading the file.";
    $_SESSION['msg'] = $msg;
}

redirect('product.php', false);
?>
