<?php
// Set headers to force download file
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="mrp_data.csv"');
header('Pragma: no-cache');
header('Expires: 0');

// Open file handle for writing
$output = fopen('php://output', 'w');

// Write headers to CSV file
fputcsv($output, array(
    'Part Number',
    'Selected Product Name',
    'Child BOM',
    'Child Name',
    'Level',
    'Quantity',
    'Quantity Order',
    'Total Requirement',
    'UoM',
    'Total Requirement (KG)',
    'Oven Date'
));

// Loop through MRP data and write each row to CSV file
if (!empty($mrpData)) {
    foreach ($mrpData as $noOrder => $partNumbers) {
        foreach ($partNumbers as $partNumber => $data) {
            $bom_structure = get_bom_structure($partNumber);
            $selected_product_name = get_product_name_by_part_number($partNumber);
            $calculationDate = date('Y-m-d', strtotime($data['delivery_date'] . '-3 days'));

            foreach ($bom_structure as $bom_item) {
                fputcsv($output, array(
                    $partNumber,
                    $selected_product_name,
                    $bom_item['child_bom'],
                    $bom_item['child_name'],
                    $bom_item['level'],
                    $bom_item['qty'],
                    number_format($data['total_quantity_order'], 0, ',', '.'),
                    number_format($bom_item['qty'] * $data['total_quantity_order'], 0, ',', '.'),
                    $bom_item['uom'],
                    number_format(($bom_item['qty'] * $data['total_quantity_order']) / 1000, 1, '.', ''),
                    $calculationDate
                ));
            }
        }
    }
}

// Close file handle
fclose($output);
?>
