<?php
ob_clean();

$export_query = "SELECT * FROM $table_name $where ORDER BY id ASC";
$rs = mysqli_query($conn, $export_query);


function csvField($value) {
    $value = (string)$value;
    if ($value !== '' && preg_match('/^[=+\-@\t\r]/', $value)) {
        $value = "'" . $value; // neutralize leading formula-trigger characters
    }
    $value = str_replace('"', '""', $value);
    return '"' . $value . '"';
}

$rows = [];
$rows[] = ['Part Number', 'Customers Ref', 'Customers Ref Code', 'Req Date', 'Req Qty', 'RefSalesCode'];

while ($row = mysqli_fetch_assoc($rs)) {
    $isNotExist = ($row['item_not_exist'] == 1);

    $partName = $isNotExist
        ? $row['item_name_if_not_exist']
        : utility::getTableFieldById("item_management", "part_number", "id", $row['part_id']);

    if ($row['customer_reff'] > 0) {
        $customerName = ucfirst(utility::getTableFieldById("client_management", "customer_name", "id", $row["customer_reff"]));
        $customerCode = ucfirst(utility::getTableFieldById("client_management", "customer_code", "id", $row["customer_reff"]));
    } else {
        $customerName = "Not Found";
        $customerCode = "Not Found";
    }

    $reqDate = $row['req_date'] ? date('d-m-Y', strtotime($row['req_date'])) : '';
    $reqQty  = ucfirst($row['req_qty']);
    $refSalesCode = ucfirst($row['RefSalesCode']);

    $rows[] = [$partName, $customerName, $customerCode, $reqDate, $reqQty, $refSalesCode];
}

$data = "";
foreach ($rows as $r) {
    $data .= implode(",", array_map('csvField', $r)) . "\n";
}

$file_name = "export_to_production_planning_report.csv";

ob_clean();
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$file_name");
header("Pragma: no-cache");
header("Expires: 0");
echo $data;
die;
?>