<?php
// qr_generate_test.php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/includes/qrlib.php';

$book_id = 9999;
$qrcode_dir = __DIR__ . '/Uploads/qrcodes';
if (!is_dir($qrcode_dir)) mkdir($qrcode_dir, 0755, true);

$qrcode_file = $qrcode_dir . "/book_test_{$book_id}.png";
$qrcode_print_file = $qrcode_dir . "/book_test_{$book_id}_print.png";

$base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
$target_url = $base_url . '/detail.php?id=' . $book_id;

echo "<pre>Target URL: $target_url\n";
echo "Using lib: " . realpath(__DIR__ . '/includes/qrlib.php') . "\n";
echo "Class QR exists: " . (class_exists('QRcode') ? 'YES' : 'NO') . "\n\n";

try {
    // force regenerate and capture output/errors
    if (class_exists('QRcode')) {
        // try normal way (GD path)
        QRcode::png($target_url, $qrcode_file, 'L', 6, 2);
        $ok1 = file_exists($qrcode_file) ? 'YES' : 'NO';
        echo "Generated qrcode_web file? $ok1 -> $qrcode_file\n";

        // print-path (bigger)
        QRcode::png($target_url, $qrcode_print_file, 'H', 10, 2);
        $ok2 = file_exists($qrcode_print_file) ? 'YES' : 'NO';
        echo "Generated qrcode_print file? $ok2 -> $qrcode_print_file\n";

        // if files exist, show file sizes
        if (file_exists($qrcode_file)) echo "Size web: " . filesize($qrcode_file) . " bytes\n";
        if (file_exists($qrcode_print_file)) echo "Size print: " . filesize($qrcode_print_file) . " bytes\n";
    } else {
        echo "QRcode class not found; check includes/qrlib.php\n";
    }
} catch (Throwable $e) {
    echo "Exception: " . $e->getMessage() . "\n";
}

// show directory listing for troubleshooting
echo "\nDirectory listing (Uploads/qrcodes):\n";
$files = glob($qrcode_dir . '/*');
if ($files) {
    foreach ($files as $f) {
        echo basename($f) . " — " . filesize($f) . " bytes\n";
    }
} else {
    echo "(no files)\n";
}

echo "\nOpen the generated images in browser via:\n";
echo "http://" . $_SERVER['HTTP_HOST'] . str_replace('\\','/', str_replace($_SERVER['DOCUMENT_ROOT'], '', $qrcode_file)) . "\n";
echo "http://" . $_SERVER['HTTP_HOST'] . str_replace('\\','/', str_replace($_SERVER['DOCUMENT_ROOT'], '', $qrcode_print_file)) . "\n";

echo "</pre>";
