<?php

namespace App\Services;

use App\Models\TrafficSession;
use App\Models\AnalyticsFunnelEvent;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Schema;

class AnalyticsLoggingService
{
    /**
     * Get or initialize the traffic session UUID.
     */
    public static function getCurrentSessionId(): ?string
    {
        if (app()->runningInConsole()) {
            return null;
        }

        // Avoid tracking admin requests
        if (request()->is('admin') || request()->is('admin/*')) {
            return null;
        }

        $sessionId = session()->get('traffic_session_id');

        if (!$sessionId) {
            $sessionId = (string) Str::uuid();

            if (Schema::hasTable('traffic_sessions')) {
                try {
                    TrafficSession::create([
                        'id' => $sessionId,
                        'user_id' => auth()->id(),
                        'ip_address' => request()->ip(),
                        'user_agent' => request()->userAgent(),
                        'utm_source' => request()->query('utm_source'),
                        'utm_medium' => request()->query('utm_medium'),
                        'utm_campaign' => request()->query('utm_campaign'),
                    ]);

                    session()->put('traffic_session_id', $sessionId);
                } catch (\Exception $e) {
                    \Illuminate\Support\Facades\Log::error('Failed to create traffic session: ' . $e->getMessage());
                    return null;
                }
            } else {
                return null;
            }
        } else {
            if (Schema::hasTable('traffic_sessions')) {
                try {
                    $session = TrafficSession::find($sessionId);
                    if ($session) {
                        $session->touch();
                        if (auth()->check() && !$session->user_id) {
                            $session->update(['user_id' => auth()->id()]);
                        }
                    }
                } catch (\Exception $e) {
                    \Illuminate\Support\Facades\Log::error('Failed to update traffic session activity: ' . $e->getMessage());
                }
            }
        }

        return $sessionId;
    }

    /**
     * Log a funnel event.
     */
    public static function logEvent(string $eventType, ?int $productId = null): void
    {
        $sessionId = self::getCurrentSessionId();
        if (!$sessionId) {
            return;
        }

        if (Schema::hasTable('analytics_funnel_events')) {
            try {
                AnalyticsFunnelEvent::create([
                    'session_id' => $sessionId,
                    'event_type' => $eventType,
                    'product_id' => $productId,
                ]);
            } catch (\Exception $e) {
                \Illuminate\Support\Facades\Log::error('Failed to log funnel event: ' . $e->getMessage());
            }
        }
    }
}
