<?php

declare(strict_types=1);

require_once __DIR__ . '/../../vendor/autoload.php';

use App\Framework\QrCode\QrCodeGenerator;
use App\Framework\QrCode\ValueObjects\ErrorCorrectionLevel;
use App\Framework\QrCode\ValueObjects\QrCodeConfig;
use App\Framework\QrCode\ValueObjects\QrCodeVersion;
use App\Framework\QrCode\ValueObjects\EncodingMode;

echo "=== Generating Minimal Test QR Codes ===\n\n";

$testData = [
    'A' => 'qrcode-test-A.png',
    'HELLO' => 'qrcode-test-HELLO.png',
    '123' => 'qrcode-test-123.png',
];

foreach ($testData as $data => $filename) {
    $config = new QrCodeConfig(
        version: QrCodeVersion::fromNumber(1),
        errorCorrectionLevel: ErrorCorrectionLevel::M,
        encodingMode: EncodingMode::BYTE
    );
    
    $matrix = QrCodeGenerator::generate($data, $config);
    $size = $matrix->getSize();
    
    // Generate PNG
    $scale = 20;
    $quietZone = 4;
    $totalSize = ($size + 2 * $quietZone) * $scale;
    
    $image = imagecreate($totalSize, $totalSize);
    $white = imagecolorallocate($image, 255, 255, 255);
    $black = imagecolorallocate($image, 0, 0, 0);
    
    imagefill($image, 0, 0, $white);
    
    for ($row = 0; $row < $size; $row++) {
        for ($col = 0; $col < $size; $col++) {
            if ($matrix->getModuleAt($row, $col)->isDark()) {
                $x = ($quietZone + $col) * $scale;
                $y = ($quietZone + $row) * $scale;
                
                for ($dy = 0; $dy < $scale; $dy++) {
                    for ($dx = 0; $dx < $scale; $dx++) {
                        imagesetpixel($image, $x + $dx, $y + $dy, $black);
                    }
                }
            }
        }
    }
    
    $filepath = "/var/www/html/public/{$filename}";
    imagepng($image, $filepath, 0);
    
    // Read format info
    $formatCols = [0, 1, 2, 3, 4, 5, 7, 8, 20, 19, 18, 17, 16, 15, 14];
    $formatH = '';
    foreach ($formatCols as $col) {
        $formatH .= $matrix->getModuleAt(8, $col)->isDark() ? '1' : '0';
    }
    
    echo "✅ Generated: {$filename}\n";
    echo "   Data: \"{$data}\"\n";
    echo "   Format: {$formatH}\n";
    echo "   Size: {$totalSize}x{$totalSize}px\n\n";
}

echo "Please test these QR codes:\n";
echo "1. https://localhost/qrcode-test-A.png (simplest - just 'A')\n";
echo "2. https://localhost/qrcode-test-HELLO.png\n";
echo "3. https://localhost/qrcode-test-123.png\n\n";

echo "If even 'A' doesn't scan, there's a fundamental structural problem.\n";
echo "If 'A' scans but 'HELLO WORLD' doesn't, it's a data encoding issue.\n";

