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

if (isset($_GET['export']) && $_GET['export'] == 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="products.csv"');

    $output = fopen('php://output', 'w');
    fputcsv($output, array('ID', 'Name', 'Quantity', 'Buy Price', 'Sale Price', 'Category ID', 'Media ID', 'Date', 'Part Number'));

    $sql = "SELECT * FROM products";
    $products = $db->query($sql);

    while ($product = $db->fetch_assoc($products)) {
        fputcsv($output, array(
            $product['id'],
            $product['name'],
            $product['quantity'],
            $product['buy_price'],
            $product['sale_price'],
            $product['categorie_id'],
            $product['media_id'],
            $product['date'],
            $product['part_number']
        ));
    }

    fclose($output);
    exit();
}

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>Download CSV</h3>
                </div>
            </div>
            <div class="panel-body">
                <a href="export_csv.php?export=csv" class="btn btn-primary">Download CSV</a>
            </div>
        </div>
    </div>
</div>

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