<?php
require_once('functions.php');

// Only execute if this is a POST request (form submission)
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    // Create CSV headers that match your table exactly
    $csv_hdr = "Product,Category,Retail Price,Wholesale Price,Buying Price,Minimum Price,Maximum Price,\n";
    $csv_output = "";

    $dbc =mysqli_connect('localhost','jbxnmmli_spo','@@!@SWQ!Y6tgaq@!@','jbxnmmli_pso');
    $result = mysqli_query($dbc, "SELECT * FROM products ORDER BY p_name ASC");

    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            // Format each field properly for CSV
            $csv_output .= '"' . str_replace('"', '""', $row['p_name']) . '",';
            $csv_output .= '"' . str_replace('"', '""', $row['category']) . '",';
          //  $csv_output .= $row['left_p'] . ',';
            $csv_output .= $row['price'] . ',';
            $csv_output .= $row['minimum'] . ',';
            $csv_output .= $row['buying'] . ',';
            $csv_output .= $row['minprice'] . ',';
            $csv_output .= $row['maxprice'];
            $csv_output .= "\n";
        }
    }

    mysqli_close($dbc);

    // Generate filename and headers
    $filename = "products_export_" . date("Y-m-d_H-i") . ".csv";
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Pragma: no-cache');
    header('Expires: 0');

    // Output CSV
    echo "\xEF\xBB\xBF" . $csv_hdr . $csv_output;
    exit;
    
} else {
    // If accessed directly without form submission, redirect back
    header("Location: your_main_page.php");
    exit;
}
?>