<?php
/**
 * QR Code Generator - Creates and stores QR codes for all products
 * Uses QR Server API to generate PNG files
 */

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

// Create QR codes folder if it doesn't exist
if (!is_dir($qrFolder)) {
    if (!mkdir($qrFolder, 0755, true)) {
        die("Error: Could not create QR codes folder!\n");
    }
}

// Read products
$products = [];
if (file_exists($dataFile)) {
    $jsonContent = file_get_contents($dataFile);
    if ($jsonContent === false) {
        die("Error: Could not read products file!\n");
    }
    $products = json_decode($jsonContent, true);
    if (!is_array($products)) {
        die("Error: Products file is not valid JSON array!\n");
    }
} else {
    die("Error: Products file not found!\n");
}

$generated = 0;
$failed = 0;
$skipped = 0;

echo "Generating QR Codes for all products...\n";
echo "=====================================\n\n";

$productCount = count($products);
echo "Processing {$productCount} products...\n\n";

for ($i = 0; $i < count($products); $i++) {
    $product = &$products[$i];
    
    $productId = $product['id'] ?? 0;
    if (!$productId) {
        $failed++;
        echo "✗ Product #{$i}: No ID found\n";
        continue;
    }
    
    // Skip if QR code already exists
    if (!empty($product['qr_code'])) {
        $skipped++;
        echo "⊘ Product ID {$productId}: QR code already exists\n";
        continue;
    }
    
    // Generate QR code
    $productUrl = 'http://localhost/ecoms/product.php?id=' . $productId;
    $qrFilename = 'qr_' . $productId . '.png';
    $qrFilePath = $qrFolder . '/' . $qrFilename;
    $qrRelativePath = 'pics_ecom/qr_codes/' . $qrFilename;
    
    // Use QR Server API to generate QR code
    $qrApiUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' . urlencode($productUrl);
    
    // Download QR code image from API
    $qrImageContent = @file_get_contents($qrApiUrl);
    
    if ($qrImageContent !== false && strlen($qrImageContent) > 0) {
        // Save QR code file
        if (file_put_contents($qrFilePath, $qrImageContent) !== false) {
            $product['qr_code'] = $qrRelativePath;
            $generated++;
            echo "✓ Product ID {$productId}: QR code generated\n";
        } else {
            $failed++;
            echo "✗ Product ID {$productId}: Failed to save file\n";
        }
    } else {
        $failed++;
        echo "✗ Product ID {$productId}: Failed to download from API\n";
    }
}
unset($product);

// Save updated products with QR code paths
$jsonOutput = json_encode($products, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
if ($jsonOutput === false) {
    die("Error: Could not encode products to JSON!\n");
}

$saveResult = file_put_contents($dataFile, $jsonOutput);

echo "\n=====================================\n";
echo "✓ COMPLETED!\n";
echo "  Generated: {$generated} QR codes\n";
echo "  Skipped: {$skipped} (already existed)\n";
echo "  Failed: {$failed}\n";
echo "  Location: $qrFolder\n";
echo "\nQR codes are linked to: http://localhost/ecoms/product.php?id=[product_id]\n";
?>
