<?php
require_once('includes/load.php');
page_require_level(3); // Pastikan level pengguna sesuai dengan kebutuhan

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_FILES['csv_file']) && !empty($_FILES['csv_file']['name'])) {
        $file = $_FILES['csv_file']['tmp_name'];
        $handle = fopen($file, "r");

        // Skip the first line (header)
        fgetcsv($handle);

        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $noOrder = $db->escape($data[0]);
            $partNumber = $db->escape($data[1]);
            $quantity = $db->escape($data[2]);
            $output = $db->escape($data[3]);
            $deliveryDate = $db->escape($data[4]);

            // Insert data into production_schedule table
            $query = "INSERT INTO production_schedule (no_order, part_number, quantity_order, output, delivery_date) 
                      VALUES ('$noOrder', '$partNumber', '$quantity', '$output', '$deliveryDate')";
            $result = $db->query($query);

            if (!$result) {
                echo "Error importing data: " . $db->error;
                exit();
            }
        }

        fclose($handle);
        header("Location: production_schedule.php?import_success=1");
        exit();
    } else {
        echo "No CSV file uploaded.";
        exit();
    }
}
?>
