<?php
// counter.php - increments and renders an SVG badge counter
require_once __DIR__ . '/lib/storage.php';

function hex($v, $fallback) {
    $v = (string)$v;
    if (preg_match('/^#?[0-9A-Fa-f]{6}$/', $v)) {
        return '#' . ltrim($v, '#');
    }
    return $fallback;
}

function esc($s) { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }

$token = isset($_GET['token']) ? preg_replace('/[^A-Za-z0-9_-]/', '', $_GET['token']) : null;
$preview = isset($_GET['preview']);

header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
header('Content-Type: image/svg+xml');

if ($preview) {
    $title = isset($_GET['title']) ? substr($_GET['title'], 0, 80) : 'Visites';
    $count = isset($_GET['count']) ? (int)$_GET['count'] : 0;
    $bg = hex($_GET['bg'] ?? '#E5E7EB', '#E5E7EB');
    $tc = hex($_GET['tc'] ?? '#111827', '#111827');
    $bc = hex($_GET['bc'] ?? '#D1D5DB', '#D1D5DB');
    $br = max(0, min(24, (int)($_GET['br'] ?? 6)));
    $style = in_array(($_GET['style'] ?? 'solid'), ['solid','outline','pill','split'], true) ? $_GET['style'] : 'solid';
    $size = in_array(($_GET['size'] ?? 'md'), ['sm','md','lg'], true) ? $_GET['size'] : 'md';
    $ac = hex($_GET['ac'] ?? '#0EA5E9', '#0EA5E9');
    // Advanced preview options
    $sep = in_array(($_GET['sep'] ?? 'space'), ['space','dot','comma','none'], true) ? $_GET['sep'] : 'space';
    $nd = max(1, min(8, (int)($_GET['nd'] ?? 1)));
    $pre = isset($_GET['pre']) ? substr((string)$_GET['pre'], 0, 16) : '';
    $suf = isset($_GET['suf']) ? substr((string)$_GET['suf'], 0, 16) : '';
    $icon = !empty($_GET['icon']);
    $bw = max(0, min(4, (int)($_GET['bw'] ?? 1)));
    $sh = !empty($_GET['sh']);
    $grad = !empty($_GET['grad']);
    $gf = isset($_GET['gf']) ? hex($_GET['gf'], null) : null;
    $gt = isset($_GET['gt']) ? hex($_GET['gt'], null) : null;
    echo render_badge($title, $count, $bg, $tc, $bc, $br, $style, $size, $ac, [
        'format_sep' => $sep,
        'min_digits' => $nd,
        'prefix' => $pre,
        'suffix' => $suf,
        'icon' => $icon,
        'border_width' => $bw,
        'shadow' => $sh,
        'gradient' => $grad,
        'grad_from' => $gf,
        'grad_to' => $gt,
    ]);
    exit;
}

if (!$token) {
    echo render_badge('Compteur', 0, '#E5E7EB', '#111827', '#D1D5DB', 6, 'solid', 'md', '#0EA5E9');
    exit;
}

$updated = update_counter($token, function ($data) {
    $data['count'] = ($data['count'] ?? 0) + 1;
    return $data;
});

if (!$updated) {
    // token inconnu: ne pas créer implicitement, retourner un badge neutre
    echo render_badge('Inconnu', 0, '#FEE2E2', '#991B1B', '#FCA5A5', 6, 'solid', 'md', '#ef4444');
    exit;
}

$bg = $updated['bg_color'] ?? '#E5E7EB';
$tc = $updated['text_color'] ?? '#111827';
$bc = $updated['border_color'] ?? '#D1D5DB';
$br = (int)($updated['border_radius'] ?? 6);
$title = $updated['title'] ?? 'Visites';
$count = (int)($updated['count'] ?? 0);
$style = in_array(($updated['style'] ?? 'solid'), ['solid','outline','pill','split'], true) ? $updated['style'] : 'solid';
$size = in_array(($updated['size'] ?? 'md'), ['sm','md','lg'], true) ? $updated['size'] : 'md';
$ac = $updated['accent_color'] ?? '#0EA5E9';
$adv = [
    'format_sep' => in_array(($updated['format_sep'] ?? 'space'), ['space','dot','comma','none'], true) ? $updated['format_sep'] : 'space',
    'min_digits' => max(1, min(8, (int)($updated['min_digits'] ?? 1))),
    'prefix' => $updated['prefix'] ?? '',
    'suffix' => $updated['suffix'] ?? '',
    'icon' => !empty($updated['icon']),
    'border_width' => max(0, min(4, (int)($updated['border_width'] ?? 1))),
    'shadow' => !empty($updated['shadow']),
    'gradient' => !empty($updated['gradient']),
    'grad_from' => $updated['grad_from'] ?? null,
    'grad_to' => $updated['grad_to'] ?? null,
];

echo render_badge($title, $count, $bg, $tc, $bc, $br, $style, $size, $ac, $adv);

