<?php

// Include the QRcode library
include('phpqrcode/qrlib.php');

/**
 * Generates a transparent QR code from a URL and saves it to a folder.
 *
 * @param string $url The URL to encode in the QR code.
 * @param string $outputFolder Folder where the QR code will be saved.
 * @param string $publicBaseUrl Public base URL (e.g. https://www.example.com/qr/)
 * @return string|false Public URL to the saved QR code image, or false on failure.
 */
function generateTransparentQR($url, $outputFolder = 'qr_codes/') {
    // Ensure output folder exists
    if (!is_dir($outputFolder)) {
        if (!mkdir($outputFolder, 0755, true)) {
            return false;
        }
    }

    // Generate a unique filename
    $fileName = uniqid('qrcode_') . '.png';
    $filePath = $outputFolder . $fileName;

    // Temporary QR code file
    $tempQR = tempnam(sys_get_temp_dir(), 'qr_') . '.png';

    // Generate basic QR code
    QRcode::png($url, $tempQR, 'H', 10);

    // Load QR code image
    $qrImage = imagecreatefrompng($tempQR);

    if (!$qrImage) return false;

    // Create truecolor image with transparency
    $transparentQR = imagecreatetruecolor(imagesx($qrImage), imagesy($qrImage));
    imagealphablending($transparentQR, false);
    imagesavealpha($transparentQR, true);
    $transparentColor = imagecolorallocatealpha($transparentQR, 0, 0, 0, 127);
    imagefill($transparentQR, 0, 0, $transparentColor);

    // Make white pixels transparent
    for ($x = 0; $x < imagesx($qrImage); $x++) {
        for ($y = 0; $y < imagesy($qrImage); $y++) {
            $rgb = imagecolorat($qrImage, $x, $y);
            $colors = imagecolorsforindex($qrImage, $rgb);

            if ($colors['red'] == 255 && $colors['green'] == 255 && $colors['blue'] == 255) {
                imagesetpixel($transparentQR, $x, $y, $transparentColor);
            } else {
                imagesetpixel($transparentQR, $x, $y, $rgb);
            }
        }
    }

    // Save transparent QR image
    imagepng($transparentQR, $filePath);

    // Cleanup
    imagedestroy($qrImage);
    imagedestroy($transparentQR);
    unlink($tempQR);

    return $fileName;
}

// Example usage
$url = "https://www.jobaajlearnings.com/?utm_source=investment_banking&utm_medium=book&utm_campaign=tracking";
$qrUrl = generateTransparentQR($url);

if ($qrUrl) {
    echo "QR Code generated: $qrUrl";
} else {
    echo "Failed to generate QR Code.";
}
?>
