<?php

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';

/**
 * Odchod do obchodu: 302 (cíl se mění při reimportu feedu), nikdy neindexovat,
 * nikdy nekešovat — zakešovaný 301 na mrtvou affiliate URL = ztracená provize.
 */
function affiliateExit(string $targetUrl, array $click = []): void {
    logAffiliateClick($click);

    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header('Pragma: no-cache');
    header('X-Robots-Tag: noindex, nofollow', true);
    header('Referrer-Policy: no-referrer-when-downgrade');
    header('Location: ' . $targetUrl, true, 302);
    exit;
}

/** Zápis prokliku. Nesmí shodit ani zdržet odchod do obchodu. */
function logAffiliateClick(array $click): void {
    if (empty($click)) {
        return;
    }
    try {
        if (!runtimeTableExists('clicks')) {
            return;
        }
        db()->query(
            "INSERT INTO clicks (product_id, offer_id, feed_id, cta_position, source_url, referrer, user_agent)
             VALUES (?,?,?,?,?,?,?)",
            [
                $click['product_id'] ?? null,
                $click['offer_id'] ?? null,
                $click['feed_id'] ?? null,
                substr((string)($_GET['pos'] ?? ''), 0, 32) ?: null,
                substr((string)($_SERVER['REQUEST_URI'] ?? ''), 0, 500),
                substr((string)($_SERVER['HTTP_REFERER'] ?? ''), 0, 500) ?: null,
                substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255) ?: null,
            ]
        );
    } catch (Throwable $e) {
        // měření nikdy nesmí zabránit prokliku
    }
}

// Maskovaný externí odkaz: /r/go/<slug> (tabulka redirects, old_url = '/r/go/<slug>')
$link = trim((string)($_GET['link'] ?? ''));
if ($link !== '') {
    $row = preg_match('/^[a-z0-9-]+$/i', $link)
        ? db()->queryOne("SELECT id, new_url, type FROM redirects WHERE old_url = ? LIMIT 1", ['/r/go/' . strtolower($link)])
        : null;
    if ($row && trim((string)$row['new_url']) !== '') {
        db()->query("UPDATE redirects SET hit_count = hit_count + 1 WHERE id = ?", [$row['id']]);
        redirect($row['new_url'], (int)$row['type'] === 301);
    }
    include __DIR__ . '/404.php';
    exit;
}

$offerId = (int)($_GET['offer_id'] ?? 0);
$productId = (int)($_GET['id'] ?? 0);

if ($offerId > 0) {
    $offer = db()->queryOne(
        "SELECT po.id, po.product_id, po.feed_id, po.affiliate_url, po.url, p.slug
         FROM product_offers po
         JOIN products p ON p.id = po.product_id
         WHERE po.id = ? AND p.visible = 1
         LIMIT 1",
        [$offerId]
    );
    if (!$offer) {
        include __DIR__ . '/404.php';
        exit;
    }

    $targetUrl = trim((string)($offer['affiliate_url'] ?: $offer['url']));
    if ($targetUrl !== '') {
        affiliateExit($targetUrl, [
            'product_id' => (int)$offer['product_id'],
            'offer_id' => (int)$offer['id'],
            'feed_id' => (int)$offer['feed_id'],
        ]);
    }

    redirect(urlProdukt($offer['slug']));
}

if ($productId <= 0) {
    include __DIR__ . '/404.php';
    exit;
}

$product = db()->queryOne("SELECT id, slug, affiliate_url FROM products WHERE id = ? AND visible = 1 LIMIT 1", [$productId]);
if (!$product) {
    include __DIR__ . '/404.php';
    exit;
}

$targetUrl = trim((string)($product['affiliate_url'] ?? ''));
if ($targetUrl === '') {
    $offer = db()->queryOne(
        "SELECT id, feed_id, affiliate_url, url
         FROM product_offers
         WHERE product_id = ?
         ORDER BY in_stock DESC, price_vat ASC, id ASC
         LIMIT 1",
        [$productId]
    );
    if ($offer) {
        $targetUrl = trim((string)($offer['affiliate_url'] ?: $offer['url']));
        $clickOfferId = (int)$offer['id'];
        $clickFeedId = (int)$offer['feed_id'];
    }
}

if ($targetUrl !== '') {
    affiliateExit($targetUrl, [
        'product_id' => $productId,
        'offer_id' => $clickOfferId ?? null,
        'feed_id' => $clickFeedId ?? null,
    ]);
}

redirect(urlProdukt($product['slug']));
