<?php

namespace FleekDash\Controllers;

use FleekDash\Controllers\Analytics\AnalyticsHelpers;
use FleekDash\Controllers\Analytics\AnalyticsCalculator;
use FleekDash\Controllers\Analytics\AnalyticsAggregator;
use FleekDash\Controllers\Analytics\UserAnalytics;
use FleekDash\Controllers\Analytics\RealTimeAnalytics;
use FleekDash\Controllers\Analytics\EngagementTracker;
use FleekDash\Controllers\Analytics\AnalyticsExporter;
use FleekDash\Services\AnalyticsCacheService;
use FleekDash\Services\AnalyticsTrackingService;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;

/**
 * Analytics Controller
 *
 * Main controller for analytics endpoints.
 * Delegates to specialized services for clean architecture.
 *
 * @package FleekDash\Controllers
 */
class AnalyticsController
{
    private $cacheService;
    private $trackingService;
    private $calculator;
    private $aggregator;
    private $userAnalytics;
    private $realTime;
    private $engagementTracker;
    private $exporter;

    public function __construct()
    {
        $this->cacheService = new AnalyticsCacheService();
        $this->trackingService = AnalyticsTrackingService::getInstance();
        $this->calculator = new AnalyticsCalculator();
        $this->aggregator = new AnalyticsAggregator();
        $this->userAnalytics = new UserAnalytics();
        $this->realTime = new RealTimeAnalytics();
        $this->engagementTracker = new EngagementTracker();
        $this->exporter = new AnalyticsExporter();

        $this->cacheService->setup_smart_invalidation();
    }

    /**
     * Check permissions - always return true
     * Let AuthMiddleware handle authentication
     */
    public function check_permissions()
    {
        return true;
    }

