<?php

namespace App\Filament\Widgets;

use Filament\Widgets\Widget;
use App\Models\TrafficSession;
use Illuminate\Support\Facades\Schema;

class LiveTrafficWidget extends Widget
{
    protected string $view = 'filament.widgets.live-traffic-widget';

    protected static ?int $sort = 0;

    protected int | string | array $columnSpan = 'full';

    public bool $showModal = false;

    public function openModal()
    {
        $this->showModal = true;
    }

    public function closeModal()
    {
        $this->showModal = false;
    }

    protected function getViewData(): array
    {
        $activeCount = 0;
        $activeSessionsList = [];

        if (Schema::hasTable('traffic_sessions')) {
            $activeCount = TrafficSession::where('updated_at', '>=', now()->subMinutes(5))->count();

            if ($this->showModal) {
                $sessions = TrafficSession::where('updated_at', '>=', now()->subMinutes(5))
                    ->orderBy('updated_at', 'desc')
                    ->get();

                foreach ($sessions as $session) {
                    $latestEvent = \App\Models\AnalyticsFunnelEvent::where('session_id', $session->id)
                        ->orderBy('created_at', 'desc')
                        ->with('product')
                        ->first();

                    $action = 'Browsing Storefront';
                    if ($latestEvent) {
                        $action = match ($latestEvent->event_type) {
                            'view_item' => $latestEvent->product ? "Viewing: {$latestEvent->product->name}" : "Viewing Product",
                            'add_to_cart' => $latestEvent->product ? "Added to Cart: {$latestEvent->product->name}" : "Added Item to Cart",
                            'begin_checkout' => "Checking Out",
                            'purchase' => "Completed Purchase 🎉",
                            'browse_home' => "Viewing Home Page",
                            'browse_shop' => "Browsing Shop",
                            'browse_categories' => "Viewing Categories",
                            'browse_contact' => "Viewing Contact Page",
                            'browse_dashboard' => "Viewing Customer Dashboard",
                            default => "Browsing Storefront",
                        };
                    }

                    // Simple User-Agent parsing
                    $ua = $session->user_agent ?? '';
                    $device = 'Desktop';
                    if (preg_match('/(ipad|tablet|playbook|silk)|(android(?!.*mobile))/i', $ua)) {
                        $device = 'Tablet';
                    } elseif (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android|iemobile|iphone)/i', $ua)) {
                        $device = 'Mobile';
                    }

                    $activeSessionsList[] = [
                        'ip' => $session->ip_address ?? 'Unknown IP',
                        'device' => $device,
                        'source' => $session->utm_source ?? 'Direct Traffic',
                        'action' => $action,
                        'last_active' => $session->updated_at->diffForHumans(),
                    ];
                }
            }
        }

        return [
            'activeCount' => $activeCount,
            'activeSessionsList' => $activeSessionsList,
        ];
    }
}
