<?php
$page_title = 'Import List Order';
require_once('includes/load.php');
page_require_level(2);

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

    if ($handle !== false) {
        // Kosongkan tabel list_order sebelum mengimpor data baru
        $db->query("DELETE FROM list_order");

        while (($data = fgetcsv($handle, 1000, ";")) !== false) {  // Menggunakan titik koma sebagai karakter pemisah
            $order_number = $db->escape($data[0]);
            $model = $db->escape($data[1]);
            $quantity = (int) $data[2];
            $description = $db->escape($data[3]);
            $customer = $db->escape($data[4]);
            $address = $db->escape($data[5]);
            $order_date = $data[6];
            $delivery_date = $data[7];

            // Lakukan validasi data jika diperlukan

            // Lakukan query SQL INSERT untuk menyimpan data ke tabel list_order
            $sql = "INSERT INTO list_order (order_number, model, quantity, description, customer, address, order_date, delivery_date)
                    VALUES ('$order_number', '$model', $quantity, '$description', '$customer', '$address', '$order_date', '$delivery_date')";

            $db->query($sql);
        }

        fclose($handle);
        $session->msg("s", "Data berhasil diimpor.");
        redirect('list_order.php');
    } else {
        $session->msg("d", "Gagal membuka file CSV.");
        redirect('import_csv.php');
    }
}

include_once('layouts/header.php');
?>

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">Import List Order</h3>
            </div>
            <div class="panel-body">
                <form action="import_list_order.php" method="post" enctype="multipart/form-data">
                    <div class="form-group">
                        <label for="csv_file">Pilih File CSV:</label>
                        <input type="file" name="csv_file" id="csv_file" required>
                    </div>
                    <button type="submit" class="btn btn-primary">Import Data</button>
                </form>
            </div>
        </div>
    </div>
</div>

<?php include_once('layouts/footer.php'); ?>