    /**
     * Get visitors analytics
     */
    public function get_visitors(WP_REST_Request $request)
    {
        try {
            // Auth handled by RouteAuthMiddleware
            $date_range = AnalyticsHelpers::getDateRange($request);
            $aggregation = $request->get_param('aggregation');

            $params = [
                'start' => $date_range['start']->format('Y-m-d'),
                'end' => $date_range['end']->format('Y-m-d'),
                'aggregation' => $aggregation
            ];

            $data = $this->cacheService->get_cached_data(
                'visitors',
                $params,
                function () use ($date_range, $aggregation) {
                    return $this->calculator->calculateVisitorsData($date_range, $aggregation);
                }
            );

            $cache_hit = $data['_cache_hit'] ?? false;
            unset($data['_cache_hit'], $data['_cached_at']);

            return new WP_REST_Response([
                'success' => true,
                'results' => array_values($data),
                'meta' => [
                    'total_records' => count($data),
                    'date_range' => [
                        'start' => $date_range['start']->format('Y-m-d'),
                        'end' => $date_range['end']->format('Y-m-d')
                    ],
                    'aggregation' => $aggregation,
                    'cache_hit' => $cache_hit
                ]
            ], 200);

        } catch (\Exception $e) {
            return new WP_Error('analytics_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Get pageviews analytics
     */
    public function get_pageviews(WP_REST_Request $request)
    {
        try {
            // Auth handled by RouteAuthMiddleware
            $date_range = AnalyticsHelpers::getDateRange($request);
        $aggregation = $request->get_param('aggregation');

        $params = [
                'start' => $date_range['start']->format('Y-m-d'),
                'end' => $date_range['end']->format('Y-m-d'),
            'aggregation' => $aggregation
        ];

            $data = $this->cacheService->get_cached_data(
            'pageviews',
            $params,
            function () use ($date_range, $aggregation) {
                    return $this->calculator->calculatePageviewsData($date_range, $aggregation);
            }
        );

        $cache_hit = $data['_cache_hit'] ?? false;
        unset($data['_cache_hit'], $data['_cached_at']);

        return new WP_REST_Response([
            'success' => true,
                'results' => array_values($data),
            'meta' => [
                'total_records' => count($data),
                    'date_range' => [
                        'start' => $date_range['start']->format('Y-m-d'),
                        'end' => $date_range['end']->format('Y-m-d')
                    ],
                    'aggregation' => $aggregation,
                'cache_hit' => $cache_hit
            ]
        ], 200);

        } catch (\Exception $e) {
            return new WP_Error('analytics_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Get popular posts
     */
    public function get_popular_posts(WP_REST_Request $request)
    {
        try {
            // Auth handled by RouteAuthMiddleware
            $date_range = AnalyticsHelpers::getDateRange($request);
            $limit = (int) $request->get_param('limit') ?: 10;

            $params = [
                'start' => $date_range['start']->format('Y-m-d'),
                'end' => $date_range['end']->format('Y-m-d'),
                'limit' => $limit
            ];

            $data = $this->cacheService->get_cached_data(
                'popular_posts',
                $params,
                function () use ($date_range, $limit) {
                    return $this->aggregator->getPopularPostsData($date_range, $limit);
                }
            );

            $cache_hit = $data['_cache_hit'] ?? false;
            unset($data['_cache_hit'], $data['_cached_at']);

            return new WP_REST_Response([
                'success' => true,
                'results' => $data,
                'meta' => [
                    'total_records' => count($data),
                    'cache_hit' => $cache_hit
                ]
            ], 200);

        } catch (\Exception $e) {
            return new WP_Error('analytics_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Get user registrations
     */
    public function get_user_registrations(WP_REST_Request $request)
    {
        try {
            // Auth handled by RouteAuthMiddleware
            $date_range = AnalyticsHelpers::getDateRange($request);
            $aggregation = $request->get_param('aggregation');

            $params = [
                'start' => $date_range['start']->format('Y-m-d'),
                'end' => $date_range['end']->format('Y-m-d'),
                'aggregation' => $aggregation
            ];

            $data = $this->cacheService->get_cached_data(
                'user_registrations',
                $params,
                function () use ($date_range, $aggregation) {
                    return $this->aggregator->getUserRegistrationsData($date_range, $aggregation);
                }
            );

            $cache_hit = $data['_cache_hit'] ?? false;
            unset($data['_cache_hit'], $data['_cached_at']);

            return new WP_REST_Response([
                'success' => true,
                'results' => array_values($data),
                'meta' => [
                    'total_records' => count($data),
                    'cache_hit' => $cache_hit
                ]
            ], 200);

        } catch (\Exception $e) {
            return new WP_Error('analytics_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Get recent users
     */
    public function get_recent_users(WP_REST_Request $request)
    {
        try {
            // Auth handled by RouteAuthMiddleware
            $limit = (int) $request->get_param('limit') ?: 5;

            $params = ['limit' => $limit];

            $data = $this->cacheService->get_cached_data(
                'recent_users',
                $params,
                function () use ($limit) {
                    return $this->userAnalytics->getRecentUsersData($limit);
                }
            );

            $cache_hit = $data['_cache_hit'] ?? false;
            unset($data['_cache_hit'], $data['_cached_at']);

            return new WP_REST_Response([
                'success' => true,
                'results' => $data,
            ], 200);

        } catch (\Exception $e) {
            return new WP_Error('analytics_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Get KPI summary
     */
    public function get_kpi_summary(WP_REST_Request $request)
    {
        try {
            // Auth handled by RouteAuthMiddleware
            $date_range = AnalyticsHelpers::getDateRange($request);

            $params = [
                'start' => $date_range['start']->format('Y-m-d'),
                'end' => $date_range['end']->format('Y-m-d')
            ];

            $data = $this->cacheService->get_cached_data(
                'kpi_summary',
                $params,
                function () use ($date_range) {
                    return $this->calculator->calculateKPISummary($date_range);
                }
            );

            return new WP_REST_Response([
                'success' => true,
                'results' => $data,
            ], 200);

        } catch (\Exception $e) {
            return new WP_Error('analytics_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Get real-time analytics
     */
    public function get_real_time(WP_REST_Request $request)
    {
        // Auth handled by RouteAuthMiddleware

        try {
            $data = $this->realTime->getRealTimeData();

        return new WP_REST_Response([
            'success' => true,
                'active_visitors' => $data['active_visitors'],
                'recent_pageviews' => $data['recent_pageviews'],
                'active_pages' => $data['active_pages'],
        ], 200);

        } catch (\Exception $e) {
            return new WP_Error('analytics_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Get cache statistics
     */
    public function get_cache_stats(WP_REST_Request $request)
    {
        return new WP_REST_Response([
            'success' => true,
            'cache_stats' => $this->cacheService->get_cache_stats()
        ], 200);
    }

    /**
     * Clear analytics cache
     */
    public function clear_cache(WP_REST_Request $request)
    {
        $cache_key = $request->get_param('cache_key');
        $this->cacheService->invalidate_cache($cache_key);

        return new WP_REST_Response([
            'success' => true,
            'message' => 'Cache cleared successfully'
        ], 200);
    }

    /**
     * Warm analytics cache
     */
    public function warm_cache(WP_REST_Request $request)
    {
        $this->cacheService->warm_cache();

        return new WP_REST_Response([
            'success' => true,
            'message' => 'Cache warmed successfully'
        ], 200);
    }

    /**
     * Get referrers data
     */
    public function get_referrers(WP_REST_Request $request)
    {
        try {
            // Auth handled by RouteAuthMiddleware
            $date_range = AnalyticsHelpers::getDateRange($request);
            $limit = (int) $request->get_param('limit') ?: 10;

            $params = [
                'start' => $date_range['start']->format('Y-m-d'),
                'end' => $date_range['end']->format('Y-m-d'),
                'limit' => $limit
            ];

            $data = $this->cacheService->get_cached_data(
                'referrers',
                $params,
                function () use ($date_range, $limit) {
                    return $this->aggregator->getReferrersData($date_range, $limit);
                }
            );

            $cache_hit = $data['_cache_hit'] ?? false;
            unset($data['_cache_hit'], $data['_cached_at']);

            return new WP_REST_Response([
                'success' => true,
                'results' => array_values($data),
                'meta' => [
                    'total_records' => count($data),
                    'cache_hit' => $cache_hit
                ]
            ], 200);

        } catch (\Exception $e) {
            return new WP_Error('analytics_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Get devices data
     */
    public function get_devices(WP_REST_Request $request)
    {
        try {
            // Auth handled by RouteAuthMiddleware
            $date_range = AnalyticsHelpers::getDateRange($request);

            $params = [
                'start' => $date_range['start']->format('Y-m-d'),
                'end' => $date_range['end']->format('Y-m-d')
            ];

            $data = $this->cacheService->get_cached_data(
                'devices',
                $params,
                function () use ($date_range) {
                    return $this->aggregator->getDevicesData($date_range);
                }
            );

            $cache_hit = $data['_cache_hit'] ?? false;
            unset($data['_cache_hit'], $data['_cached_at']);

            return new WP_REST_Response([
                'success' => true,
                'results' => array_values($data),
                'meta' => [
                    'total_records' => count($data),
                    'cache_hit' => $cache_hit
                ]
            ], 200);

        } catch (\Exception $e) {
            return new WP_Error('analytics_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Get geographic data
     */
    public function get_geographic(WP_REST_Request $request)
    {
        try {
            // Auth handled by RouteAuthMiddleware
            $date_range = AnalyticsHelpers::getDateRange($request);
            $limit = (int) $request->get_param('limit') ?: 10;

            $params = [
                'start' => $date_range['start']->format('Y-m-d'),
                'end' => $date_range['end']->format('Y-m-d'),
                'limit' => $limit
            ];

            $data = $this->cacheService->get_cached_data(
                'geographic',
                $params,
                function () use ($date_range, $limit) {
                    return $this->aggregator->getGeographicData($date_range, $limit);
                }
            );

            $cache_hit = $data['_cache_hit'] ?? false;
            unset($data['_cache_hit'], $data['_cached_at']);

            return new WP_REST_Response([
                'success' => true,
                'results' => array_values($data),
                'meta' => [
                    'total_records' => count($data),
                    'cache_hit' => $cache_hit
                ]
            ], 200);

        } catch (\Exception $e) {
            return new WP_Error('analytics_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Get user engagement
     */
    public function get_user_engagement(WP_REST_Request $request)
    {
        try {
            // Auth handled by RouteAuthMiddleware
            $date_range = AnalyticsHelpers::getDateRange($request);
            $aggregation = $request->get_param('aggregation');
            $engagement_type = $request->get_param('engagement_type');
            $source = $request->get_param('source');

            $params = [
                'start' => $date_range['start']->format('Y-m-d'),
                'end' => $date_range['end']->format('Y-m-d'),
                'aggregation' => $aggregation,
                'type' => $engagement_type,
                'source' => $source
            ];

            $data = $this->cacheService->get_cached_data(
                'user_engagement',
                $params,
                function () use ($date_range, $aggregation, $engagement_type, $source) {
                    return $this->aggregator->getUserEngagementData($date_range, $aggregation, $engagement_type, $source);
                }
            );

            $cache_hit = $data['_cache_hit'] ?? false;
            unset($data['_cache_hit'], $data['_cached_at']);

            return new WP_REST_Response([
                'success' => true,
                'results' => array_values($data),
                'meta' => [
                    'total_records' => count($data),
                    'cache_hit' => $cache_hit
                ],
                'available_types' => $this->engagementTracker->getAvailableEngagementTypes(),
                'available_sources' => $this->engagementTracker->getAvailableEngagementSources(),
            ], 200);

        } catch (\Exception $e) {
            return new WP_Error('analytics_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Track engagement event
     */
    public function track_engagement_event(WP_REST_Request $request)
    {
        try {
            // Auth handled by RouteAuthMiddleware

            $event_data = [
                'user_id' => \get_current_user_id(),
                'event_type' => $request->get_param('event_type'),
                'content_id' => $request->get_param('content_id'),
                'content_type' => $request->get_param('content_type'),
                'source' => $request->get_param('source'),
                'metadata' => $request->get_param('metadata'),
                'timestamp' => \current_time('mysql')
            ];

            if (empty($event_data['event_type'])) {
                return new WP_Error('missing_event_type', 'Event type is required', ['status' => 400]);
            }

            $stored_event = $this->engagementTracker->storeEngagementEvent($event_data);
            $this->cacheService->invalidate_cache('user_engagement');

            return new WP_REST_Response([
                'success' => true,
                'message' => 'Engagement event tracked successfully',
                'event_id' => $stored_event['id'] ?? null
            ], 200);

        } catch (\Exception $e) {
            return new WP_Error('tracking_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Export analytics data
     */
    public function export_analytics(WP_REST_Request $request)
    {
        try {
            // Auth handled by RouteAuthMiddleware
            $format = $request->get_param('format') ?: 'csv';
            $data_type = $request->get_param('data_type') ?: 'visitors';
            $date_range = AnalyticsHelpers::getDateRange($request);

            // Get data based on type
            $data = [];
            switch ($data_type) {
                case 'visitors':
                    $data = $this->calculator->calculateVisitorsData($date_range, 'daily');
                    break;
                case 'pageviews':
                    $data = $this->calculator->calculatePageviewsData($date_range, 'daily');
                    break;
                case 'popular_posts':
                    $data = $this->aggregator->getPopularPostsData($date_range, 50);
                    break;
                case 'kpi_summary':
                    $data = $this->calculator->calculateKPISummary($date_range);
                    break;
                default:
                    return new WP_Error('invalid_data_type', 'Invalid data type for export', ['status' => 400]);
            }

            if (empty($data)) {
                return new WP_Error('no_data', 'No data available for export', ['status' => 404]);
            }

            $filename = sprintf(
                'fleekdash-analytics-%s-%s-%s.%s',
                $data_type,
                $date_range['start']->format('Y-m-d'),
                $date_range['end']->format('Y-m-d'),
                $format
            );

            if ($format === 'csv') {
                return $this->exporter->exportAsCSV($data, $filename);
            } else {
                return $this->exporter->exportAsJSON($data, $filename);
            }

        } catch (\Exception $e) {
            return new WP_Error('export_error', $e->getMessage(), ['status' => 500]);
        }
    }
}
