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

if (isset($_GET['product'])) {
    $selected_product = $db->escape($_GET['product']);
    $bom_structure = get_bom_structure($selected_product);
    $selected_product_name = get_product_name_by_part_number($selected_product);

    // Membuat nama file CSV
    $filename = 'bom_structure_' . $selected_product . '.csv';

    // Mengatur header HTTP agar browser mengenali file sebagai file CSV
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '"');

    // Membuka "php://output" sebagai file output CSV
    $output = fopen('php://output', 'w');

    // Menulis baris header CSV
    fputcsv($output, ['Child BOM', 'Child Name', 'Level', 'Quantity']);

    // Menulis data BOM Structure ke dalam file CSV
    foreach ($bom_structure as $bom_item) {
        fputcsv($output, [$bom_item['child_bom'], $bom_item['child_name'], $bom_item['level'], $bom_item['qty']]);
    }

    // Menutup file output
    fclose($output);

    exit();
} else {
    // Jika tidak ada parameter product, arahkan kembali ke halaman BOM View
    redirect('view_bom.php', false);
}
