<?php
// Simple inline SR NO migration - no session required
$dataFile = __DIR__ . '/data/products.json';

if (!file_exists($dataFile)) {
    echo "ERROR: Products file not found at: " . $dataFile;
    exit(1);
}

$contents = file_get_contents($dataFile);
$products = json_decode($contents, true);

if (!is_array($products)) {
    echo "ERROR: Failed to decode products JSON";
    exit(1);
}

$needsUpdate = 0;
$maxSrNo = 0;

foreach ($products as &$product) {
    if (empty($product['sr_no'])) {
        $product['sr_no'] = $product['id'];
        $needsUpdate++;
    }
    if ($product['sr_no'] > $maxSrNo) {
        $maxSrNo = $product['sr_no'];
    }
}
unset($product);

// Save with proper formatting
$saveResult = file_put_contents($dataFile, json_encode($products, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

if ($saveResult !== false) {
    echo "✓ SUCCESS: SR NO Migration Complete\n";
    echo "─────────────────────────────────\n";
    echo "Updated products: " . $needsUpdate . "\n";
    echo "Total products: " . count($products) . "\n";
    echo "Max SR NO: " . $maxSrNo . "\n";
    echo "✓ All products now have unique serial numbers for QR codes!\n";
    exit(0);
} else {
    echo "✗ ERROR: Failed to save products file\n";
    echo "Check file permissions: " . $dataFile;
    exit(1);
}
?>
