<?php
require_once __DIR__.'/../app/bootstrap.php';
$code = $_GET['c'] ?? '';
if (!preg_match('/^[A-Za-z0-9_-]{4,32}$/', $code)) { http_response_code(404); exit('QR-Code nicht gefunden.'); }
$stmt = $pdo->prepare('SELECT * FROM '.qtbl('qr_codes').' WHERE code = ?');
$stmt->execute([$code]);
$qr = $stmt->fetch();
if (!$qr || !valid_url($qr['target_url'])) { http_response_code(404); exit('QR-Code nicht gefunden.'); }
$targetUrl = qr_append_utm($qr['target_url'], $qr);
$pdo->beginTransaction();
$upd = $pdo->prepare('UPDATE '.qtbl('qr_codes').' SET scan_count = scan_count + 1, last_scan_at = NOW() WHERE id = ?');
$upd->execute([$qr['id']]);
$ip = $_SERVER['REMOTE_ADDR'] ?? '';
$salt = $config['stats_salt'] ?? ($config['session_name'] ?? 'qrmanager');
$ipHash = $ip ? hash('sha256', $salt.'|'.$ip) : null;
$ua = substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 255);
$ref = substr($_SERVER['HTTP_REFERER'] ?? '', 0, 500);
$geo = qr_geo_lookup($config, $ip);
$log = $pdo->prepare('INSERT INTO '.qtbl('qr_scans').'(qr_code_id, ip_hash, user_agent, referer, country_code, country_name, region_name, city) VALUES(?,?,?,?,?,?,?,?)');
$log->execute([$qr['id'], $ipHash, $ua ?: null, $ref ?: null, $geo['country_code'], $geo['country_name'], $geo['region_name'], $geo['city']]);
$pdo->commit();
header('Location: '.$targetUrl, true, 302);
exit;
