<?php
// Load your necessary includes here if needed
require_once('includes/load.php');

// Check if a CSV file was uploaded
if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] === UPLOAD_ERR_OK) {
    $csvFile = $_FILES['csv_file']['tmp_name'];

    // Read the CSV file
    $handle = fopen($csvFile, 'r');
    if ($handle) {
        // Skip the header row
        fgetcsv($handle);

        // Import data from CSV
        while (($data = fgetcsv($handle)) !== false) {
            $id = $data[0];
            $partNumber = $data[1];
            $productName = $data[2];
            $categoryID = $data[3];
            $inStock = $data[4];
            $productAdded = $data[5];

            // Check if the product already exists in the database
            $checkQuery = "SELECT id FROM products WHERE id = '$id'";
            $existingProduct = $db->query($checkQuery);

            if ($db->num_rows($existingProduct) > 0) {
                // Product already exists, update it
                $updateQuery = "UPDATE products SET part_number = '$partNumber', name = '$productName', categorie_id = '$categoryID', quantity = '$inStock', date = '$productAdded' WHERE id = '$id'";
                $db->query($updateQuery);
            } else {
                // Product doesn't exist, insert it
                $insertQuery = "INSERT INTO products (id, part_number, name, categorie_id, quantity, date) VALUES ('$id', '$partNumber', '$productName', '$categoryID', '$inStock', '$productAdded')";
                $db->query($insertQuery);
            }
        }

        fclose($handle);
    }
}

// Redirect to product.php after import
header('Location: product.php');
exit();
?>
