<?php
// Shortlink redirector: /s.php?c=XXXXXX -> redirects to the stored target URL
require_once __DIR__ . '/includes/functions.php';

function renderLinkMessagePage($title, $message, $isExpired = false) {
    http_response_code($isExpired ? 410 : 404);
    $pageTitle = $title;
    include __DIR__ . '/includes/public_header.php';
    ?>
    <div style="min-height:100vh; display:flex; align-items:center; justify-content:center; padding:32px 20px; background:var(--surface-soft);">
      <div style="width:100%; max-width:400px;">
        <div class="card" style="box-shadow:var(--shadow-md); text-align:center;">
          <?php if ($isExpired): ?>
            <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="#cf202f" stroke-width="1.6" stroke-linecap="round" style="margin:4px auto 16px;"><circle cx="12" cy="12" r="9"/><path d="M12 8v4M12 16h.01"/></svg>
          <?php else: ?>
            <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="#0052ff" stroke-width="1.6" stroke-linecap="round" style="margin:4px auto 16px;"><path d="M10 14a5 5 0 0 0 7.07 0l2.83-2.83a5 5 0 0 0-7.07-7.07L11.6 5.34"/><path d="M14 10a5 5 0 0 0-7.07 0L4.1 12.83a5 5 0 0 0 7.07 7.07L12.4 18.66"/></svg>
          <?php endif; ?>
          <h1 style="font-size:20px; margin-bottom:10px;"><?= htmlspecialchars($title) ?></h1>
          <p style="font-size:14px; color:var(--body); line-height:1.6;"><?= htmlspecialchars($message) ?></p>
        </div>
      </div>
    </div>
    <?php
    include __DIR__ . '/includes/public_footer.php';
    exit;
}

$code = trim($_GET['c'] ?? '');

if ($code === '' || !preg_match('/^[A-Za-z0-9]{4,12}$/', $code)) {
    renderLinkMessagePage('Invalid Link', 'This payment link is malformed.');
}

$link = getShortlinkRaw($code);

if (!$link) {
    renderLinkMessagePage('Link Not Found', 'This payment link does not exist or has been removed.');
}

if (isShortlinkExpired($link)) {
    renderLinkMessagePage(
        'Link Expired',
        'This payment link was only valid for 10 minutes and has now expired. Please ask the sender for a new payment link.',
        true
    );
}

incrementShortlinkClicks($code);

header('Location: ' . $link['target_url']);
exit;
