You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
3.3 KiB
PHP

<?php
require_once 'includes/db.php';
require_once 'includes/auth.php';
checkAuth();
$message = '';
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES['csv_file'])) {
$file = $_FILES['csv_file']['tmp_name'];
if (($handle = fopen($file, "r")) !== FALSE) {
// Pomijamy pierwszy wiersz (nagłówki)
fgetcsv($handle, 1000, ";");
try {
$pdo->beginTransaction();
$sql = "INSERT INTO " . DB_PREFIX . "orders
(product_name, quantity, purchase_place, price_per_unit, delivery_date, notes, status)
VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $pdo->prepare($sql);
$count = 0;
while (($row = fgetcsv($handle, 1000, ";")) !== FALSE) {
// $row[0] to LP - pomijamy zgodnie z wymaganiem
// Obsługa polskich znaków (jeśli plik jest w Windows-1250)
foreach($row as $key => $value) {
$row[$key] = mb_convert_encoding($value, "UTF-8", "auto");
}
if (empty($row[1])) continue; // Pomiń jeśli brak nazwy produktu
$stmt->execute([
$row[1], // Produkt
(int)$row[2], // Ilość
$row[3], // Miejsce zakupu
(float)str_replace(',', '.', $row[4]), // Cena (zamiana przecinka na kropkę)
$row[5], // Data dostawy
$row[6], // Notatki
$row[7] ?? 'nowe' // Status
]);
$count++;
}
$pdo->commit();
$message = "<div class='alert alert-success'>Zaimportowano $count zamówień z pliku CSV!</div>";
} catch (Exception $e) {
$pdo->rollBack();
$message = "<div class='alert alert-danger'>Błąd: " . $e->getMessage() . "</div>";
}
fclose($handle);
}
}
?>
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<title>Import CSV - <?php echo APP_NAME; ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container py-5">
<div class="card shadow mx-auto" style="max-width: 600px;">
<div class="card-header bg-success text-white">
<h4 class="mb-0">Import z pliku CSV</h4>
</div>
<div class="card-body">
<?php echo $message; ?>
<div class="alert alert-warning small">
<strong>Ważne:</strong> W Excelu wybierz <em>Zapisz jako</em> -> <strong>CSV (rozdzielany średnikami)</strong>.
</div>
<form method="POST" enctype="multipart/form-data">
<div class="mb-3">
<label class="form-label">Wybierz plik .csv</label>
<input type="file" name="csv_file" class="form-control" accept=".csv" required>
</div>
<div class="d-flex justify-content-between">
<a href="index.php" class="btn btn-secondary">Powrót</a>
<button type="submit" class="btn btn-success">Importuj dane</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>