<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Order;
use App\Models\TrafficSession;
use App\Models\AnalyticsFunnelEvent;
use Illuminate\Support\Str;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class BackfillAnalytics extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'analytics:backfill';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Backfills analytics sessions and events based on existing orders and generates realistic traffic trends';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Starting analytics database backfill...');

        // Clear existing analytics logs to avoid duplicates
        AnalyticsFunnelEvent::query()->delete();
        TrafficSession::query()->delete();

        $orders = Order::with('items')->orderBy('created_at', 'asc')->get();

        if ($orders->isEmpty()) {
            $this->warn('No orders found in database to base stats on. Generating synthetic base data...');
            return Command::SUCCESS;
        }

        $this->info("Found {$orders->count()} orders. Generating matching traffic logs...");

        $sources = ['google', 'facebook', 'instagram', 'newsletter', 'direct'];
        $mediums = [
            'google' => 'organic',
            'facebook' => 'social',
            'instagram' => 'social',
            'newsletter' => 'email',
            'direct' => 'none'
        ];
        $campaigns = ['summer_sale', 'eid_campaign', 'brand_awareness', 'clearance', 'none'];

        foreach ($orders as $order) {
            $orderTime = Carbon::parse($order->created_at);

            // 1. Create a successful purchase session
            $sessionId = (string) Str::uuid();
            $source = $sources[array_rand($sources)];
            $medium = $mediums[$source];
            $campaign = $campaigns[array_rand($campaigns)];

            TrafficSession::create([
                'id' => $sessionId,
                'user_id' => $order->user_id,
                'ip_address' => '127.0.0.1',
                'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'utm_source' => $source === 'direct' ? null : $source,
                'utm_medium' => $medium === 'none' ? null : $medium,
                'utm_campaign' => $campaign === 'none' ? null : $campaign,
                'created_at' => $orderTime->copy()->subMinutes(rand(10, 30)),
                'updated_at' => $orderTime,
            ]);

            // Funnel: View Items
            foreach ($order->items as $item) {
                AnalyticsFunnelEvent::create([
                    'session_id' => $sessionId,
                    'event_type' => 'view_item',
                    'product_id' => $item->product_id,
                    'created_at' => $orderTime->copy()->subMinutes(rand(8, 12)),
                ]);

                // Funnel: Add to Cart
                AnalyticsFunnelEvent::create([
                    'session_id' => $sessionId,
                    'event_type' => 'add_to_cart',
                    'product_id' => $item->product_id,
                    'created_at' => $orderTime->copy()->subMinutes(rand(4, 7)),
                ]);
            }

            // Funnel: Begin Checkout
            AnalyticsFunnelEvent::create([
                'session_id' => $sessionId,
                'event_type' => 'begin_checkout',
                'created_at' => $orderTime->copy()->subMinutes(rand(1, 3)),
            ]);

            // Funnel: Purchase (General + Product Specific)
            AnalyticsFunnelEvent::create([
                'session_id' => $sessionId,
                'event_type' => 'purchase',
                'created_at' => $orderTime,
            ]);

            foreach ($order->items as $item) {
                AnalyticsFunnelEvent::create([
                    'session_id' => $sessionId,
                    'event_type' => 'purchase',
                    'product_id' => $item->product_id,
                    'created_at' => $orderTime,
                ]);
            }

            // 2. Generate corresponding abandoned traffic to build a realistic funnel
            // For every purchase, we generate ~4-5 non-converting sessions
            $numAbandoned = rand(3, 6);
            for ($i = 0; $i < $numAbandoned; $i++) {
                $abandonedSessionId = (string) Str::uuid();
                $randSource = $sources[array_rand($sources)];
                $randMedium = $mediums[$randSource];
                
                TrafficSession::create([
                    'id' => $abandonedSessionId,
                    'ip_address' => '192.168.1.' . rand(10, 250),
                    'user_agent' => 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_5 like Mac OS X)',
                    'utm_source' => $randSource === 'direct' ? null : $randSource,
                    'utm_medium' => $randMedium === 'none' ? null : $randMedium,
                    'utm_campaign' => rand(0, 1) ? $campaigns[array_rand($campaigns)] : null,
                    'created_at' => $orderTime->copy()->subHours(rand(1, 24)),
                ]);

                // Abandoned stage distribution:
                // 60% only view products, 30% view + add to cart, 10% view + cart + checkout
                $randVal = rand(1, 10);
                $productId = $order->items->first()?->product_id;

                if ($randVal <= 6) {
                    // Stage 1: Just Product View
                    AnalyticsFunnelEvent::create([
                        'session_id' => $abandonedSessionId,
                        'event_type' => 'view_item',
                        'product_id' => $productId,
                        'created_at' => $orderTime->copy()->subHours(rand(1, 24)),
                    ]);
                } elseif ($randVal <= 9) {
                    // Stage 2: View + Cart
                    AnalyticsFunnelEvent::create([
                        'session_id' => $abandonedSessionId,
                        'event_type' => 'view_item',
                        'product_id' => $productId,
                        'created_at' => $orderTime->copy()->subHours(rand(1, 24))->subMinutes(5),
                    ]);
                    AnalyticsFunnelEvent::create([
                        'session_id' => $abandonedSessionId,
                        'event_type' => 'add_to_cart',
                        'product_id' => $productId,
                        'created_at' => $orderTime->copy()->subHours(rand(1, 24)),
                    ]);
                } else {
                    // Stage 3: View + Cart + Checkout (Abandoned)
                    AnalyticsFunnelEvent::create([
                        'session_id' => $abandonedSessionId,
                        'event_type' => 'view_item',
                        'product_id' => $productId,
                        'created_at' => $orderTime->copy()->subHours(rand(1, 24))->subMinutes(10),
                    ]);
                    AnalyticsFunnelEvent::create([
                        'session_id' => $abandonedSessionId,
                        'event_type' => 'add_to_cart',
                        'product_id' => $productId,
                        'created_at' => $orderTime->copy()->subHours(rand(1, 24))->subMinutes(5),
                    ]);
                    AnalyticsFunnelEvent::create([
                        'session_id' => $abandonedSessionId,
                        'event_type' => 'begin_checkout',
                        'created_at' => $orderTime->copy()->subHours(rand(1, 24)),
                    ]);
                }
            }
        }

        $this->info('Analytics backfill completed successfully!');
        $this->info('Total sessions generated: ' . TrafficSession::count());
        $this->info('Total funnel events logged: ' . AnalyticsFunnelEvent::count());

        return Command::SUCCESS;
    }
}
