<?php

include '../includes/auth.php'; 
include '../includes/db.php'; 

if(isset($_POST['import'])){
    if($_FILES['csv']['error'] === UPLOAD_ERR_OK){
        $filename = $_FILES['csv']['tmp_name'];
        $handle = fopen($filename, "r");

        // Skip header row
        fgetcsv($handle);

        while(($data = fgetcsv($handle, 1000, ",")) !== FALSE){
            [$code, $test_name, $description, $tube_container, $volume, $reporting_time, $price, $preparation] = $data;

            $stmt = $conn->prepare("INSERT INTO services (code, test_name, description, tube_container, volume, reporting_time, price, preparation)
                                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("ssssssss", $code, $test_name, $description, $tube_container, $volume, $reporting_time, $price, $preparation);
            $stmt->execute();
        }

        fclose($handle);
        echo "<p style='color:green;'>✅ Data imported successfully!</p>";
    } else {
        echo "<p style='color:red;'>⚠️ Upload error!</p>";
    }
}
?>

<form method="post" enctype="multipart/form-data">
    <h2>Import Services CSV</h2>
    <input type="file" name="csv" accept=".csv" required>
    <button type="submit" name="import">Import</button>
</form>
