<?php

$kitWeightsFile = "kit_weights.csv";
$magentoImportFile = "magento_import_bd.csv";
$outputFile = "bundles_with_weight_mismatch.csv";

$simpleWeights = [];
if (($handle = fopen($kitWeightsFile, "r")) !== FALSE) {
    fgetcsv($handle); // Skip header
    while (($data = fgetcsv($handle)) !== FALSE) {
        $simpleWeights[$data[0]] = (float) $data[1]; // SKU => Weight
    }
    fclose($handle);
}

$rows = [];
if (($handle = fopen($magentoImportFile, "r")) !== FALSE) {
    $header = fgetcsv($handle); // Read header
    $rows[] = array_merge($header, ["weight_mismatch"]); // Add new column

    while (($data = fgetcsv($handle)) !== FALSE) {
        $bundleSKUs = explode("_", $data[0]); // Split bundle SKUs
        $bundleWeight = (float) $data[1]; // Get bundle's weight

        $mismatch = false;
        foreach ($bundleSKUs as $sku) {
            if (isset($simpleWeights[$sku]) && $simpleWeights[$sku] != $bundleWeight) {
                $mismatch = true;
                break;
            }
        }

        $data[] = $mismatch ? "TRUE" : "FALSE"; // Add mismatch flag
        if ($mismatch) {
            $data[] = $simpleWeights[$sku];
            $data[] = $bundleWeight;
            $rows[] = $data; // Store mismatched rows
        }
    }
    fclose($handle);
}

if (($handle = fopen($outputFile, "w")) !== FALSE) {
    foreach ($rows as $row) {
        fputcsv($handle, $row);
    }
    fclose($handle);
}

echo "Export complete: $outputFile\n";

