<?php
/**
 * TrackPro — Pixel Tracker (1x1 transparent GIF)
 * Embed in emails/documents: <img src="https://domain.com/link/trackpro/tracking/pixel.php?uid=XXXX" width="1" height="1">
 */
require_once __DIR__ . '/../includes/db.php';

$uid = $_GET['uid'] ?? '';
if (empty($uid) || !preg_match('/^[a-zA-Z0-9]+$/', $uid)) {
    header('Content-Type: image/gif');
    echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
    exit;
}

$pdo = getDB();
$stmt = $pdo->prepare("SELECT `id`,`pixel_enabled` FROM `tracking_links` WHERE `link_uid` = ? AND `is_active` = 1");
$stmt->execute([$uid]);
$link = $stmt->fetch();

if ($link && $link['pixel_enabled']) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['HTTP_X_REAL_IP'] ?? $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    $ip = trim(explode(',', $ip)[0]);
    try {
        $pdo->prepare("INSERT INTO `pixel_opens` (`link_id`,`ip_address`,`user_agent`,`referer`) VALUES (?,?,?,?)")
            ->execute([$link['id'], $ip, $_SERVER['HTTP_USER_AGENT'] ?? null, $_SERVER['HTTP_REFERER'] ?? null]);
    } catch (Exception $e) {
        error_log("Pixel track error: " . $e->getMessage());
    }
}

// Serve 1x1 transparent GIF with no-cache headers
header('Content-Type: image/gif');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
