<?php

namespace Licenzo\Services\Logging\Concerns;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

use Licenzo\App;
use Licenzo\Framework\Http\Request;

/**
 * Trait CapturesContext
 *
 * Automatically captures request context like IP, user agent, user ID, and source
 */
trait CapturesContext
{
    /**
     * Get client IP address
     */
    protected static function getClientIp(): ?string
    {
        return \Licenzo\Helper\Helper::getClientIp();
    }

    /**
     * Get user agent from request
     */
    protected static function getUserAgent(): ?string
    {
        return App::request()->userAgent();
    }

    /**
     * Get current WordPress user ID
     */
    protected static function getCurrentUserId(): ?int
    {
        $userId = get_current_user_id();
        return $userId ?: null;
    }

    /**
     * Auto-detect event source based on context
     */
    protected static function detectSource(): string
    {
        // REST API request
        if (defined('REST_REQUEST') && REST_REQUEST) {
            return 'api';
        }

        // Cron job
        if (defined('DOING_CRON') && DOING_CRON) {
            return 'cron';
        }

        // Admin area with logged-in user
        if (is_admin() && static::getCurrentUserId()) {
            return 'admin';
        }

        // AJAX request
        if (defined('DOING_AJAX') && DOING_AJAX) {
            return 'ajax';
        }

        // Default to system
        return 'system';
    }

    /**
     * Capture all HTTP headers
     */
    protected static function captureHeaders(): array
    {
        /**
         * @var $request Request
        */
        $request = App::request();

        $requestHeader = $request->header();
        $headers = [];
        foreach ($requestHeader as $key => $value) {
            if (str_starts_with($key, 'HTTP_')) {
                $header = str_replace('_', '-', substr($key, 5));
                $headers[$header] = $value;
            }
        }
        return $headers;
    }

    /**
     * Extract headers from Request object
     */
    protected static function extractHeaders(?Request $request): array
    {
        if (!$request) {
            return static::captureHeaders();
        }

        // If Request has headers property
        if (method_exists($request, 'headers') && is_object($request->headers)) {
            return $request->headers();
        }

        // Fallback to manual capture
        return static::captureHeaders();
    }

    /**
     * Extract instance identifier from request
     */
    protected static function extractInstanceIdentifier(?Request $request): ?string
    {
        if (!$request) {
            return null;
        }

        return $request->input('instance_identifier')
            ?? $request->input('instance')
            ?? $request->input('domain')
            ?? null;
    }

    /**
     * Extract request hash from request
     */
    protected static function extractRequestHash(?Request $request): ?string
    {
        if (!$request) {
            return null;
        }

        return $request->input('hash')
            ?? $request->input('request_hash')
            ?? $request->header('X-License-Hash')
            ?? null;
    }
}

