<?php
require_once('includes/load.php');
page_require_level(3); // Memastikan level akses sesuai

if (isset($_POST['import_csv'])) {
    $file_name = $_FILES['csv_file']['tmp_name'];

    if ($_FILES['csv_file']['size'] > 0) {
        $file = fopen($file_name, 'r');
        $row_num = 0; // Inisialisasi nomor baris untuk pesan error

        while (($row = fgetcsv($file, 1000, ";")) !== FALSE) {
            // Escape dan ambil nilai dari setiap kolom
            $part_number  = $db->escape($row[0]);
            $time_filling = $db->escape($row[1]);
            $time_label   = $db->escape($row[2]);
            $time_seal    = $db->escape($row[3]);
            $time_packing = $db->escape($row[4]);
            $time_shrink  = $db->escape($row[5]);
            $description  = $db->escape($row[6]);

            // Query untuk insert data ke tabel std_time
            $sql = "INSERT INTO std_time (part_number, time_filling, time_label, time_seal, time_packing, time_shrink, description) ";
            $sql .= "VALUES ('{$part_number}', '{$time_filling}', '{$time_label}', '{$time_seal}', '{$time_packing}', '{$time_shrink}', '{$description}')";

            // Eksekusi query
            $result = $db->query($sql);

            // Periksa apakah insert berhasil
            if (!$result) {
                $session->msg('d', 'Gagal mengimpor data pada baris ' . ($row_num + 1));
                fclose($file);
                redirect('import_std_time.php', false);
            }

            $row_num++;
        }

        fclose($file);
        $session->msg('s', 'Data berhasil diimpor.');
        redirect('import_std_time.php', false);
    } else {
        $session->msg('d', 'Tidak ada file yang dipilih.');
        redirect('import_std_time.php', false);
    }
}
?>

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

<div class="row">
    <div class="col-md-12">
        <?php echo display_msg($msg); ?>
    </div>
</div>

<div class="row">
    <div class="col-md-9">
        <div class="panel panel-default">
            <div class="panel-heading">
                <strong>
                    <span class="glyphicon glyphicon-upload"></span>
                    <span>Impor Data Std Time</span>
                </strong>
            </div>
            <div class="panel-body">
                <form method="post" action="import_std_time.php" enctype="multipart/form-data" class="clearfix">
                    <div class="form-group">
                        <label for="csv_file" class="control-label">Pilih File CSV</label>
                        <input type="file" class="form-control" name="csv_file" accept=".csv" required>
                    </div>
                    <div class="form-group clearfix">
                        <button type="submit" name="import_csv" class="btn btn-primary">Impor</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

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