<?php

namespace FleekDash\Controllers\Universal;

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

/**
 * System Controller
 *
 * Handles system-level endpoints (stats, installation).
 * Part of Universal Analytics System.
 *
 * @package FleekDash\Controllers\Universal
 * @since 2.2.0
 */
class SystemController
{
    private $universal_service;

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

    /**
     * Get system statistics
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response|WP_Error
     */
    public function get_system_stats(WP_REST_Request $request)
    {
        try {
            $stats = $this->universal_service->getSystemStats();

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

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

    /**
     * Install universal analytics system
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response|WP_Error
     */
    public function install_system(WP_REST_Request $request)
    {
        try {
            $user_id = \get_current_user_id();

            if (!$user_id) {
                return new WP_Error('not_authenticated', 'Authentication required', ['status' => 401]);
            }

            $result = $this->universal_service->install();

            return new WP_REST_Response([
                'success' => true,
                'message' => $result ? 'System installed successfully' : 'System already installed',
                'installed' => $result
            ], 200);

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