<?php
// Load your necessary includes here if needed
require_once('includes/load.php');

// Set headers for CSV file download
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="products.csv"');

// Create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// Define the delimiter and enclosure for CSV
$delimiter = ',';
$enclosure = '"';

// Write CSV header row
fputcsv($output, array('ID', 'Part Number', 'Product Name', 'Category ID', 'In-Stock', 'Product Added'), $delimiter, $enclosure);

// Replace this with your actual query to retrieve products data
$sql = "SELECT id, part_number, name, categorie_id, date FROM products";
$products = $db->query($sql);

// Loop through products and write to CSV
while ($product = $db->fetch_assoc($products)) {
    $row = array(
        $product['id'],
        $product['part_number'],
        $product['name'],
        $product['categorie_id'],
        get_product_stock($product['id']), // Use the function to get stock
        $product['date'] // Assuming 'date' is a valid column in your database
    );
    fputcsv($output, $row, $delimiter, $enclosure);
}

// Close the file pointer
fclose($output);
exit();
?>
