<?php
require('config.php');

// Set headers to force download
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=batch_entries.csv');

// Open output stream
$output = fopen('php://output', 'w');

// Write CSV column headers
fputcsv($output, ['ID', 'Stock ID', 'Initial Quantity', 'Quantity', 'Batch No', 'Added By', 'Date Added']);

// Fetch batch entries from database
$query = "SELECT id, stockID, initialQTY, quantity, batchNo, addedBy, DATE_FORMAT(dateAdded, '%Y-%m-%d') as formatted_date FROM batch_entries ORDER BY id DESC";
$result = $connect->query($query);

if ($result) {
    while ($row = $result->fetch_assoc()) {
        // Replace original date with formatted date
        $row['dateAdded'] = $row['formatted_date'];
        unset($row['formatted_date']);

        fputcsv($output, $row);
    }
} else {
    fputcsv($output, ['Error retrieving data']);
}

// Close output stream
fclose($output);
?>
