<?php
require_once __DIR__ . '/../app/bootstrap.php';
use App\Core\Database; use App\Core\Response; use App\Core\Security;
$ref = strtoupper(mb_substr(trim((string)($_GET['ref'] ?? '')),0,50));
if (!preg_match('/^[A-Z0-9_-]{3,50}$/',$ref)) Response::json(['ok'=>true]);
if (!Security::rateLimit('affiliate-click:'.Security::clientIp().'|'.$ref,60,3600)) Response::json(['ok'=>true]);
$member = Database::safeFetchOne('SELECT id FROM affiliate_members WHERE referral_code=? AND status="active" LIMIT 1',[$ref]);
if (!$member) Response::json(['ok'=>true]);
$landing = mb_substr((string)($_GET['url'] ?? ''),0,255);
if (!Security::isSafeReturnPath($landing)) $landing = '';
Database::safeExecute('INSERT INTO affiliate_clicks (referral_code,landing_url,ip_address,user_agent,created_at) VALUES (?,?,?,?,NOW())',[$ref,$landing,Security::clientIp(),Security::userAgent()]);
Response::json(['ok'=>true]);
