<?php
// src/controllers/AnonymousController.php
declare(strict_types=1);

final class AnonymousController
{
    public static function trackAdClick(): void
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

        $ad_id = $_GET['id'] ?? '';
        if (!$ad_id) {
            self::safeRedirect('./?r=dashboard');
            return;
        }

        // Core deps
        require_once __DIR__ . '/../Database.php';
        require_once __DIR__ . '/../config.php';
        require_once __DIR__ . '/../helpers.php';
        // Optional SecurityHelper (usually lives in src/helpers/SecurityHelper.php)
        $sec = __DIR__ . '/../helpers/SecurityHelper.php';
        if (file_exists($sec)) {
            require_once $sec;
        }

        $CONFIG = include __DIR__ . '/../config.php';

        try {
            $db = Database::getConnection($CONFIG);

            $stmt = $db->prepare('SELECT id, target_url FROM ads WHERE id = ? LIMIT 1');
            $stmt->execute([$ad_id]);
            $ad = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$ad) {
                self::safeRedirect('./?r=dashboard');
                return;
            }

            // Normalizar URL destino
            $target = trim((string)($ad['target_url'] ?? ''));
            if ($target !== '' && !preg_match('~^https?://~i', $target)) {
                $target = 'https://' . $target;
            }
            if ($target === '') {
                self::safeRedirect('./?r=dashboard');
                return;
            }

            // Sumar clic (sin last_click, acorde a tu esquema)
            try {
                $upd = $db->prepare('UPDATE ads SET clicks = clicks + 1 WHERE id = ?');
                $upd->execute([$ad_id]);

                // Log opcional si existe ad_clicks
                try {
                    $user_id = $_SESSION['user']['id'] ?? null;
                    $ip = get_client_ip();
                    $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
                    $log = $db->prepare('INSERT INTO ad_clicks (ad_id, user_id, ip, user_agent, created_at) VALUES (?, ?, ?, ?, NOW())');
                    $log->execute([$ad_id, $user_id, $ip, $ua]);
                } catch (Throwable $t) {}
            } catch (Throwable $t) {}

            self::safeRedirect($target);
            return;

        } catch (Throwable $e) {
            self::safeRedirect('./?r=dashboard');
            return;
        }
    }

    public static function trackAdClickPost(): void
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        header('Content-Type: application/json');
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Método no permitido']);
            return;
        }
        $ad_id = $_POST['id'] ?? '';
        if (!$ad_id) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'ID de anuncio no válido']);
            return;
        }

        require_once __DIR__ . '/../Database.php';
        require_once __DIR__ . '/../config.php';
        require_once __DIR__ . '/../helpers.php';
        $sec = __DIR__ . '/../helpers/SecurityHelper.php';
        if (file_exists($sec)) {
            require_once $sec;
        }
        $CONFIG = include __DIR__ . '/../config.php';

        try {
            $db = Database::getConnection($CONFIG);

            $check = $db->prepare('SELECT id FROM ads WHERE id = ?');
            $check->execute([$ad_id]);
            if (!$check->fetch()) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Anuncio no encontrado']);
                return;
            }

            $upd = $db->prepare('UPDATE ads SET clicks = clicks + 1 WHERE id = ?');
            $ok  = $upd->execute([$ad_id]);

            if ($ok) {
                $cnt = $db->prepare('SELECT clicks FROM ads WHERE id = ?');
                $cnt->execute([$ad_id]);
                $row = $cnt->fetch(PDO::FETCH_ASSOC);

                // Log opcional silencioso
                try {
                    $user_id = $_SESSION['user']['id'] ?? null;
                    $ip = get_client_ip();
                    $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
                    $log = $db->prepare('INSERT INTO ad_clicks (ad_id, user_id, ip, user_agent, created_at) VALUES (?, ?, ?, ?, NOW())');
                    $log->execute([$ad_id, $user_id, $ip, $ua]);
                } catch (Throwable $t) {}

                echo json_encode(['success' => true, 'clicks' => (int)($row['clicks'] ?? 0)]);
            } else {
                http_response_code(500);
                echo json_encode(['success' => false, 'message' => 'No se pudo registrar el clic']);
            }
        } catch (Throwable $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Error interno']);
        }
    }

    public static function refreshAdStatuses(): void
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            header('Content-Type: application/json');
            echo json_encode(['success' => true]);
        } else {
            self::safeRedirect('./?r=admin/ads');
        }
        exit;
    }

    private static function safeRedirect(string $url): void
    {
        if (function_exists('ob_get_level')) {
            while (ob_get_level() > 0) {
                ob_end_clean();
            }
        }
        header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
        header('Pragma: no-cache');
        header('Location: ' . $url, true, 302);
        echo '<!doctype html><html><head><meta http-equiv="refresh" content="0;url=' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '"></head>';
        echo '<body><noscript><a href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '">Continuar</a></noscript>';
        echo '<script>try{window.location.replace(' . json_encode($url) . ');}catch(e){window.location.href=' . json_encode($url) . ';}</script></body></html>';
        exit;
    }
}
