<?php

namespace FleekDash\Controllers\Universal;

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

/**
 * Categories Controller
 * 
 * Handles analytics categories endpoints.
 * Part of Universal Analytics System.
 * 
 * @package FleekDash\Controllers\Universal
 * @since 2.2.0
 */
class CategoriesController
{
    private $universal_service;

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

    /**
     * Get all analytics categories
     * 
     * @param WP_REST_Request $request
     * @return WP_REST_Response|WP_Error
     */
    public function get_categories(WP_REST_Request $request)
    {
        try {
            $active_only = $request->get_param('active_only') !== 'false';
            $categories = $this->universal_service->getCategories($active_only);

            return new WP_REST_Response([
                'success' => true,
                'results' => $categories,
                'meta' => [
                    'total' => count($categories),
                    'active_only' => $active_only
                ]
            ], 200);

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

    /**
     * Get category by slug
     * 
     * @param WP_REST_Request $request
     * @return WP_REST_Response|WP_Error
     */
    public function get_category(WP_REST_Request $request)
    {
        try {
            $slug = $request->get_param('slug');

            if (!$slug) {
                return new WP_Error('missing_slug', 'Category slug is required', ['status' => 400]);
            }

            $category = $this->universal_service->getCategoryBySlug($slug);

            if (!$category) {
                return new WP_Error('category_not_found', 'Category not found', ['status' => 404]);
            }

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

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

