<?php
/**
 * generate_qr_code.php
 * 
 * Endpoint to generate QR codes for cryptocurrency addresses
 * Uses the PHP QR Code library if available, or falls back to an external API
 */

header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// CRITICAL: Allow origin with credentials
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Define TONSUI_LOADED constant to prevent direct access to session_init.php
define('TONSUI_LOADED', true);

// Include centralized session initialization
require_once __DIR__ . '/session_init.php';

// Require user authentication
requireLogin(true);

// The data to encode in the QR code
$data = isset($_GET['data']) ? trim($_GET['data']) : '';

if (empty($data)) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Missing required parameter: data'
    ]);
    exit;
}

// Maximum length to prevent abuse
if (strlen($data) > 1000) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Data exceeds maximum allowed length'
    ]);
    exit;
}

try {
    // Generate a QR code and return as a data URI
    $qrCode = generateQRCode($data);
    
    echo json_encode([
        'success' => true,
        'qr_code' => $qrCode
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    error_log('Error generating QR code: ' . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred while generating QR code'
    ]);
}

/**
 * Generate a QR code for the provided data
 * Returns a data URI for the QR code image
 * 
 * @param string $data The data to encode in the QR code
 * @return string Data URI for the QR code
 */
function generateQRCode($data) {
    // Try to use the PHP QR Code library if it exists
    $phpqrcode_path = __DIR__ . '/../vendor/phpqrcode/qrlib.php';
    
    if (file_exists($phpqrcode_path)) {
        require_once $phpqrcode_path;
        
        // Generate QR code image and return as a data URI
        ob_start();
        \QRcode::png($data, null, QR_ECLEVEL_L, 10, 2);
        $qrcode_image = ob_get_clean();
        
        return 'data:image/png;base64,' . base64_encode($qrcode_image);
    }
    
    // Fall back to an external API
    $baseUrl = "https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=";
    return $baseUrl . urlencode($data);
}
