<?php
// brand_logo.php - dynamic SVG text-based logo
// Usage: /auth-backend/brand_logo.php?t=Multi-purpose%20International&color=%23111827&accent=%23c1121f&bg=none

header('Content-Type: image/svg+xml');
header('Cache-Control: public, max-age=86400');

// Try to read env if available
if (!class_exists('TonEnv')) {
  $envPath = __DIR__ . '/includes/Env.php';
  if (is_file($envPath)) { require_once $envPath; }
}

$brand = isset($_GET['t']) ? trim($_GET['t']) : '';
if ($brand === '' || $brand === null) {
  $brand = class_exists('TonEnv') ? (string)TonEnv::get('BRAND_NAME', 'Multi-purpose International') : 'Multi-purpose International';
}

$color = isset($_GET['color']) ? $_GET['color'] : '#111827'; // text color
$accent = isset($_GET['accent']) ? $_GET['accent'] : '#c1121f'; // accent underline
$bg = isset($_GET['bg']) ? $_GET['bg'] : 'none'; // background
$fontWeight = isset($_GET['weight']) ? (int)$_GET['weight'] : 800;
$paddingX = 24; $paddingY = 18; $fontSize = isset($_GET['size']) ? (int)$_GET['size'] : 28;

// Estimate width roughly: average 0.6em per char
$len = mb_strlen($brand, 'UTF-8');
$estTextWidth = (int)ceil($fontSize * 0.62 * $len);
$width = $estTextWidth + ($paddingX * 2);
$height = (int)($fontSize + ($paddingY * 2));
if ($width < 320) $width = 320; if ($height < 72) $height = 72;
// Compute underline Y position
$underlineY = $fontSize + 6;

// Basic sanitization for SVG attributes
function esc($s) { return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
// Allow only safe color values (#hex, none, currentColor, rgb/rgba)
function escColor($c) {
  $c = trim($c);
  if (preg_match('/^(none|currentColor)$/i', $c)) return $c;
  if (preg_match('/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/', $c)) return $c;
  if (preg_match('/^rgba?\([0-9 ,\.]+\)$/', $c)) return $c;
  return '#111827';
}
$color = escColor($color);
$accent = escColor($accent);
$bg = escColor($bg);
$brandEsc = esc($brand);

$svg = <<<SVG
<svg xmlns="http://www.w3.org/2000/svg" width="$width" height="$height" viewBox="0 0 $width $height" role="img" aria-label="" preserveAspectRatio="xMinYMin meet">
  <title>{$brandEsc}</title>
  <rect x="0" y="0" width="$width" height="$height" fill="{$bg}"/>
  <g transform="translate({$paddingX}, {$paddingY})">
    <text x="0" y="{$fontSize}" font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif" font-size="{$fontSize}" font-weight="{$fontWeight}" fill="{$color}">{$brandEsc}</text>
    <rect x="0" y="{$underlineY}" width="{$estTextWidth}" height="4" fill="{$accent}" rx="2"/>
  </g>
</svg>
SVG;

echo $svg;
