<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UserStatsController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        
        // Get user's ad statistics
        $totalAds = $user->ads()->count();
        $activeAds = $user->ads()->where('status', 'Active')->count();
        $totalViews = $user->ads()->sum('view_count') ?? 0;
        $totalLikes = DB::table('ad_likes')->whereIn('ad_id', $user->ads()->pluck('id'))->count();
        
        // Advanced Stats (Daily Views for Chart)
        $analytics = [];
        
        // Check if user has advanced analytics capability
        // We check the plan directly or via user propery if eager loaded
        $hasAdvancedAnalytics = false;
        
        // Simplest check: if current_plan_id is set and plan has analytics
        if ($user->current_plan_id) {
            $plan = DB::table('user_plans')->find($user->current_plan_id);
            if ($plan && $plan->analytics_tier === 'advanced') {
                $hasAdvancedAnalytics = true;
            }
        }
        
        if ($hasAdvancedAnalytics) {
            // Mocking daily views for now as we don't have a daily_ad_views table yet
            // In a real app, this would query a logging table
            // For demo/prototype: Generate realistic looking curve based on total views
            $analytics['daily_views'] = $this->generateMockDailyData($totalViews);
            $analytics['top_ads'] = $user->ads()
                ->orderBy('view_count', 'desc')
                ->take(3)
                ->select('id', 'title', 'view_count', 'price', 'images')
                ->get()
                ->map(function($ad) {
                    $ad->image_url = $ad->images ? json_decode($ad->images)[0] ?? null : null;
                    return $ad;
                });
        }
        
        return response()->json([
            'total_ads' => $totalAds,
            'active_ads' => $activeAds,
            'total_views' => $totalViews,
            'total_likes' => $totalLikes,
            'analytics_tier' => $hasAdvancedAnalytics ? 'advanced' : 'basic',
            'chart_data' => $hasAdvancedAnalytics ? $analytics : null,
        ]);
    }

    private function generateMockDailyData($totalViews) {
        $data = [];
        $days = 7;
        $base = (int)($totalViews / $days);
        
        for ($i = 6; $i >= 0; $i--) {
            $date = now()->subDays($i)->format('M d');
            // Randomize slightly around the average
            $views = max(0, $base + rand(-5, 10)); 
            $data[] = ['date' => $date, 'views' => $views];
        }
        return $data;
    }
}
