<?php

class MQTTTracker
{
    private ?CMSAPI $api = null;
    private array $config;
    private string $sessionId;
    
    public function __construct()
    {
        $this->loadConfig();
        $this->sessionId = $this->generateSessionId();
        
        // Track page visit
        $this->trackPageVisit();
    }
    
    public function setAPI(CMSAPI $api): void
    {
        $this->api = $api;
    }
    
    private function loadConfig(): void
    {
        $configFile = __DIR__ . '/config.json';
        $this->config = [
            'enabled' => true,
            'broker_host' => 'localhost',
            'broker_port' => 1883,
            'client_id' => 'codepress_cms',
            'username' => '',
            'password' => '',
            'topic_prefix' => 'codepress',
            'track_visitors' => true,
            'track_pages' => true,
            'track_performance' => true,
            'session_timeout' => 1800
        ];
        
        if (file_exists($configFile)) {
            $jsonConfig = json_decode(file_get_contents($configFile), true);
            $this->config = array_merge($this->config, $jsonConfig);
        }
    }
    
    private function generateSessionId(): string
    {
        if (isset($_COOKIE['cms_session_id'])) {
            return $_COOKIE['cms_session_id'];
        }
        
        $sessionId = uniqid('cms_', true);
        setcookie('cms_session_id', $sessionId, time() + $this->config['session_timeout'], '/');
        return $sessionId;
    }
    
    private function trackPageVisit(): void
    {
        if (!$this->config['enabled'] || !$this->config['track_pages']) {
            return;
        }
        
        $pageData = [
            'timestamp' => date('c'),
            'session_id' => $this->sessionId,
            'page_url' => $_SERVER['REQUEST_URI'] ?? '',
            'page_title' => $this->api ? $this->api->getCurrentPageTitle() : '',
            'referrer' => $_SERVER['HTTP_REFERER'] ?? '',
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
            'ip_address' => $this->getClientIp(),
            'language' => $this->api ? $this->api->getCurrentLanguage() : 'nl',
            'layout' => $this->api ? $this->getPageLayout() : 'unknown'
        ];
        
        $this->publishMessage('page_visit', $pageData);
    }
    
    private function getPageLayout(): string
    {
        if (!$this->api) return 'unknown';
        
        $page = $this->api->getCurrentPage();
        return $page['layout'] ?? 'sidebar-content';
    }
    
    private function getClientIp(): string
    {
        $ipKeys = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'];
        
        foreach ($ipKeys as $key) {
            if (!empty($_SERVER[$key])) {
                $ips = explode(',', $_SERVER[$key]);
                return trim($ips[0]);
            }
        }
        
        return 'unknown';
    }
    
    private function publishMessage(string $topic, array $data): void
    {
        if (!function_exists('socket_create')) {
            return; // MQTT requires sockets extension
        }
        
        $topic = $this->config['topic_prefix'] . '/' . $topic;
        $payload = json_encode($data);
        
        // Simple MQTT-like publish (would need proper MQTT client library)
        $this->logMessage($topic, $payload);
    }
    
    private function logMessage(string $topic, string $payload): void
    {
        $logFile = __DIR__ . '/mqtt_tracker.log';
        $logEntry = date('Y-m-d H:i:s') . " [{$topic}] {$payload}\n";
        file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
    }
    
    public function getSidebarContent(): string
    {
        // MQTT Tracker is een functionele plugin zonder UI
        return '';
    }
    
    
    
    public function getConfig(): array
    {
        return $this->config;
    }
    
    public function updateConfig(array $newConfig): void
    {
        $this->config = array_merge($this->config, $newConfig);
        
        $configFile = __DIR__ . '/config.json';
        file_put_contents($configFile, json_encode($this->config, JSON_PRETTY_PRINT));
    }
}