<?php
/**
 * Fast QR Code Generator - Uses data URIs with QR Server API
 */

$dataFile = __DIR__ . '/data/products.json';
$qrFolder = __DIR__ . '/pics_ecom/qr_codes';

// Create QR codes folder
if (!is_dir($qrFolder)) {
    mkdir($qrFolder, 0755, true);
}

// Read products JSON
$jsonContent = file_get_contents($dataFile);
$products = json_decode($jsonContent, true);

echo "Generating QR codes for " . count($products) . " products...\n\n";

$generated = 0;
$failed = 0;

foreach ($products as $idx => $product) {
    $id = $product['id'] ?? 0;
    if (!$id) continue;
    
    // Check if already has QR code
    if (!empty($product['qr_code'])) {
        echo "⊘ ID {$id}: Already has QR code\n";
        continue;
    }
    
    $qrFile = $qrFolder . '/qr_' . $id . '.png';
    $qrUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' . 
             urlencode('http://localhost/ecoms/product.php?id=' . $id);
    
    // Download and save
    $data = @file_get_contents($qrUrl);
    if ($data && file_put_contents($qrFile, $data)) {
        $products[$idx]['qr_code'] = 'pics_ecom/qr_codes/qr_' . $id . '.png';
        $generated++;
        echo "✓ Product {$id}: Generated\n";
    } else {
        $failed++;
        echo "✗ Product {$id}: Failed\n";
    }
    
    // Small delay to avoid rate limiting
    usleep(100000);
}

// Save products
file_put_contents($dataFile, json_encode($products, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));

echo "\n========================================\n";
echo "✓ Complete! Generated: {$generated}, Failed: {$failed}\n";
?>
