<?php
session_start();
if (!isset($_SESSION['username'])) {
    echo "<script>window.top.location.href='index.php';</script>"; // Redirect parent window to login page
    exit();
}

include 'connect.php';

if (isset($_POST['submit'])) {
    // Check if the file is uploaded
    if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] == 0) {
        // Get file information
        $fileTmpName = $_FILES['csv_file']['tmp_name'];
        $fileName = $_FILES['csv_file']['name'];
        $fileType = $_FILES['csv_file']['type'];

        // Open the CSV file
        if (($handle = fopen($fileTmpName, "r")) !== FALSE) {
            // Skip the header row if there is one
            fgetcsv($handle);

            // Prepare the SQL insert statement
            $stmt = $conn->prepare("INSERT INTO products_table (product_number, pr_Name, pr_Price, pr_Cost) VALUES (?, ?, ?, ?)");

            // Loop through the file and insert data
            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    $product_number = (string) $data[0];
                    $product_name = $data[1];
                    $price = floatval($data[2]);
                    $cost = floatval($data[3]);

                    $stmt->bind_param("ssdd", $product_number, $product_name, $price, $cost);
                    $stmt->execute();
                }

            fclose($handle);

            echo "Data imported successfully!";
        } else {
            echo "Error opening the file.";
        }
    } else {
        echo "No file uploaded or there was an error with the upload.";
    }
}

$conn->close();
?>

<!--<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Import CSV Data</title>
</head>
<body>
    <h2>Upload CSV File</h2>
    <form action="" method="post" enctype="multipart/form-data">
        <input type="file" name="csv_file" required>
        <button type="submit" name="submit">Upload and Import</button>
    </form>
</body>
</html> -->
