<?php
// track/click.php - Tracking klik link

$cid   = $_GET['cid']   ?? '';
$token = $_GET['token'] ?? '';
$url   = $_GET['url']   ?? '';

if ($cid && $token && $url && filter_var($url, FILTER_VALIDATE_URL) &&
    preg_match('/^camp_[a-z0-9]+$/', $cid)) {

    $file = __DIR__ . "/../tracking/$cid.json";
    if (file_exists($file)) {
        $data = json_decode(file_get_contents($file), true);
        if (isset($data['recipients'][$token])) {
            $data['recipients'][$token]['clicked'] = ($data['recipients'][$token]['clicked'] ?? 0) + 1;
            $data['clicked'] = ($data['clicked'] ?? 0) + 1;
            file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT));
        }
    }

    header("Location: " . $url, true, 302);
    exit;
}

http_response_code(400);
echo "Bad Request";
exit;