<?php
define('_FEXEC', 1);
require('includes/application_top.php');

// Make sure a section_id is provided
if (!isset($_GET['section_id']) || empty($_GET['section_id'])) {
    die('Section ID not provided.');
}

$section_id = (int)$_GET['section_id'];

// Build the query to join products and products_description based on products_id
// and filter by section_id (which is the same as your categories_id / cPath)
$query = "SELECT 
            p.products_id, 
            p.products_quantity, 
            pd.products_name, 
            pd.products_number, 
            p.color_code, 
            p.products_status, 
            p.products_x, 
            p.products_y, 
            p.products_w, 
            p.products_h, 
            p.products_r, 
            p.products_sx, 
            p.products_sy, 
            p.product_type
          FROM " . TABLE_PRODUCTS . " p
          JOIN " . TABLE_PRODUCTS_DESCRIPTION . " pd 
            ON p.products_id = pd.products_id
          WHERE p.section_id = " . $section_id;

$result = tep_db_query($query);

$filename = "export_section_" . $section_id . ".csv";

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

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

// Write the header row
fputcsv($output, [
    'products_id',
    'products_quantity',
    'products_name',
    'products_number',
    'color_code',
    'products_status',
    'products_x',
    'products_y',
    'products_w',
    'products_h',
    'products_r',
    'products_sx',
    'products_sy',
    'product_type'
]);

// Write each data row to the CSV
while ($row = tep_db_fetch_array($result)) {
    fputcsv($output, [
        $row['products_id'],
        $row['products_quantity'],
        $row['products_name'],
        $row['products_number'],
        $row['color_code'],
        $row['products_status'],
        $row['products_x'],
        $row['products_y'],
        $row['products_w'],
        $row['products_h'],
        $row['products_r'],
        $row['products_sx'],
        $row['products_sy'],
        $row['product_type']
    ]);
}

fclose($output);
exit;
?>
