<?php
/**
 * Base Analytics Class
 * Provides common functionality for all analytics modules
 */

class SEOAnalyticsBase {
    protected $config;
    protected $cache_dir;
    protected $log_file;
    protected $db;

    public function __construct($config = null) {
        if (!$config) {
            $config = include __DIR__ . '/config.php';
        }
        $this->config = $config;
        $this->cache_dir = __DIR__ . '/../../cache/seo_analytics/';
        $this->log_file = __DIR__ . '/../../logs/seo_analytics.log';
        $this->ensureDirectories();
    }

    /**
     * Ensure required directories exist
     */
    private function ensureDirectories() {
        if (!is_dir($this->cache_dir)) {
            mkdir($this->cache_dir, 0755, true);
        }
    }

    /**
     * Get cached data
     */
    protected function getCache($key) {
        $file = $this->cache_dir . md5($key) . '.cache';
        if (file_exists($file)) {
            $data = unserialize(file_get_contents($file));
            if ($data['expires'] > time()) {
                return $data['value'];
            } else {
                unlink($file);
            }
        }
        return null;
    }

    /**
     * Set cached data
     */
    protected function setCache($key, $value, $ttl = null) {
        if ($ttl === null) {
            $ttl = $this->config['general']['cache_ttl'];
        }
        $file = $this->cache_dir . md5($key) . '.cache';
        $data = [
            'value' => $value,
            'expires' => time() + $ttl,
        ];
        file_put_contents($file, serialize($data));
        return true;
    }

    /**
     * Make HTTPS request
     */
    protected function makeRequest($url, $method = 'GET', $headers = [], $data = null) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        
        if ($data) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }

        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error) {
            $this->log("Request error: $error", 'error');
            return ['error' => $error, 'code' => 0];
        }

        $this->log("Request: $method $url - Response: $http_code", 'debug');
        
        return [
            'data' => json_decode($response, true),
            'code' => $http_code,
            'raw' => $response,
        ];
    }

    /**
     * Log messages
     */
    protected function log($message, $level = 'info') {
        if (!$this->config['general']['log_requests'] && $level === 'debug') {
            return;
        }
        $timestamp = date('Y-m-d H:i:s');
        $log_message = "[$timestamp] [$level] $message\n";
        error_log($log_message, 3, $this->log_file);
    }

    /**
     * Rate limiting check
     */
    protected function checkRateLimit($identifier) {
        $limit_file = $this->cache_dir . 'rate_limit_' . md5($identifier) . '.txt';
        $max_requests = $this->config['general']['rate_limit'];
        $time_window = 3600; // 1 hour

        if (file_exists($limit_file)) {
            $data = json_decode(file_get_contents($limit_file), true);
            if ($data['time'] > time() - $time_window) {
                if ($data['count'] >= $max_requests) {
                    return false;
                }
                $data['count']++;
                file_put_contents($limit_file, json_encode($data));
                return true;
            }
        }

        file_put_contents($limit_file, json_encode(['count' => 1, 'time' => time()]));
        return true;
    }

    /**
     * Format data for API response
     */
    protected function formatResponse($data, $status = 'success', $message = '') {
        return [
            'status' => $status,
            'message' => $message,
            'data' => $data,
            'timestamp' => date('c'),
        ];
    }

    /**
     * Get configuration value
     */
    protected function getConfig($path) {
        $keys = explode('.', $path);
        $value = $this->config;
        foreach ($keys as $key) {
            if (isset($value[$key])) {
                $value = $value[$key];
            } else {
                return null;
            }
        }
        return $value;
    }
}
?>
