<?php

namespace PloverCRM\Core\Api\V1;

use PloverCRM\Core\Api\AbstractEndpoint;
use PloverCRM\Core\Services\PlaceholderService;
use WP_REST_Request;

/**
 * Placeholders Endpoint
 * 
 * GET /wp-json/plover-crm/v1/placeholders
 * 
 * Returns all available placeholders for templates
 */
class PlaceholdersEndpoint extends AbstractEndpoint
{
    public function getRoute(): string
    {
        return '/placeholders';
    }

    public function getMethod()
    {
        return 'GET';
    }

    public function handle(WP_REST_Request $request)
    {
        $crm = $this->container->get('crm');

        if (!$crm->isAvailable()) {
            return $this->error('CRM not available', 503);
        }

        $placeholders = PlaceholderService::getAvailablePlaceholders();

        // Group placeholders by category
        $grouped = [];
        foreach ($placeholders as $placeholder) {
            $group = $placeholder['group'] ?? 'Other';
            if (!isset($grouped[$group])) {
                $grouped[$group] = [];
            }
            $grouped[$group][] = [
                'key' => $placeholder['key'],
                'label' => $placeholder['label'],
            ];
        }

        return $this->success([
            'placeholders' => $placeholders,
            'grouped' => $grouped,
        ]);
    }
}
