<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AnalyticsController extends Controller
{
    public function index(Request $request)
    {
        $user = auth()->user();
        $period = $request->input('period', '30days');
        
        // Helper Closure for Date Filtering
        $dateFilter = function($q) use ($period) {
            if ($period == 'today') {
                $q->whereDate('clicked_at', today());
            } elseif ($period == '7days') {
                $q->where('clicked_at', '>=', now()->subDays(6));
            } elseif ($period == '30days') {
                $q->where('clicked_at', '>=', now()->subDays(29));
            }
            // 'all' applies no filter
        };

        // Base query for user's clicks
        $clicksQuery = \App\Models\Click::whereHas('shortlink', function($q) use ($user) {
            $q->where('user_id', $user->id);
        });
        
        // Apply filter to base query
        $dateFilter($clicksQuery);

        // 1. Overview Stats
        $totalClicks = $clicksQuery->count();
        $uniqueClicks = (clone $clicksQuery)->where('is_unique', true)->count();
        $totalLinks = $user->shortlinks()->count();

        $stats = [
            'total_clicks' => $totalClicks,
            'unique_clicks' => $uniqueClicks,
            'total_links' => $totalLinks,
            'avg_clicks' => $totalLinks > 0 ? round($totalClicks / $totalLinks, 1) : 0
        ];

        // 2. Clicks Over Time Logic
        $chartQuery = \App\Models\Click::whereHas('shortlink', function($q) use ($user) {
            $q->where('user_id', $user->id);
        });

        $labels = [];
        $chartData = [];

        if ($period == 'today') {
            // Per Hour for Today
            $clicksData = $chartQuery->whereDate('clicked_at', today())
                ->selectRaw('HOUR(clicked_at) as hour, COUNT(*) as count')
                ->groupBy('hour')
                ->pluck('count', 'hour');
            
            for ($i = 0; $i <= 23; $i++) {
                $labels[] = sprintf('%02d:00', $i);
                $chartData[] = $clicksData[$i] ?? 0;
            }
        } elseif ($period == '7days') {
            // Last 7 Days
            $clicksData = $chartQuery->where('clicked_at', '>=', now()->subDays(6))
                ->selectRaw('DATE(clicked_at) as date, COUNT(*) as count')
                ->groupBy('date')
                ->pluck('count', 'date');

            for ($i = 6; $i >= 0; $i--) {
                $date = now()->subDays($i)->format('Y-m-d');
                $labels[] = now()->subDays($i)->format('d M');
                $chartData[] = $clicksData[$date] ?? 0;
            }
        } elseif ($period == 'all') {
            // Per Month (Last 12 Months as representation of All Time/Long Term)
             $clicksData = $chartQuery
                ->selectRaw('DATE_FORMAT(clicked_at, "%Y-%m") as month, COUNT(*) as count')
                ->groupBy('month')
                ->orderBy('month')
                ->pluck('count', 'month');

            // Generate labels for last 12 months or range present in DB? 
            // For UI consistency, let's show last 12 months
            for ($i = 11; $i >= 0; $i--) {
                $date = now()->subMonths($i)->format('Y-m');
                $labels[] = now()->subMonths($i)->format('M Y');
                $chartData[] = $clicksData[$date] ?? 0;
            }
        } else {
            // Default: 30 Days
            $clicksData = $chartQuery->where('clicked_at', '>=', now()->subDays(29))
                ->selectRaw('DATE(clicked_at) as date, COUNT(*) as count')
                ->groupBy('date')
                ->pluck('count', 'date');

            for ($i = 29; $i >= 0; $i--) {
                $date = now()->subDays($i)->format('Y-m-d');
                $labels[] = now()->subDays($i)->format('d M');
                $chartData[] = $clicksData[$date] ?? 0;
            }
        }

        // 3. Device Stats
        $devices = $this->getGroupedStats($user, 'device_type', $dateFilter);
        $totalDevices = $devices->sum('count');
        $devices->transform(function($item) use ($totalDevices) {
            $item->percentage = $totalDevices > 0 ? ($item->count / $totalDevices) * 100 : 0;
            return $item;
        });

        // 4. Browser Stats
        $browsers = $this->getGroupedStats($user, 'browser', $dateFilter);

        // 5. OS Stats
        $os = $this->getGroupedStats($user, 'os', $dateFilter);
        $totalOS = $os->sum('count');
        $os->transform(function($item) use ($totalOS) {
            $item->percentage = $totalOS > 0 ? ($item->count / $totalOS) * 100 : 0;
            return $item;
        });

        // 6. Country Stats
        $countries = $this->getGroupedStats($user, 'country', $dateFilter);
        $totalCountries = $countries->sum('count');
        $countries->transform(function($item) use ($totalCountries) {
            $item->percentage = $totalCountries > 0 ? ($item->count / $totalCountries) * 100 : 0;
            return $item;
        });

        // 7. City Stats
        $cities = $this->getGroupedStats($user, 'city', $dateFilter);
        $totalCities = $cities->sum('count');
        $cities->transform(function($item) use ($totalCities) {
            $item->percentage = $totalCities > 0 ? ($item->count / $totalCities) * 100 : 0;
            return $item;
        });

        // 8. Top Performing Links
        $topLinks = $user->shortlinks()
            ->withCount([
                'clicks' => $dateFilter, // Apply date filter to the main count
                'clicks as unique_clicks_count' => function($q) use($dateFilter) {
                    $dateFilter($q);
                    $q->where('is_unique', true);
                },
                'clicks as clicks_30_days_count' => function($q) {
                    $q->where('clicked_at', '>=', now()->subDays(30));
                },
                'clicks as clicks_7_days_count' => function($q) {
                    $q->where('clicked_at', '>=', now()->subDays(7));
                },
                'clicks as clicks_today_count' => function($q) {
                    $q->whereDate('clicked_at', now()->today());
                },
                'clicks as clicks_1_hour_count' => function($q) {
                    $q->where('clicked_at', '>=', now()->subHour());
                }
            ])
            ->with(['clicks' => function($q) {
                // Latest click info is always useful
                $q->latest('clicked_at')->limit(1)->select('shortlink_id', 'clicked_at', 'referer_url'); 
            }])
            ->having('clicks_count', '>', 0) // Only show links with clicks in this period
            ->orderByDesc('clicks_count')
            ->take(10)
            ->get();
            
        // Calculate Top Referrer and other stats for each link manually (efficient enough for 5 items)
        $topLinks->each(function($link) {
            // Get all referrers and group by domain
            $referrerStats = $link->clicks()
                ->select('referer_url', \DB::raw('count(*) as total'))
                ->whereNotNull('referer_url')
                ->groupBy('referer_url')
                ->orderByDesc('total')
                ->limit(100)
                ->get()
                ->groupBy(function($item) {
                    return parse_url($item->referer_url, PHP_URL_HOST) ?: 'Direct/Other';
                })
                ->map(function($group, $domain) {
                    return [
                        'source' => $domain, 
                        'count' => $group->sum('total')
                    ];
                })
                ->sortByDesc('count')
                ->values()
                ->take(5);
            
            $link->referrer_summary = $referrerStats;
            
            $link->top_referrer = $referrerStats->isNotEmpty() ? $referrerStats->first()['source'] : 'Direct/None';
            
            // Format latest referrer
            $latestClick = $link->clicks->first();
            $link->latest_referrer = $latestClick && $latestClick->referer_url 
                ? parse_url($latestClick->referer_url, PHP_URL_HOST) 
                : 'Direct/None';
            
            // Get top device
            $topDevice = $link->clicks()
                ->selectRaw('device_type, COUNT(*) as count')
                ->groupBy('device_type')
                ->orderByDesc('count')
                ->first();
            $link->top_device = $topDevice ? $topDevice->device_type : '-';
            $link->top_device_count = $topDevice ? $topDevice->count : 0;
            
            // Get top OS
            $topOS = $link->clicks()
                ->selectRaw('os, COUNT(*) as count')
                ->groupBy('os')
                ->orderByDesc('count')
                ->first();
            $link->top_os = $topOS ? $topOS->os : '-';
            $link->top_os_count = $topOS ? $topOS->count : 0;
            
            // Get top country
            $topCountry = $link->clicks()
                ->selectRaw('country, COUNT(*) as count')
                ->groupBy('country')
                ->orderByDesc('count')
                ->first();
            $link->top_country = $topCountry ? $topCountry->country : '-';
            $link->top_country_count = $topCountry ? $topCountry->count : 0;
            
            // Get top city
            $topCity = $link->clicks()
                ->selectRaw('city, COUNT(*) as count')
                ->groupBy('city')
                ->orderByDesc('count')
                ->first();
            $link->top_city = $topCity ? $topCity->city : '-';
            $link->top_city_count = $topCity ? $topCity->count : 0;
        });

        // 7. Today's Insights (New Sidebar Data)
        $todayClicksQuery = \App\Models\Click::whereHas('shortlink', function($q) use ($user) {
                $q->where('user_id', $user->id);
            })
            ->whereDate('clicked_at', now()->today());

        $todayStats = [
            'clicks' => $todayClicksQuery->count(),
            'unique_visitors' => $todayClicksQuery->where('is_unique', true)->count(),
            'top_link_today' => $user->shortlinks()
                ->whereHas('clicks', function($q) {
                    $q->whereDate('clicked_at', now()->today());
                })
                ->withCount(['clicks' => function($q) {
                    $q->whereDate('clicked_at', now()->today());
                }])
                ->orderByDesc('clicks_count')
                ->first()
        ];

        // 8. Smart Insights Generation
        $insightText = "Ayo bagikan link pertamamu untuk mendapatkan analisis canggih di sini!";
        $insightCandidates = [];

        // 1. Trending Now (Last 1 Hour) - PRIORITY HIGH
        $lastHourLink = $user->shortlinks()
            ->whereHas('clicks', fn($q) => $q->where('clicked_at', '>=', now()->subHour()))
            ->withCount(['clicks' => fn($q) => $q->where('clicked_at', '>=', now()->subHour())])
            ->orderByDesc('clicks_count')
            ->first();

        if ($lastHourLink && $lastHourLink->clicks_count > 3) {
            $linkName = $lastHourLink->custom_alias ?: $lastHourLink->short_code;
            $insightCandidates[] = [
                'type' => 'trending',
                'priority' => 10, // Highest priority
                'content' => "Link <strong>{$linkName}</strong> mendapatkan lonjakan <strong>{$lastHourLink->clicks_count} klik</strong> dalam satu jam terakhir. Momentum sedang bagus, bagikan lagi sekarang!" . 
                             "<a href='" . route('shortlinks.index') . "?search={$linkName}' class='block mt-3 text-xs font-semibold text-emerald-600 hover:text-emerald-700'>Lihat Detail <i class='fa-solid fa-arrow-right ml-1'></i></a>"
            ];
        }

        // 2. Top Source (Last 30 Days) - PRIORITY MEDIUM
        $topSource30Raw = \App\Models\Click::whereHas('shortlink', fn($q) => $q->where('user_id', $user->id))
            ->where('clicked_at', '>=', now()->subDays(30))
            ->whereNotNull('referer_url')
            ->selectRaw('referer_url, COUNT(*) as count')
            ->groupBy('referer_url')
            ->orderByDesc('count')
            ->first();

        if ($topSource30Raw) {
            $sourceName = parse_url($topSource30Raw->referer_url, PHP_URL_HOST);
            if ($sourceName) {
                $insightCandidates[] = [
                    'type' => 'source',
                    'priority' => 5,
                    'content' => "Dalam 30 hari terakhir, trafik terbanyak Anda berasal dari <strong>{$sourceName}</strong>. Bagikan lebih banyak link di sana!"
                ];
            }
        }

        // 3. Top Device (All Time) - PRIORITY MEDIUM
        $topDeviceRaw = \App\Models\Click::whereHas('shortlink', fn($q) => $q->where('user_id', $user->id))
            ->selectRaw('device_type, COUNT(*) as count')
            ->groupBy('device_type')
            ->orderByDesc('count')
            ->first();

        if ($topDeviceRaw) {
            $device = ucfirst($topDeviceRaw->device_type);
            $insightCandidates[] = [
                'type' => 'device',
                'priority' => 5,
                'content' => "Mayoritas pengunjung Anda menggunakan <strong>{$device}</strong>. Pastikan konten tujuan Anda nyaman dibuka di perangkat tersebut."
            ];
        }

        // 4. Weekly Recap (Standard) - PRIORITY LOW (Fallback)
        $weeklyClicksQuery = \App\Models\Click::whereHas('shortlink', fn($q) => $q->where('user_id', $user->id))
            ->where('clicked_at', '>=', now()->subDays(7));
        $weeklyCount = $weeklyClicksQuery->count();

        if ($weeklyCount > 0) {
             // Weekly Top Link
             $topLinkWeekly = $user->shortlinks()
                ->whereHas('clicks', fn($q) => $q->where('clicked_at', '>=', now()->subDays(7)))
                ->withCount(['clicks' => fn($q) => $q->where('clicked_at', '>=', now()->subDays(7))])
                ->orderByDesc('clicks_count')
                ->first();
             
             $recapContent = "Minggu ini Anda meraih total <strong>{$weeklyCount} klik</strong>.";
             if ($topLinkWeekly) {
                 $wLinkName = $topLinkWeekly->custom_alias ?: $topLinkWeekly->short_code;
                 $recapContent .= " Bintang minggu ini adalah <strong>{$wLinkName}</strong> dengan {$topLinkWeekly->clicks_count} klik.";
             }

             $insightCandidates[] = [
                'type' => 'weekly',
                'priority' => 1,
                'content' => $recapContent
            ];
        }

        // 5. Usage Tips (Non-Data Helpers) - PRIORITY LOW-MID
        $tips = [
            [
                'icon' => 'fa-calendar-days',
                'text' => "Anda bisa mengubah tampilan grafik statistik dari 30 hari menjadi 7 hari, hari ini, atau sepanjang masa melalui menu dropdown di pojok kanan atas grafik."
            ],
            [
                'icon' => 'fa-chart-pie',
                'text' => "Ingin tahu performa spesifik satu link? Cukup klik nama link pada widget 'Link Terpopuler' atau di halaman Daftar Link untuk membuka popup statistik lengkap."
            ],
            [
                'icon' => 'fa-pen-to-square',
                'text' => "Salah memasukkan URL tujuan? Jangan khawatir, Anda bisa mengeditnya kapan saja. Pergi ke menu <strong>Daftar Link</strong> lalu klik ikon pensil pada link yang ingin diubah."
            ],
            [
                'icon' => 'fa-wand-magic-sparkles',
                'text' => "Buat link Anda lebih unik dan mudah diingat dengan mengisi kolom 'Custom Alias' (opsional) saat membuat shortlink baru. Contoh: <code>domain.com/diskon-spesial</code>."
            ]
        ];

        // Randomly pick one tip to be a candidate
        $randomTip = $tips[array_rand($tips)];
        $insightCandidates[] = [
            'type' => 'tip',
            'priority' => 3, // slightly lower priority than data insights, but available to be picked
            'content' => $randomTip['text']
        ];

        // Selection Logic
        if (!empty($insightCandidates)) {
            // Sort by priority DESC
            usort($insightCandidates, fn($a, $b) => $b['priority'] <=> $a['priority']);

            // If top priority is trending (10), take it.
            if ($insightCandidates[0]['priority'] >= 10) {
                $insightText = $insightCandidates[0]['content'];
            } else {
                // Otherwise, shuffle ALL available candidates (Data insights + Tips)
                // This gives a mix of data analysis and helpful tips when there's no viral trend.
                $randomInsight = $insightCandidates[array_rand($insightCandidates)];
                $insightText = $randomInsight['content'];
            }
        }

        // 9. Recent Activities (Real-time clicks feed)
        $recentActivities = \App\Models\Click::with('shortlink')
            ->whereHas('shortlink', function($q) use ($user) {
                $q->where('user_id', $user->id);
            })
            ->latest('clicked_at')
            ->take(30)
            ->get();

        return view('dashboard.analytics.index', compact(
            'stats', 
            'labels', 
            'chartData', 
            'devices', 
            'browsers', 
            'os',
            'countries',
            'cities',
            'topLinks',
            'todayStats',
            'insightText',
            'recentActivities'
        ));
    }



    public function data(Request $request)
    {
        $search = $request->query('search');
        if (!$search) {
            return redirect()->route('analytics.index');
        }

        $user = auth()->user();
        
        // Find the shortlink
        $shortlink = $user->shortlinks()
            ->where(function($q) use ($search) {
                $q->where('short_code', $search)
                  ->orWhere('custom_alias', $search);
            })
            ->firstOrFail();

        // Base Clicks Query
        $clicksQuery = $shortlink->clicks();
        
        // Stats Summary
        $stats = [
            'total_clicks' => $clicksQuery->count(),
            'unique_clicks' => $clicksQuery->where('is_unique', true)->count(),
        ];

        // Chart Data (Last 30 Days)
        $labels = [];
        $chartData = [];
        for ($i = 29; $i >= 0; $i--) {
            $date = now()->subDays($i)->format('Y-m-d');
            $labels[] = now()->subDays($i)->format('d M');
            $chartData[] = $shortlink->clicks()
                ->whereDate('clicked_at', $date)
                ->count();
        }

        // Top Breakdown Helper
        $getBreakdown = function($col) use ($shortlink) {
            return $shortlink->clicks()
                ->selectRaw("$col, COUNT(*) as total")
                ->groupBy($col)
                ->orderByDesc('total')
                ->take(5)
                ->get();
        };

        $devices = $getBreakdown('device_type');
        $browsers = $getBreakdown('browser');
        $os_stats = $getBreakdown('os');
        $countries = $getBreakdown('country');
        $cities = $getBreakdown('city');

        // Extra Summary Stats
        $latestClick = $shortlink->clicks()->latest('clicked_at')->first();
        $lastClick = $latestClick ? $latestClick->clicked_at->diffForHumans() : 'Belum pernah';
        
        $clicks1Hour = $shortlink->clicks()->where('clicked_at', '>=', now()->subHour())->count();
        $dailyClicks = $shortlink->clicks()->where('clicked_at', '>=', today())->count();
        $weeklyClicks = $shortlink->clicks()->where('clicked_at', '>=', now()->subDays(6))->count();

        // Dynamic Period Stats (New Link vs Established)
        $isNewLink = $shortlink->created_at->diffInDays(now()) < 7;
        
        if ($isNewLink) {
            $periodLabel = "Hari ini";
            $periodContext = "hari ini";
            // Use today's clicks
            $mainStatsQuery = $shortlink->clicks()->whereDate('clicked_at', today());
        } else {
            $periodLabel = "Dalam 7 hari terakhir";
            $periodContext = "minggu ini";
            // Use last 7 days
            $mainStatsQuery = $shortlink->clicks()->where('clicked_at', '>=', now()->subDays(6));
        }
        
        $totalPeriodClicks = $mainStatsQuery->count();

        // Calculate Dominant Stats for this period
        $topSourcePeriod = (clone $mainStatsQuery)
            ->whereNotNull('referer_url')
            ->selectRaw('referer_url, COUNT(*) as total')
            ->groupBy('referer_url')
            ->orderByDesc('total')
            ->get()
            ->groupBy(function($item) {
                return parse_url($item->referer_url, PHP_URL_HOST) ?: 'Lainnya';
            })
            ->sortByDesc(fn($g) => $g->sum('total'))
            ->keys()
            ->first();

        $topDevicePeriod = (clone $mainStatsQuery)
            ->selectRaw('device_type, COUNT(*) as total')
            ->groupBy('device_type')
            ->orderByDesc('total')
            ->value('device_type');

        $topCityPeriod = (clone $mainStatsQuery)
            ->selectRaw('city, COUNT(*) as total')
            ->where('city', '!=', 'Unknown')
            ->groupBy('city')
            ->orderByDesc('total')
            ->value('city');

        $topCountryPeriod = (clone $mainStatsQuery)
            ->selectRaw('country, COUNT(*) as total')
            ->where('country', '!=', 'Unknown')
            ->groupBy('country')
            ->orderByDesc('total')
            ->value('country');

        // Recycle the variable name '$dominant7Days' to avoid breaking view for now (we'll update view text separately)
        // But cleaner to pass 'periodLabel' too.
        $dominant7Days = [
            'source' => $topSourcePeriod ?: 'Direct/Email/WA',
            'device' => $topDevicePeriod ?: '-',
            'city' => $topCityPeriod ?: '-',
            'country' => $topCountryPeriod ?: '-'
        ];

        // Advanced Insights (Percentages & Comparison)
        $insights = [];

        if ($totalPeriodClicks > 0) {
            // OS Insight
            $osBreakdown = (clone $mainStatsQuery)
                ->selectRaw('os, COUNT(*) as total')
                ->groupBy('os')
                ->orderByDesc('total')
                ->take(2)
                ->get();
            
            if ($osBreakdown->isNotEmpty()) {
                $topOS = $osBreakdown->first();
                $pctOS = round(($topOS->total / $totalPeriodClicks) * 100, 1);
                $insights['os'] = "Sistem operasi <strong>{$topOS->os}</strong> mendominasi dengan kontribusi <strong>{$pctOS}%</strong> dari total klik ({$periodContext}).";
            }

            // Device Insight
             $devBreakdown = (clone $mainStatsQuery)
                ->selectRaw('device_type, COUNT(*) as total')
                ->groupBy('device_type')
                ->orderByDesc('total')
                ->get();

             if ($devBreakdown->isNotEmpty()) {
                $topDev = $devBreakdown->first();
                $pctDev = round(($topDev->total / $totalPeriodClicks) * 100, 1);
                $insights['device'] = "Perangkat <strong>" . ucfirst($topDev->device_type) . "</strong> menjadi pilihan utama pengunjung, mendominasi <strong>{$pctDev}%</strong> ($periodLabel).";
             }

             // City/Location Insight
             $cityBreakdown = (clone $mainStatsQuery)
                ->where('city', '!=', 'Unknown')
                ->selectRaw('city, COUNT(*) as total')
                ->groupBy('city')
                ->orderByDesc('total')
                ->take(1)
                ->get();

             if ($cityBreakdown->isNotEmpty()) {
                 $topCity = $cityBreakdown->first();
                 $pctCity = round(($topCity->total / $totalPeriodClicks) * 100, 1);
                 $insights['location'] = "Dari segi geografis, <strong>{$topCity->city}</strong> adalah kota teraktif yang menyumbang <strong>{$pctCity}%</strong> kunjungan {$periodContext}.";
             }

             // Peak Time Insight
            $hourBreakdown = (clone $mainStatsQuery)
                ->selectRaw('HOUR(clicked_at) as hour, COUNT(*) as total')
                ->groupBy('hour')
                ->orderByDesc('total')
                ->first();

            if ($hourBreakdown) {
                $startHour = sprintf('%02d:00', $hourBreakdown->hour);
                $endHour = sprintf('%02d:00', ($hourBreakdown->hour + 1) % 24);
                $insights['peak_time'] = "Waktu tersibuk {$periodContext} adalah sekitar pukul <strong>{$startHour} - {$endHour}</strong> (total {$hourBreakdown->total} klik).";
            }
        }



        // --- Restore Carousel Data Requirements ---
        // We still need 7-day data for the "Weekly Winner" in carousel, regardless of the Insight context
        $sevenDaysQuery = $shortlink->clicks()->where('clicked_at', '>=', now()->subDays(6));
        $total7Days = $sevenDaysQuery->count(); // Used in Comparison Logic

        // --- 30 Days Analysis (For Carousel) ---
        $thirtyDaysQuery = $shortlink->clicks()->where('clicked_at', '>=', now()->subDays(30));
        
        // --- Slide 6: Location Analysis (Cities Only) ---
        $top3Cities30 = (clone $thirtyDaysQuery)
            ->where('city', '!=', 'Unknown')
            ->selectRaw('city, COUNT(*) as total')
            ->groupBy('city')
            ->orderByDesc('total')
            ->take(3)
            ->get();
            
        // Top City Weekly
        $topCityWeekly = (clone $sevenDaysQuery)
            ->where('city', '!=', 'Unknown')
            ->selectRaw('city, COUNT(*) as total')
            ->groupBy('city')
            ->orderByDesc('total')
            ->first();
        
        // Top City Daily
        $topCityDaily = $shortlink->clicks()
             ->where('clicked_at', '>=', today())
             ->where('city', '!=', 'Unknown')
             ->selectRaw('city, COUNT(*) as total')
             ->groupBy('city')
             ->orderByDesc('total')
             ->first();

        // --- Slide 7: Country Analysis (New Comparison) ---
        $top3Countries30 = (clone $thirtyDaysQuery)
            ->where('country', '!=', 'Unknown')
            ->selectRaw('country, COUNT(*) as total')
            ->groupBy('country')
            ->orderByDesc('total')
            ->take(3)
            ->get();

        $topCountryWeekly = (clone $sevenDaysQuery)
             ->where('country', '!=', 'Unknown')
             ->selectRaw('country, COUNT(*) as total')
             ->groupBy('country')
             ->orderByDesc('total')
             ->first();

        // --- 30 Days Analysis (For Carousel) - Continued ---
        $total30Days = $thirtyDaysQuery->count();
        
        $dominant30Days = [
            'source' => '-', 'device' => '-', 'city' => '-'
        ];
        $insights30Days = [];
        $comparison30Days = "Belum cukup data untuk perbandingan.";

        $trendMessage30Days = "Belum ada cukup data aktivitas untuk melihat tren 30 hari terakhir.";
        if ($total30Days > 0) {
             // 1. Trend Analysis 30D (Replaces Dominant Stats)
             $clicksLast15 = $shortlink->clicks()
                ->where('clicked_at', '>=', now()->subDays(15))
                ->count();
             
             $clicksPrev15 = $shortlink->clicks()
                ->where('clicked_at', '>=', now()->subDays(30))
                ->where('clicked_at', '<', now()->subDays(15))
                ->count();

             $trendMessage30Days = "Trafik Anda stabil dalam 30 hari terakhir.";
             if ($clicksPrev15 > 0) {
                 $pctTrend = (($clicksLast15 - $clicksPrev15) / $clicksPrev15) * 100;
                 if ($pctTrend >= 10) {
                     $trendMessage30Days = "Kerja bagus, tren klik link Anda dalam 30 hari terakhir cenderung <strong>naik</strong>.";
                 } elseif ($pctTrend <= -10) {
                     $trendMessage30Days = "Perhatian, tren klik link Anda dalam 30 hari terakhir cenderung <strong>turun</strong>.";
                 }
            } elseif ($clicksLast15 > 0) {
                // New traffic case
                $daysOld = $shortlink->created_at->diffInDays(now());
                if ($daysOld < 30) {
                    $trendMessage30Days = "Analisis link Anda dalam 30 hari terakhir <span class='block text-xs font-normal text-slate-400 mt-2'>(Data dan rekomendasi mungkin tidak akurat karena umur link Anda kurang dari 30 hari atau baru saja dibuat)</span>";
                } else {
                    $trendMessage30Days = "Analisis link Anda dalam 30 hari terakhir.";
                }
            } else {
                 $trendMessage30Days = "Belum ada cukup data aktivitas untuk melihat tren 30 hari terakhir.";
             }
             
             // Keep these for compatibility if view uses them elsewhere, or just nullify
             $dominant30Days['source'] = null; // Unused
             $dominant30Days['device'] = null; // Unused
             $dominant30Days['city'] = null;   // Unused

             // 2. Breakdown Insights 30D
             $osBreakdown30 = (clone $thirtyDaysQuery)->selectRaw('os, COUNT(*) as total')->groupBy('os')->orderByDesc('total')->first();
             if ($osBreakdown30) {
                 $pct = round(($osBreakdown30->total / $total30Days) * 100, 1);
                 $insights30Days[] = "Sistem Operasi: <strong>{$osBreakdown30->os}</strong> ({$pct}%)";
             }
             $devBreakdown30 = (clone $thirtyDaysQuery)->selectRaw('device_type, COUNT(*) as total')->groupBy('device_type')->orderByDesc('total')->first();
             if ($devBreakdown30) {
                 $pct = round(($devBreakdown30->total / $total30Days) * 100, 1);
                 $insights30Days[] = "Perangkat: <strong>" . ucfirst($devBreakdown30->device_type) . "</strong> ({$pct}%)";
             }

             // 3. Comparison Logic (Avg Weekly vs Avg Prior Period)
             // We compare avg daily clicks of [Last 7 Days] vs [Previous 23 Days] (Days 8-30)
             // This avoids the "328.6%" issue where comparing 7 days vs 30 days (overlapping) for new links results in a constant ratio.
             
             $clicks7Days = $total7Days; // From previous calculation
             $clicksPrior23Days = $shortlink->clicks()
                ->where('clicked_at', '>=', now()->subDays(30))
                ->where('clicked_at', '<', now()->subDays(6)) // Days 8-30 roughly (using 6 to align with 7days query)
                ->count();

             // Get dominant device for the text
             $topDevice30 = (clone $thirtyDaysQuery)->selectRaw('device_type, COUNT(*) as total')->groupBy('device_type')->orderByDesc('total')->first();
             $domDevice = $topDevice30 ? ucfirst($topDevice30->device_type) : 'berbagai perangkat';

             if ($clicksPrior23Days > 0) {
                 $avgDaily7 = $clicks7Days / 7;
                 $avgDailyPrior = $clicksPrior23Days / 23; // Remaining period

                 $pctChange = round((($avgDaily7 - $avgDailyPrior) / $avgDailyPrior) * 100, 1);
                 
                 $trendText = "stabil";
                 if ($pctChange > 5) $trendText = "kenaikan";
                 elseif ($pctChange < -5) $trendText = "penurunan";
                 
                 $changeStr = abs($pctChange) . '%';
                 $comparison30Days = "Performa link Anda dalam <strong>7 hari terakhir</strong> mengalami <strong>{$trendText} sebesar {$changeStr}</strong> jika dibandingkan dengan rata-rata harian periode sebelumnya (hari 8-30). Tren terkini didominasi oleh akses melalui <strong>{$domDevice}</strong>.";
             } else {
                 // Case: New Link or No Prior Activity
                 if ($clicks7Days > 0) {
                     $comparison30Days = "Link ini sedang <strong>populer minggu ini</strong>. Terdapat total <strong>{$clicks7Days} klik</strong> dalam 7 hari terakhir. Karena ini adalah aktivitas baru, belum ada data historis sebelumnya untuk perbandingan tren (lonjakan aktivitas).";
                 } else {
                     $comparison30Days = "Belum ada cukup data aktivitas dalam 30 hari terakhir untuk menampilkan analisis tren pertumbuhan.";
                 }
             }
        }

        // --- Slide 4: Top 3 Sources & Avg Time (30 Days) ---
        $top3Sources30 = collect([]);
        $avgClickHour30 = '-';
        if ($total30Days > 0) {
            $top3Sources30 = (clone $thirtyDaysQuery)
                ->whereNotNull('referer_url')
                ->selectRaw('referer_url, COUNT(*) as total')
                ->groupBy('referer_url')
                ->orderByDesc('total')
                ->take(3)
                ->get()
                ->map(function ($item) {
                     $host = parse_url($item->referer_url, PHP_URL_HOST) ?: 'Unknown';
                     return ['name' => $host, 'total' => $item->total];
                });
        }

        // --- Slide New: Populer Click Time (Separated) ---
        $peakHour30Val = null;
        $peakHour30Text = '-';
        if ($total30Days > 0) {
            $peakHour30Val = (clone $thirtyDaysQuery)
                ->selectRaw('HOUR(clicked_at) as hour, COUNT(*) as total')
                ->groupBy('hour')
                ->orderByDesc('total')
                ->value('hour');
            if (!is_null($peakHour30Val)) {
                 $peakHour30Text = sprintf('%02d:00 - %02d:00', $peakHour30Val, ($peakHour30Val + 1) % 24);
            }
        }

        $peakHour7Val = null;
        $peakHour7Text = '-';
        if ($total7Days > 0) {
            $peakHour7Val = (clone $sevenDaysQuery)
                ->selectRaw('HOUR(clicked_at) as hour, COUNT(*) as total')
                ->groupBy('hour')
                ->orderByDesc('total')
                ->value('hour');
             if (!is_null($peakHour7Val)) {
                 $peakHour7Text = sprintf('%02d:00 - %02d:00', $peakHour7Val, ($peakHour7Val + 1) % 24);
            }
        }

        // Recommendation Logic
        $timeRecommendation = "Belum cukup data untuk rekomendasi waktu.";
        if (!is_null($peakHour30Val) && !is_null($peakHour7Val)) {
            $recommendedTime = $peakHour7Text; // Prioritize recent trend
            $timeRecommendation = "Rata-rata orang mengklik link Anda ada sekitar pukul: <strong>{$recommendedTime}</strong>. Bagikan lebih banyak di waktu tersebut!";
        } elseif (!is_null($peakHour30Val)) {
             $timeRecommendation = "Rata-rata orang mengklik link Anda ada sekitar pukul: <strong>{$peakHour30Text}</strong>. Bagikan lebih banyak di waktu tersebut!";
        }

        // --- Slide 5: Last 24 Hours Insight (Since 00:00) ---
        $todayQuery = $shortlink->clicks()->where('clicked_at', '>=', today()); // Since 00:00 today
        $totalToday = $todayQuery->count();
        $last24HStats = null;

        if ($totalToday > 0) {
            $peakHourToday = (clone $todayQuery)
                ->selectRaw('HOUR(clicked_at) as hour, COUNT(*) as total')
                ->groupBy('hour')
                ->orderByDesc('total')
                ->first();
            
            $domDeviceToday = (clone $todayQuery)->selectRaw('device_type, COUNT(*) as total')->groupBy('device_type')->orderByDesc('total')->value('device_type');
            $domOSToday = (clone $todayQuery)->selectRaw('os, COUNT(*) as total')->groupBy('os')->orderByDesc('total')->value('os');
            $domSourceTodayRaw = (clone $todayQuery)->whereNotNull('referer_url')->selectRaw('referer_url, COUNT(*) as total')->groupBy('referer_url')->orderByDesc('total')->first();
            $domSourceToday = $domSourceTodayRaw ? (parse_url($domSourceTodayRaw->referer_url, PHP_URL_HOST) ?: 'Lainnya') : 'Direct/Email';

            if ($peakHourToday) {
                 $start = sprintf('%02d:00', $peakHourToday->hour);
                 $last24HStats = [
                     'peak_hour' => $start,
                     'device' => $domDeviceToday,
                     'os' => $domOSToday,
                     'source' => $domSourceToday
                 ];
            }
        }

        // --- Slide 6: Geographic Analysis ---
        // 1. Top 3 Locations (30 Days)
        $top3Locations30 = [];
        if ($total30Days > 0) {
            $top3Locations30 = (clone $thirtyDaysQuery)
                ->selectRaw('city, country, COUNT(*) as total')
                ->where('city', '!=', 'Unknown')
                ->groupBy('city', 'country')
                ->orderByDesc('total')
                ->take(3)
                ->get();
        }

        // 2. Weekly Champion (7 Days)
        $topLocationWeekly = '-';
        if ($sevenDaysQuery->count() > 0) {
             $locWeekly = (clone $sevenDaysQuery)
                ->selectRaw('city, country, COUNT(*) as total')
                ->where('city', '!=', 'Unknown')
                ->groupBy('city', 'country')
                ->orderByDesc('total')
                ->first();
             if ($locWeekly) {
                 $topLocationWeekly = "{$locWeekly->city}, {$locWeekly->country}";
             }
        }

        // 3. Daily Champion (24H / Since 00:00)
        $topLocationDaily = '-';
        if ($totalToday > 0) {
             $locDaily = (clone $todayQuery)
                ->selectRaw('city, country, COUNT(*) as total')
                ->where('city', '!=', 'Unknown')
                ->groupBy('city', 'country')
                ->orderByDesc('total')
                ->first();
             if ($locDaily) {
                 $topLocationDaily = "{$locDaily->city}, {$locDaily->country}";
             }
        }

        // Top Referrers (Now 30 Days)
        $referrers = $shortlink->clicks()
            ->where('clicked_at', '>=', now()->subDays(30))
            ->selectRaw('referer_url, COUNT(*) as total')
            ->groupBy('referer_url')
            ->orderByDesc('total')
            ->take(5)
            ->get()
            ->map(function ($item) {
                $item->referer_domain = parse_url($item->referer_url, PHP_URL_HOST);
                return $item;
            });

        // Detailed Click History (Last 7 Days, Paginated)
        // Detailed Click History (Latest 30, Paginated 10)
        $historySearch = $request->query('q');
        $clickHistoryQuery = $shortlink->clicks(); // Removed 7-day filter

        if ($historySearch) {
             $clickHistoryQuery->where(function($q) use ($historySearch) {
                 $q->where('ip_address', 'like', "%{$historySearch}%")
                   ->orWhere('referer_url', 'like', "%{$historySearch}%")
                   ->orWhere('country', 'like', "%{$historySearch}%")
                   ->orWhere('city', 'like', "%{$historySearch}%")
                   ->orWhere('device_type', 'like', "%{$historySearch}%")
                   ->orWhere('os', 'like', "%{$historySearch}%")
                   ->orWhere('browser', 'like', "%{$historySearch}%");
             });
        }
            
        // Fetch top 30 items
        $top30Clicks = $clickHistoryQuery->latest('clicked_at')->take(30)->get();

        // Manual Pagination
        $page = \Illuminate\Pagination\Paginator::resolveCurrentPage() ?: 1;
        $perPage = 10;
        $clickHistory = new \Illuminate\Pagination\LengthAwarePaginator(
            $top30Clicks->forPage($page, $perPage),
            $top30Clicks->count(),
            $perPage,
            $page,
            ['path' => \Illuminate\Pagination\Paginator::resolveCurrentPath(), 'query' => $request->query()]
        );

        // Slide 9: Final Recommendation
        $recSource = 'Media Sosial';
        if (isset($top3Sources30) && $top3Sources30->isNotEmpty()) {
             $recSource = $top3Sources30->first()['name'];
        }

        $recTime = isset($peakHour30Text) && $peakHour30Text !== '-' ? $peakHour30Text : 'waktu aktif audiens';
        
        $recDevice = 'berbagai perangkat';
        if (isset($devBreakdown30) && $devBreakdown30) {
            $recDevice = ucfirst($devBreakdown30->device_type);
        }

        $recOS = 'sistem operasi populer';
        if (isset($osBreakdown30) && $osBreakdown30) {
             $recOS = $osBreakdown30->os;
        }

        $finalRecommendation = "Dari data yang kami rangkum, kami menyarankan Anda untuk membagikan lebih banyak link ke <strong>{$recSource}</strong> pada waktu sekitar pukul <strong>{$recTime}</strong>. Optimalkan halaman tujuan Anda agar lebih sesuai dengan pengunjung mayoritas yaitu pengguna <strong>{$recDevice}</strong> dan <strong>{$recOS}</strong>. Perhatikan juga Insight 24 jam dari kami sebagai acuan baru dan tren klik Anda hari ini. Mungkin tren kedepan akan mengarah ke data hari ini dibanding 30 hari terakhir. Keputusan di tangan Anda!";

        return view('dashboard.analytics.data', compact(
            'shortlink',
            'stats',
            'labels',
            'chartData',
            'devices',
            'browsers',
            'os_stats',
            'countries',
            'cities',
            'referrers',
            'lastClick',
            'clicks1Hour',
            'dominant7Days',
            'insights',
            'dominant30Days',
            'insights30Days',
            'comparison30Days',
            'top3Sources30',
            'peakHour30Text',
            'peakHour7Text',
            'timeRecommendation',
            'last24HStats',
            'top3Cities30',
            'topCityWeekly',
            'topCityDaily',
            'top3Countries30',
            'topCountryWeekly',
            'dailyClicks',
            'weeklyClicks',
            'trendMessage30Days',
            'periodLabel',
            'finalRecommendation',
            'clickHistory'
        ));
    }

    private function getGroupedStats($user, $column, $dateFilter = null)
    {
        $query = \App\Models\Click::whereHas('shortlink', function($q) use ($user) {
                $q->where('user_id', $user->id);
            });
            
        if ($dateFilter) {
            $dateFilter($query);
        }

        return $query->selectRaw("$column, COUNT(*) as count")
            ->groupBy($column)
            ->orderByDesc('count')
            ->get();
    }
}
