<?php
// api/preview_ticket.php — Generate + stream a preview ticket image
// Suppress deprecation/notice output that would corrupt the PNG stream
error_reporting(E_ERROR | E_PARSE);
@ini_set('display_errors', '0');

// Catch all errors before any output
set_error_handler(function($errno, $errstr, $errfile, $errline) {
    // Ignore deprecations, notices and warnings — only show real errors
    // (custom handlers override error_reporting(), so we filter manually)
    if ($errno & (E_DEPRECATED | E_USER_DEPRECATED | E_NOTICE | E_USER_NOTICE | E_WARNING | E_USER_WARNING)) {
        return true; // suppress — return true means "handled, don't bubble"
    }
    outputErrorImage("PHP Error: $errstr (line $errline)");
});
set_exception_handler(function($e) {
    outputErrorImage("Exception: " . $e->getMessage());
});

function outputErrorImage(string $msg): never {
    if (!headers_sent()) {
        header('Content-Type: image/png');
        header('Cache-Control: no-store');
    }
    $w = 600; $h = 200;
    $img = imagecreatetruecolor($w, $h);
    $bg  = imagecolorallocate($img, 30, 10, 10);
    $red = imagecolorallocate($img, 220, 80, 80);
    $wht = imagecolorallocate($img, 220, 220, 220);
    imagefill($img, 0, 0, $bg);
    imagestring($img, 4, 20, 30, 'PREVIEW ERROR', $red);
    // Word-wrap the message across multiple lines
    $words = explode(' ', $msg);
    $line = ''; $y = 70;
    foreach ($words as $word) {
        $test = $line ? "$line $word" : $word;
        if (strlen($test) > 60) {
            imagestring($img, 2, 20, $y, $line, $wht);
            $y += 18; $line = $word;
        } else {
            $line = $test;
        }
    }
    if ($line) imagestring($img, 2, 20, $y, $line, $wht);
    imagepng($img);
    imagedestroy($img);
    exit;
}

require_once __DIR__ . '/../config.php';
startSecureSession();

// Auth — check both admin session AND a signed token for cross-request compatibility
if (empty($_SESSION['admin_id'])) {
    // Try token-based auth as fallback
    $tok    = $_GET['tok'] ?? '';
    $eId    = (int)($_GET['event_id'] ?? 0);
    $expect = substr(md5('preview' . $eId . date('YmdH')), 0, 12);
    if ($tok !== $expect) {
        outputErrorImage('Not authenticated. Please refresh the page and try again.');
    }
}

require_once BASE_PATH . '/lib/qr_invite.php';

$eventId = (int)($_GET['event_id'] ?? 0);
if (!$eventId) outputErrorImage('No event ID provided.');

$db = db();
$ev = $db->prepare('SELECT * FROM events WHERE id=?');
$ev->execute([$eventId]);
$event = $ev->fetch();

if (!$event) outputErrorImage('Event not found (ID: ' . $eventId . ')');

// Check template exists — show all attempted paths if missing
if (empty($event['ticket_template'])) {
    outputErrorImage('No ticket template uploaded for this event. Upload one in the designer first.');
}
$tplPath = resolveUploadPath($event['ticket_template']);
if (!$tplPath) {
    // Show diagnostic info
    $stored = $event['ticket_template'];
    outputErrorImage(
        'Template file not found on disk. ' .
        'Stored: "' . $stored . '" | ' .
        'BASE_PATH: ' . BASE_PATH . ' | ' .
        'Tried: ' . BASE_PATH . '/' . $stored . ' and ' .
        ($_SERVER['DOCUMENT_ROOT'] ?? 'no-docroot') . '/' . $stored
    );
}

// Check layout saved
if (empty($event['ticket_layout'])) {
    outputErrorImage('No layout saved yet. Click "Save Layout" in the designer first.');
}

// Use first real guest or generate a dummy
$gs = $db->prepare('SELECT * FROM guests WHERE event_id=? LIMIT 1');
$gs->execute([$eventId]);
$guest = $gs->fetch();

if (!$guest) {
    $guest = [
        'id'           => 0,
        'event_id'     => $eventId,
        'name'         => 'Sample Guest Name',
        'email'        => '',
        'category'     => 'VIP',
        'table_number' => 'A1',
        'seat_number'  => '',
        'token'        => 'preview_' . md5($eventId . 'preview'),
        'invite_path'  => null,
    ];
}

// Always delete cached preview so it regenerates fresh
$slug        = $event['slug'] ?? 'preview';
$previewDir  = INVITE_PATH . '/' . $slug;
if (!is_dir($previewDir)) mkdir($previewDir, 0755, true);
$previewFile = $previewDir . '/' . $guest['token'] . '.png';
if (file_exists($previewFile)) unlink($previewFile);

// Generate
$path = buildInvite($guest, $event);

if (!file_exists($path)) {
    outputErrorImage('Ticket generation failed — file was not created at: ' . $path);
}

$size = filesize($path);
if ($size < 100) {
    outputErrorImage('Generated file is too small (' . $size . ' bytes) — likely corrupted.');
}

// Stream image
header('Content-Type: image/png');
header('Content-Length: ' . $size);
header('Cache-Control: no-store, no-cache');
header('X-Preview-Path: ' . basename($path));
readfile($path);
exit;
