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

if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] == 0) {
    $csvFile = fopen($_FILES['csv_file']['tmp_name'], 'r');
    if ($csvFile) {
        // Skip the first row if it contains headers
        fgetcsv($csvFile, 0, ';');
        
        while (($row = fgetcsv($csvFile, 0, ';')) !== FALSE) {
            $no_order = $db->escape($row[0]);
            $client = $db->escape($row[1]);
            $part_number = $db->escape($row[2]);
            $quantity_order = $db->escape($row[3]);
            $delivery_date = $db->escape($row[4]);
            $input_date = isset($row[5]) ? $db->escape($row[5]) : null;

            $query = "INSERT INTO production_schedule (no_order, client, part_number, quantity_order, delivery_date, input_date) 
                      VALUES ('{$no_order}', '{$client}', '{$part_number}', '{$quantity_order}', '{$delivery_date}', '{$input_date}')";
            
            if (!$db->query($query)) {
                // Handle query error
                header('Location: schedule.php?import_error=1');
                exit;
            }
        }
        
        fclose($csvFile);
        header('Location: schedule.php?import_success=1');
    } else {
        // Handle file open error
        header('Location: schedule.php?import_error=1');
    }
} else {
    // Handle file upload error
    header('Location: schedule.php?import_error=1');
}
?>
