<?php

namespace App\Filament\Widgets;

use Filament\Widgets\Widget;
use App\Models\TrafficSession;
use App\Models\AnalyticsFunnelEvent;

class ConversionFunnelWidget extends Widget
{
    protected string $view = 'filament.widgets.conversion-funnel-widget';

    protected static ?int $sort = 1;

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

    protected function getViewData(): array
    {
        $days = 30;
        $startDate = now()->subDays($days);

        // Funnel Stats
        $totalSessions = TrafficSession::where('created_at', '>=', $startDate)->count();

        $productViews = AnalyticsFunnelEvent::where('event_type', 'view_item')
            ->where('created_at', '>=', $startDate)
            ->distinct('session_id')
            ->count('session_id');

        $addToCarts = AnalyticsFunnelEvent::where('event_type', 'add_to_cart')
            ->where('created_at', '>=', $startDate)
            ->distinct('session_id')
            ->count('session_id');

        $checkouts = AnalyticsFunnelEvent::where('event_type', 'begin_checkout')
            ->where('created_at', '>=', $startDate)
            ->distinct('session_id')
            ->count('session_id');

        $purchases = AnalyticsFunnelEvent::where('event_type', 'purchase')
            ->where('created_at', '>=', $startDate)
            ->distinct('session_id')
            ->count('session_id');

        // Conversion Rates
        $viewRate = $totalSessions > 0 ? ($productViews / $totalSessions) * 100 : 0;
        $cartRate = $totalSessions > 0 ? ($addToCarts / $totalSessions) * 100 : 0;
        $checkoutRate = $totalSessions > 0 ? ($checkouts / $totalSessions) * 100 : 0;
        $purchaseRate = $totalSessions > 0 ? ($purchases / $totalSessions) * 100 : 0;

        return [
            'totalSessions' => $totalSessions,
            'productViews' => $productViews,
            'addToCarts' => $addToCarts,
            'checkouts' => $checkouts,
            'purchases' => $purchases,
            'viewRate' => number_format($viewRate, 1),
            'cartRate' => number_format($cartRate, 1),
            'checkoutRate' => number_format($checkoutRate, 1),
            'purchaseRate' => number_format($purchaseRate, 1),
        ];
    }
}