function render_badge($title, $count, $bg, $tc, $bc, $br, $style, $size, $ac, $adv = []) {
    // Size presets
    if ($size === 'sm') { $paddingX = 8; $paddingY = 5; $gap = 6; $fontSize = 12; }
    elseif ($size === 'lg') { $paddingX = 14; $paddingY = 8; $gap = 10; $fontSize = 15; }
    else { $paddingX = 10; $paddingY = 6; $gap = 8; $fontSize = 13; }

    $fontFamily = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Inter, Arial, sans-serif";

    // Formatting
    $sepMap = ['space' => ' ', 'dot' => '.', 'comma' => ',', 'none' => ''];
    $sepChar = $sepMap[$adv['format_sep'] ?? 'space'] ?? ' ';
    $minDigits = max(1, (int)($adv['min_digits'] ?? 1));
    $prefix = isset($adv['prefix']) ? (string)$adv['prefix'] : '';
    $suffix = isset($adv['suffix']) ? (string)$adv['suffix'] : '';
    $countAbs = max(0, (int)$count);
    $countStrRaw = number_format($countAbs, 0, '', $sepChar);
    if ($minDigits > 1 && $sepChar === '') {
        $plain = (string)$countAbs;
        $countStrRaw = str_pad($plain, $minDigits, '0', STR_PAD_LEFT);
    }
    $countStr = $prefix . $countStrRaw . $suffix;

    // Rough width estimation
    $titleW = max(24, strlen($title) * 7);
    $iconW = !empty($adv['icon']) ? 18 : 0;
    $countW = max(24, strlen($countStr) * 7);
    $width = $paddingX*3 + ($iconW ? ($iconW + 6) : 0) + $titleW + $gap + $countW;
    $height = ($fontSize + $paddingY*2) + 6;

    $rx = (int)($style === 'pill' ? max($br, 999) : $br);
    $titleX = $paddingX + ($iconW ? ($iconW + 6) : 0);
    $countX = $paddingX*2 + ($iconW ? ($iconW + 6) : 0) + $titleW + $gap;
    $centerY = ($height / 2) + ($size === 'lg' ? 5 : 4); // optical adjust

    // Optional icon SVG snippet
    $iconSvg = '';
    if (!empty($adv['icon'])) {
        $ix = $paddingX + 9;
        $iy = $centerY - 1;
        $iconSvg = "<circle cx=\"$ix\" cy=\"$iy\" r=\"5\" fill=\"$ac\" />";
    }

    // Style rendering
    $bgFill = $bg; $stroke = $bc; $titleFill = $tc; $countFill = $tc;
    $extra = '';
    $defs = '';
    $filter = '';
    $strokeWidth = max(0, min(4, (int)($adv['border_width'] ?? 1)));
    if (!empty($adv['shadow'])) {
        $filter = 'filter="url(#ds)"';
        $defs .= '<defs><filter id="ds" x="-50%" y="-50%" width="200%" height="200%">'
               . '<feDropShadow dx="0" dy="1" stdDeviation="1.5" flood-color="#00000055"/></filter></defs>';
    }
    if (!empty($adv['gradient']) && !empty($adv['grad_from']) && !empty($adv['grad_to'])) {
        $defs .= '<defs><linearGradient id="bgGrad" x1="0" y1="0" x2="1" y2="1">'
               . '<stop offset="0%" stop-color="' . esc($adv['grad_from']) . '"/>'
               . '<stop offset="100%" stop-color="' . esc($adv['grad_to']) . '"/>'
               . '</linearGradient></defs>';
        $bgFill = 'url(#bgGrad)';
    }
    if ($style === 'outline') {
        $bgFill = '#FFFFFF00'; // transparent
        $stroke = $ac ?: $bc;
    } elseif ($style === 'pill') {
        $bgFill = $bg;
        $stroke = $ac;
    } elseif ($style === 'split') {
        // Draw base rect, then a left accent rect for the title
        $leftW = $paddingX + $titleW + $gap;
        $titleFill = '#ffffff';
        $extra = "<rect x=\"0\" y=\"0\" width=\"$width\" height=\"$height\" fill=\"$bg\" stroke=\"$bc\" rx=\"$rx\" ry=\"$rx\"/>" .
                 "<clipPath id=\"clipR\"><rect x=\"0\" y=\"0\" width=\"$width\" height=\"$height\" rx=\"$rx\" ry=\"$rx\"/></clipPath>" .
                 "<rect x=\"0\" y=\"0\" width=\"$leftW\" height=\"$height\" fill=\"$ac\" clip-path=\"url(#clipR)\"/>";
        $bgFill = '#FFFFFF00';
        $stroke = '#FFFFFF00';
    }

    $svg = <<<SVG
<svg xmlns="http://www.w3.org/2000/svg" width="$width" height="$height" role="img" aria-label="{$title}: {$countStr}">
  <title>{$title}: {$countStr}</title>
  $defs
  $extra
  <rect x="0" y="0" width="$width" height="$height" fill="$bgFill" stroke="$stroke" rx="$rx" ry="$rx" stroke-width="$strokeWidth" $filter/>
  <g font-family="$fontFamily" font-size="$fontSize">
    <!-- optional icon -->
    $iconSvg
    <text x="$titleX" y="$centerY" dominant-baseline="middle" fill="$titleFill">${title}</text>
    <text x="$countX" y="$centerY" dominant-baseline="middle" font-weight="700" fill="$countFill">${countStr}</text>
  </g>
</svg>
SVG;
    return $svg;
}
