<?php

namespace FleekDash\Controllers\Universal;

use WP_REST_Request;
use WP_REST_Response;
use WP_Error;
use FleekDash\Services\UniversalAnalyticsService;

/**
 * Data Controller
 *
 * Handles metric data endpoints.
 * Part of Universal Analytics System.
 *
 * @package FleekDash\Controllers\Universal
 * @since 2.2.0
 */
class DataController
{
    private $universal_service;

    public function __construct()
    {
        $this->universal_service = UniversalAnalyticsService::getInstance();
    }

    /**
     * Get metric data
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response|WP_Error
     */
    public function get_metric_data(WP_REST_Request $request)
    {
        try {
            $metric = $request->get_param('metric');
            $category = $request->get_param('category');
            $sources = $request->get_param('sources');
            $range = $request->get_param('range') ?: '30d';
            $start_date = $request->get_param('start_date');
            $end_date = $request->get_param('end_date');
            $aggregation = $request->get_param('aggregation') ?: 'daily';
            $breakdown = $request->get_param('breakdown') === '1';

            if (!$metric) {
                return new WP_Error('missing_metric', 'Metric is required', ['status' => 400]);
            }

            // Calculate date range
            $date_range = $this->calculate_date_range($range, $start_date, $end_date);

            // Parse sources
            $source_array = $sources ? explode(',', $sources) : null;

            $data = $this->universal_service->getMetricData(
                $metric,
                $date_range['start'],
                $date_range['end'],
                $source_array,
                $aggregation
            );

            return new WP_REST_Response([
                'success' => true,
                'results' => $data,
                'meta' => [
                    'metric' => $metric,
                    'category' => $category,
                    'sources' => $source_array,
                    'date_range' => $date_range,
                    'aggregation' => $aggregation,
                    'breakdown' => $breakdown,
                    'total_records' => count($data)
                ]
            ], 200);

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

    /**
     * Get multiple metrics data
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response|WP_Error
     */
    public function get_multiple_metrics_data(WP_REST_Request $request)
    {
        try {
            $metrics = $request->get_param('metrics');
            $sources = $request->get_param('sources');
            $range = $request->get_param('range') ?: '30d';
            $start_date = $request->get_param('start_date');
            $end_date = $request->get_param('end_date');

            if (!$metrics) {
                return new WP_Error('missing_metrics', 'Metrics are required', ['status' => 400]);
            }

            $metrics_array = explode(',', $metrics);
            $date_range = $this->calculate_date_range($range, $start_date, $end_date);
            $source_array = $sources ? explode(',', $sources) : null;

            $data = $this->universal_service->getMultipleMetricsData(
                $metrics_array,
                $date_range['start'],
                $date_range['end'],
                $source_array
            );

            return new WP_REST_Response([
                'success' => true,
                'results' => $data,
                'meta' => [
                    'metrics' => $metrics_array,
                    'sources' => $source_array,
                    'date_range' => $date_range,
                    'total_metrics' => count($metrics_array)
                ]
            ], 200);

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

    /**
     * Calculate date range from parameters
     *
     * @param string $range Range preset
     * @param string|null $start_date Custom start date
     * @param string|null $end_date Custom end date
     * @return array Date range
     */
    private function calculate_date_range($range, $start_date, $end_date)
    {
        if ($start_date && $end_date) {
            return [
                'start' => $start_date,
                'end' => $end_date
            ];
        }

        $end = new \DateTime();
        $start = clone $end;

        switch ($range) {
            case '24h':
                $start->modify('-1 day');
                break;
            case '7d':
                $start->modify('-7 days');
                break;
            case '30d':
                $start->modify('-30 days');
                break;
            case '90d':
                $start->modify('-90 days');
                break;
            default:
                $start->modify('-30 days');
        }

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