<?php
namespace WalletUpPro\Core\Security;

use WalletUpPro\Services\DatabaseManager;
use WalletUpPro\Core\Error\ErrorHandler;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

class AuditLogger
{
    private $db;
    private $errorHandler;

    public function __construct(\WalletUpPro\Core\Database\DatabaseManager $db, ErrorHandler $errorHandler)
    {
        $this->db = $db;
        $this->errorHandler = $errorHandler;
    }

    public function logSecurityEvent(string $event, array $data = []): void
    {
        try {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Write operation, caching not applicable.
            $this->db->insert('wallet_up_security_log', [
                'event' => $event,
                'user_id' => get_current_user_id(),
                'ip_address' => $this->getClientIP(),
                'data' => wp_json_encode($data),
                'created_at' => current_time('mysql')
            ]);
        } catch (\Exception $e) {
            $this->errorHandler->log('Security event logging failed: ' . $e->getMessage());
        }
    }

    private function getClientIP(): string
    {
        $ipKeys = [
            'HTTP_CLIENT_IP',
            'HTTP_X_FORWARDED_FOR',
            'HTTP_X_FORWARDED',
            'HTTP_X_CLUSTER_CLIENT_IP',
            'HTTP_FORWARDED_FOR',
            'HTTP_FORWARDED',
            'REMOTE_ADDR'
        ];

        foreach ($ipKeys as $key) {
            if (isset($_SERVER[$key])) {
                $ip = filter_var(sanitize_text_field(wp_unslash($_SERVER[$key])), FILTER_VALIDATE_IP);
                if ($ip !== false) {
                    return $ip;
                }
            }
        }

        return '0.0.0.0';
    }

    public function getSecurityLogs(array $filters = []): array
    {
        try {
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table name is safely derived from wpdb prefix.
            $query = "SELECT * FROM {$this->db->getTableName('security_log')} WHERE 1=1";
            $params = [];

            if (!empty($filters['user_id'])) {
                $query .= " AND user_id = %d";
                $params[] = $filters['user_id'];
            }

            if (!empty($filters['event'])) {
                $query .= " AND event = %s";
                $params[] = $filters['event'];
            }

            if (!empty($filters['date_from'])) {
                $query .= " AND created_at >= %s";
                $params[] = $filters['date_from'];
            }

            if (!empty($filters['date_to'])) {
                $query .= " AND created_at <= %s";
                $params[] = $filters['date_to'];
            }

            $query .= " ORDER BY created_at DESC";

            if (!empty($filters['limit'])) {
                $query .= " LIMIT %d";
                $params[] = $filters['limit'];
            }

            // Correct call to prepare and fetch results
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Prepared query with safe table name.
            return $this->db->getResults($this->db->prepare($query, $params));
        } catch (\Exception $e) {
            $this->errorHandler->log('Security log retrieval failed: ' . $e->getMessage());
            return [];
        }
    }
}