<?php

namespace App\Http\Controllers;

use App\Services\AnalyticsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AnalyticsController extends Controller
{
    protected $analyticsService;

    public function __construct(AnalyticsService $analyticsService)
    {
        $this->analyticsService = $analyticsService;
    }

    /**
     * Get dashboard overview
     */
    public function dashboardOverview(Request $request)
    {
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');

        $data = $this->analyticsService->getDashboardOverview($startDate, $endDate);

        return response()->json([
            'success' => true,
            'data' => $data,
            'date_range' => [
                'start' => $startDate,
                'end' => $endDate,
            ],
        ]);
    }

    /**
     * Get user analytics
     */
    public function userAnalytics(Request $request)
    {
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');

        $data = $this->analyticsService->getUserAnalytics($startDate, $endDate);

        return response()->json([
            'success' => true,
            'data' => $data,
        ]);
    }

    /**
     * Get ad analytics
     */
    public function adAnalytics(Request $request)
    {
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');

        $data = $this->analyticsService->getAdAnalytics($startDate, $endDate);

        return response()->json([
            'success' => true,
            'data' => $data,
        ]);
    }

    /**
     * Get revenue analytics
     */
    public function revenueAnalytics(Request $request)
    {
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');

        $data = $this->analyticsService->getRevenueAnalytics($startDate, $endDate);

        return response()->json([
            'success' => true,
            'data' => $data,
        ]);
    }

    /**
     * Get technical analytics
     */
    public function technicalAnalytics(Request $request)
    {
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');

        $data = $this->analyticsService->getTechnicalAnalytics($startDate, $endDate);

        return response()->json([
            'success' => true,
            'data' => $data,
        ]);
    }

    /**
     * Get all analytics data
     */
    public function allAnalytics(Request $request)
    {
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');

        $data = [
            'overview' => $this->analyticsService->getDashboardOverview($startDate, $endDate),
            'user_analytics' => $this->analyticsService->getUserAnalytics($startDate, $endDate),
            'ad_analytics' => $this->analyticsService->getAdAnalytics($startDate, $endDate),
            'revenue_analytics' => $this->analyticsService->getRevenueAnalytics($startDate, $endDate),
            'technical_analytics' => $this->analyticsService->getTechnicalAnalytics($startDate, $endDate),
        ];

        return response()->json([
            'success' => true,
            'data' => $data,
            'date_range' => [
                'start' => $startDate,
                'end' => $endDate,
            ],
        ]);
    }

    /**
     * Export analytics data
     */
    public function exportAnalytics(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
            'format' => 'required|in:csv,json,excel',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors(),
            ], 422);
        }

        $startDate = $request->start_date;
        $endDate = $request->end_date;
        $format = $request->format;

        // Get all analytics data
        $data = $this->analyticsService->allAnalytics($startDate, $endDate);

        // Export logic would go here based on format
        // For now, return the data
        return response()->json([
            'success' => true,
            'message' => "Exporting analytics data from {$startDate} to {$endDate} in {$format} format",
            'data' => $data,
        ]);
    }

    /**
     * Get real-time analytics
     */
    public function realTimeAnalytics()
    {
        // Get data from last hour
        $startDate = now()->subHour();
        $endDate = now();

        $data = [
            'active_users' => $this->analyticsService->getActiveUsers($startDate, $endDate),
            'page_views' => $this->analyticsService->getPageViews($startDate, $endDate),
            'registrations' => $this->analyticsService->getRegistrations($startDate, $endDate),
            'ads_posted' => $this->analyticsService->getAdsPosted($startDate, $endDate),
            'messages_sent' => $this->analyticsService->getMessagesSent($startDate, $endDate),
        ];

        return response()->json([
            'success' => true,
            'data' => $data,
            'timestamp' => now(),
        ]);
    }

    /**
     * Track custom event
     */
    public function trackEvent(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'event_type' => 'required|string',
            'event_data' => 'nullable|array',
            'user_id' => 'nullable|integer|exists:users,id',
            'session_id' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors(),
            ], 422);
        }

        $event = $this->analyticsService->trackEvent(
            $request->event_type,
            $request->event_data ?? [],
            $request->user_id,
            $request->session_id
        );

        return response()->json([
            'success' => true,
            'message' => 'Event tracked successfully',
            'event' => $event,
        ], 201);
    }

    /**
     * Get analytics summary
     */
    public function summary(Request $request)
    {
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');

        // Get overview data
        $overview = $this->analyticsService->getDashboardOverview($startDate, $endDate);

        // Calculate growth rates
        $previousStartDate = null;
        $previousEndDate = null;

        if ($startDate && $endDate) {
            $startDateObj = new \DateTime($startDate);
            $endDateObj = new \DateTime($endDate);
            $interval = $endDateObj->diff($startDateObj);
            
            $previousEndDate = $startDateObj->modify('-1 day');
            $previousStartDate = $previousEndDate->modify('-' . $interval->days . ' days');
        }

        $previousOverview = $this->analyticsService->getDashboardOverview(
            $previousStartDate, 
            $previousEndDate
        );

        $summary = [
            'overview' => $overview,
            'growth_rates' => $this->calculateGrowthRates($overview, $previousOverview),
            'insights' => $this->generateInsights($overview),
        ];

        return response()->json([
            'success' => true,
            'data' => $summary,
        ]);
    }

    /**
     * Get business intelligence dashboard
     */
    public function businessIntelligence(Request $request)
    {
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');

        // Get comprehensive business intelligence data
        $data = [
            'kpi_overview' => $this->getKPIOverview($startDate, $endDate),
            'revenue_analytics' => $this->getRevenueAnalyticsData($startDate, $endDate),
            'user_behavior_analysis' => $this->getUserBehaviorAnalysis($startDate, $endDate),
            'market_trends' => $this->getMarketTrends($startDate, $endDate),
            'conversion_funnels' => $this->getConversionFunnels($startDate, $endDate),
            'customer_lifetime_value' => $this->getCustomerLifetimeValue($startDate, $endDate),
        ];

        return response()->json([
            'success' => true,
            'data' => $data,
            'date_range' => [
                'start' => $startDate,
                'end' => $endDate,
            ],
        ]);
    }

    /**
     * Get AI-powered insights
     */
    public function aiInsights(Request $request)
    {
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');

        // Get current analytics data
        $overview = $this->analyticsService->getDashboardOverview($startDate, $endDate);

        // Generate AI insights based on data patterns
        $insights = [
            'trends' => $this->analyzeTrends($overview),
            'opportunities' => $this->identifyOpportunities($overview),
            'risks' => $this->identifyRisks($overview),
            'recommendations' => $this->generateRecommendations($overview),
        ];

        return response()->json([
            'success' => true,
            'insights' => $insights,
            'timestamp' => now(),
        ]);
    }

    /**
     * Get executive summary
     */
    public function executiveSummary(Request $request)
    {
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');

        // Get comprehensive data for executive summary
        $businessIntelligence = $this->businessIntelligence($request)->getData(true);
        
        $summary = [
            'top_performers' => $this->getTopPerformers($startDate, $endDate),
            'risks_identified' => $this->getIdentifiedRisks($startDate, $endDate),
            'strategic_recommendations' => $this->getStrategicRecommendations($startDate, $endDate),
            'key_metrics' => $businessIntelligence['data']['kpi_overview'],
            'growth_summary' => $this->getGrowthSummary($startDate, $endDate),
        ];

        return response()->json([
            'success' => true,
            'summary' => $summary,
            'date_range' => [
                'start' => $startDate,
                'end' => $endDate,
            ],
        ]);
    }

    /**
     * Export analytics report
     */
    public function exportReport(Request $request)
    {
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');
        $reportType = $request->input('report_type', 'business_intelligence');

        // Get data based on report type
        switch ($reportType) {
            case 'executive_summary':
                $data = $this->executiveSummary($request)->getData(true);
                break;
            case 'detailed_report':
                $data = $this->businessIntelligence($request)->getData(true);
                break;
            default:
                $data = $this->businessIntelligence($request)->getData(true);
                break;
        }

        // Generate PDF report (simplified for now)
        $reportData = [
            'title' => 'CLXpro Analytics Report',
            'date_range' => [
                'start' => $startDate,
                'end' => $endDate,
            ],
            'report_type' => $reportType,
            'generated_at' => now(),
            'data' => $data['data'] ?? $data['summary'],
        ];

        return response()->json([
            'success' => true,
            'message' => 'Analytics report generated successfully',
            'report' => $reportData,
        ]);
    }

    /**
     * Get KPI overview for business intelligence
     */
    private function getKPIOverview($startDate, $endDate)
    {
        $overview = $this->analyticsService->getDashboardOverview($startDate, $endDate);
        
        return [
            'total_revenue' => $overview['total_revenue'] ?? 0,
            'active_users' => $overview['active_users'] ?? 0,
            'conversion_rate' => $overview['conversion_rate'] ?? 0,
            'arpu' => $overview['arpu'] ?? 0,
            'revenue_growth_rate' => $overview['revenue_growth_rate'] ?? 0,
            'user_growth_rate' => $overview['user_growth_rate'] ?? 0,
        ];
    }

    /**
     * Get revenue analytics data
     */
    private function getRevenueAnalyticsData($startDate, $endDate)
    {
        return [
            'daily_revenue' => $this->analyticsService->getDailyRevenue($startDate, $endDate),
            'revenue_by_category' => $this->analyticsService->getRevenueByCategory($startDate, $endDate),
            'payment_method_breakdown' => $this->analyticsService->getPaymentMethodBreakdown($startDate, $endDate),
            'revenue_trends' => $this->analyticsService->getRevenueTrends($startDate, $endDate),
        ];
    }

    /**
     * Get user behavior analysis
     */
    private function getUserBehaviorAnalysis($startDate, $endDate)
    {
        return [
            'feature_usage' => $this->analyticsService->getFeatureUsage($startDate, $endDate),
            'session_analysis' => $this->analyticsService->getSessionAnalysis($startDate, $endDate),
            'user_journey' => $this->analyticsService->getUserJourney($startDate, $endDate),
            'engagement_metrics' => $this->analyticsService->getEngagementMetrics($startDate, $endDate),
        ];
    }

    /**
     * Get market trends
     */
    private function getMarketTrends($startDate, $endDate)
    {
        return [
            'category_trends' => $this->analyticsService->getCategoryTrends($startDate, $endDate),
            'geographic_distribution' => $this->analyticsService->getGeographicDistribution($startDate, $endDate),
            'seasonal_patterns' => $this->analyticsService->getSeasonalPatterns($startDate, $endDate),
            'competitor_analysis' => $this->analyticsService->getCompetitorAnalysis($startDate, $endDate),
        ];
    }

    /**
     * Get conversion funnels
     */
    private function getConversionFunnels($startDate, $endDate)
    {
        return [
            'registration_funnel' => $this->analyticsService->getRegistrationFunnel($startDate, $endDate),
            'ad_posting_funnel' => $this->analyticsService->getAdPostingFunnel($startDate, $endDate),
            'purchase_funnel' => $this->analyticsService->getPurchaseFunnel($startDate, $endDate),
            'retention_funnel' => $this->analyticsService->getRetentionFunnel($startDate, $endDate),
        ];
    }

    /**
     * Get customer lifetime value
     */
    private function getCustomerLifetimeValue($startDate, $endDate)
    {
        return [
            'high_value_customers' => $this->analyticsService->getHighValueCustomers($startDate, $endDate),
            'customer_segments' => $this->analyticsService->getCustomerSegments($startDate, $endDate),
            'churn_analysis' => $this->analyticsService->getChurnAnalysis($startDate, $endDate),
            'lifetime_value_trends' => $this->analyticsService->getLifetimeValueTrends($startDate, $endDate),
        ];
    }

    /**
     * Analyze trends for AI insights
     */
    private function analyzeTrends($overview)
    {
        $trends = [];
        
        if ($overview['revenue_growth_rate'] > 10) {
            $trends['revenue_trend'] = 'Strong growth detected in revenue metrics';
        } elseif ($overview['revenue_growth_rate'] < -5) {
            $trends['revenue_trend'] = 'Revenue decline detected, requires attention';
        } else {
            $trends['revenue_trend'] = 'Stable revenue performance';
        }

        if ($overview['user_growth_rate'] > 15) {
            $trends['user_trend'] = 'Rapid user acquisition';
        } elseif ($overview['user_growth_rate'] < 0) {
            $trends['user_trend'] = 'User acquisition challenges';
        } else {
            $trends['user_trend'] = 'Steady user growth';
        }

        return $trends;
    }

    /**
     * Identify opportunities for AI insights
     */
    private function identifyOpportunities($overview)
    {
        $opportunities = [];
        
        if ($overview['conversion_rate'] < 5) {
            $opportunities['feature_improvement_opportunities'] = [
                'Improve conversion funnel',
                'Enhance user onboarding',
                'Optimize ad posting process'
            ];
        }

        if ($overview['avg_session_duration'] < 120) {
            $opportunities['engagement_opportunities'] = [
                'Increase user engagement',
                'Improve content quality',
                'Enhance user experience'
            ];
        }

        return $opportunities;
    }

    /**
     * Identify risks for AI insights
     */
    private function identifyRisks($overview)
    {
        $risks = [];
        
        if ($overview['bounce_rate'] > 70) {
            $risks['churn_risk'] = 'High bounce rate indicates potential user dissatisfaction';
        }

        if ($overview['conversion_rate'] < 2) {
            $risks['revenue_risk'] = 'Low conversion rate may impact revenue growth';
        }

        return $risks;
    }

    /**
     * Generate recommendations for AI insights
     */
    private function generateRecommendations($overview)
    {
        $recommendations = [];
        
        if ($overview['revenue_growth_rate'] < 5) {
            $recommendations[] = 'Focus on revenue optimization strategies';
        }

        if ($overview['user_growth_rate'] < 5) {
            $recommendations[] = 'Invest in user acquisition campaigns';
        }

        if ($overview['conversion_rate'] < 5) {
            $recommendations[] = 'Optimize conversion funnel and user experience';
        }

        return $recommendations;
    }

    /**
     * Get top performers for executive summary
     */
    private function getTopPerformers($startDate, $endDate)
    {
        return [
            'top_categories' => $this->analyticsService->getTopCategories($startDate, $endDate),
            'top_users' => $this->analyticsService->getTopUsers($startDate, $endDate),
            'top_ads' => $this->analyticsService->getTopAds($startDate, $endDate),
            'best_performing_features' => $this->analyticsService->getBestPerformingFeatures($startDate, $endDate),
        ];
    }

    /**
     * Get identified risks for executive summary
     */
    private function getIdentifiedRisks($startDate, $endDate)
    {
        return [
            'high_risk_areas' => $this->analyticsService->getHighRiskAreas($startDate, $endDate),
            'potential_threats' => $this->analyticsService->getPotentialThreats($startDate, $endDate),
            'vulnerabilities' => $this->analyticsService->getVulnerabilities($startDate, $endDate),
        ];
    }

    /**
     * Get strategic recommendations for executive summary
     */
    private function getStrategicRecommendations($startDate, $endDate)
    {
        return [
            'short_term_actions' => $this->analyticsService->getShortTermActions($startDate, $endDate),
            'long_term_strategies' => $this->analyticsService->getLongTermStrategies($startDate, $endDate),
            'investment_priorities' => $this->analyticsService->getInvestmentPriorities($startDate, $endDate),
        ];
    }

    /**
     * Get growth summary for executive summary
     */
    private function getGrowthSummary($startDate, $endDate)
    {
        $overview = $this->analyticsService->getDashboardOverview($startDate, $endDate);
        
        return [
            'revenue_growth' => $overview['revenue_growth_rate'] ?? 0,
            'user_growth' => $overview['user_growth_rate'] ?? 0,
            'market_share_growth' => $overview['market_share_growth'] ?? 0,
            'competitive_position' => $overview['competitive_position'] ?? 'stable',
        ];
    }

    /**
     * Calculate growth rates
     */
    private function calculateGrowthRates($current, $previous)
    {
        $growthRates = [];

        foreach ($current as $key => $currentValue) {
            if (isset($previous[$key])) {
                $previousValue = $previous[$key];
                $growthRate = $previousValue > 0 
                    ? (($currentValue - $previousValue) / $previousValue) * 100 
                    : 0;
                
                $growthRates[$key] = [
                    'current' => $currentValue,
                    'previous' => $previousValue,
                    'growth_rate' => round($growthRate, 2),
                    'trend' => $growthRate >= 0 ? 'up' : 'down',
                ];
            }
        }

        return $growthRates;
    }

    /**
     * Generate insights
     */
    private function generateInsights($overview)
    {
        $insights = [];

        // Bounce rate insights
        if ($overview['bounce_rate'] > 70) {
            $insights[] = [
                'type' => 'warning',
                'message' => 'High bounce rate detected. Consider improving page load times and content quality.',
                'metric' => 'bounce_rate',
            ];
        }

        // Session duration insights
        if ($overview['avg_session_duration'] < 60) {
            $insights[] = [
                'type' => 'warning',
                'message' => 'Low average session duration. Users may not be finding what they need.',
                'metric' => 'avg_session_duration',
            ];
        }

        // User engagement insights
        if ($overview['active_users'] > 0 && $overview['total_page_views'] / $overview['active_users'] < 3) {
            $insights[] = [
                'type' => 'info',
                'message' => 'Low page views per user. Consider improving navigation and content discovery.',
                'metric' => 'user_engagement',
            ];
        }

        // Conversion insights
        if ($overview['total_registrations'] > 0 && $overview['total_ads_posted'] > 0) {
            $conversionRate = ($overview['total_ads_posted'] / $overview['total_registrations']) * 100;
            if ($conversionRate < 20) {
                $insights[] = [
                    'type' => 'info',
                    'message' => 'Low ad posting conversion rate. Consider simplifying the ad posting process.',
                    'metric' => 'conversion_rate',
                ];
            }
        }

        return $insights;
    }
}
