<?php

namespace PloverCRM\Core\Api\V1;

use PloverCRM\Core\Api\AbstractEndpoint;
use PloverCRM\Common\RoleManager;
use WP_REST_Request;

/**
 * Active Columns Endpoint
 * 
 * GET /wp-json/plover-crm/v1/settings/active-columns
 * 
 * Returns the list of active (visible) columns for contacts table
 * Filtered by user's read permissions
 */
class ActiveColumnsEndpoint extends AbstractEndpoint
{
    const OPTION_NAME = 'plover_crm_active_columns';
    
    const DEFAULT_COLUMNS = [
        "full_name",
        "email",
        "phone",
        "city",
        "country",
        "created_at",
        "stage-plover-crm"
    ];

    public function getRoute(): string
    {
        return '/settings/active-columns';
    }

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

    public function handle(WP_REST_Request $request)
    {
        $activeColumns = get_option(self::OPTION_NAME, self::DEFAULT_COLUMNS);
        
        // Ensure it's an array
        if (!is_array($activeColumns)) {
            $activeColumns = self::DEFAULT_COLUMNS;
        }

        // Filter by user's read permissions
        $user = wp_get_current_user();
        if ($user && $user->ID) {
            // Super admin sees all columns
            if (!RoleManager::isSuperAdmin($user->ID)) {
                $activeColumns = array_values(array_filter($activeColumns, function($column) use ($user) {
                    return RoleManager::checkFieldPermission($user->ID, $column, 'read');
                }));
            }
        }

        return $this->success([
            'active_columns' => $activeColumns
        ]);
    }
}
