<?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 "=== After Format Information Fix ===\n\n";

$config = new QrCodeConfig(
    version: QrCodeVersion::fromNumber(1),
    errorCorrectionLevel: ErrorCorrectionLevel::M,
    encodingMode: EncodingMode::BYTE
);

$matrix = QrCodeGenerator::generate("HELLO WORLD", $config);
$size = $matrix->getSize();

// Extract format information
$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';
}

$formatRows = [20, 19, 18, 17, 16, 15, 14, 8, 7, 5, 4, 3, 2, 1, 0];
$formatV = '';
foreach ($formatRows as $row) {
    $formatV .= $matrix->getModuleAt($row, 8)->isDark() ? '1' : '0';
}

echo "Our Format Information:\n";
echo "  Horizontal: {$formatH}\n";
echo "  Vertical:   {$formatV}\n";
echo "  Match: " . ($formatH === $formatV ? "✅" : "❌") . "\n\n";

// Decode
$xorMask = "101010000010010";
$unmaskedH = '';
for ($i = 0; $i < 15; $i++) {
    $unmaskedH .= (int)$formatH[$i] ^ (int)$xorMask[$i];
}

$ecBits = substr($unmaskedH, 0, 2);
$maskBits = substr($unmaskedH, 2, 3);

echo "Decoded:\n";
echo "  EC Level: {$ecBits} = " . match($ecBits) {'01' => 'L', '00' => 'M', '11' => 'Q', '10' => 'H'} . "\n";
echo "  Mask Pattern: {$maskBits} = Pattern " . bindec($maskBits) . "\n\n";

// Generate large PNG for testing
$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/qrcode-CORRECTED.png';
imagepng($image, $filepath, 0);

echo "✅ Corrected QR code generated: qrcode-CORRECTED.png\n";
echo "   Size: {$totalSize}x{$totalSize}px\n";
echo "   Mask Pattern: " . bindec($maskBits) . "\n";
echo "\nPlease test this QR code with your scanner!\n";
