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

if (isset($_POST['submit'])) {
    $file = $_FILES['file']['tmp_name'];

    if ($_FILES['file']['size'] > 0) {
        $handle = fopen($file, "r");

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

        while (($data = fgetcsv($handle, 1000, ",")) !== false) {
            $id = $db->escape($data[0]);
            $name = $db->escape($data[1]);
            $quantity = $db->escape($data[2]);
            $buy_price = $db->escape($data[3]);
            $sale_price = $db->escape($data[4]);
            $categorie_id = $db->escape($data[5]);
            $media_id = $db->escape($data[6]);
            $date = $db->escape($data[7]);
            $part_number = $db->escape($data[8]);

            $sql = "INSERT INTO your_table_name (id, name, quantity, buy_price, sale_price, categorie_id, media_id, date, part_number) 
                    VALUES ('$id', '$name', '$quantity', '$buy_price', '$sale_price', '$categorie_id', '$media_id', '$date', '$part_number')";
            $result = $db->query($sql);
        }

        fclose($handle);
        $msg = "CSV data imported successfully!";
    } else {
        $msg = "File is empty!";
    }
}

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-12">
        <div class="panel panel-default">
            <div class="panel-heading clearfix">
                <div class="pull-left">
                    <h3>Import CSV Data</h3>
                </div>
            </div>
            <div class="panel-body">
                <form method="post" action="import_csv.php" enctype="multipart/form-data">
                    <div class="form-group">
                        <label for="file">Choose CSV File:</label>
                        <input type="file" name="file" accept=".csv">
                    </div>
                    <button type="submit" name="submit" class="btn btn-primary">Import</button>
                </form>
            </div>
        </div>
    </div>
</div>

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