<?php

namespace PloverCRM\Core\Api\V1;

use PloverCRM\Core\Api\AbstractEndpoint;
use PloverCRM\Common\Permissions;
use PloverCRM\Common\RoleManager;
use PloverCRM\Core\Services\GeneralSettingsPayloadBuilder;
use WP_REST_Request;

/**
 * Active Columns Endpoint
 * 
 * GET /wp-json/plover-crm/v1/settings/active-columns
 * PUT /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', 'PUT'];
    }

    public function checkPermission(WP_REST_Request $request)
    {
        $passwordAuth = $this->authenticateWithPassword($request);

        if ($passwordAuth) {
            wp_set_current_user((int) $passwordAuth['user_id']);
        }

        $action = $request->get_method() === 'GET' ? 'view' : 'manage';

        if (!Permissions::canAccessSetting('lead_table', $action)) {
            return $this->error(
                $action === 'view'
                    ? 'You do not have permission to view lead table settings.'
                    : 'You do not have permission to manage lead table settings.',
                403,
                $action === 'view'
                    ? 'lead_table_read_permission_denied'
                    : 'lead_table_manage_permission_denied'
            );
        }

        return true;
    }

    public function handle(WP_REST_Request $request)
    {
        if ($request->get_method() === 'PUT') {
            return $this->updateActiveColumns($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($this->serializeActiveColumns($activeColumns));
    }

    private function updateActiveColumns(WP_REST_Request $request)
    {
        $payload = $request->get_json_params();

        if (!is_array($payload) || !is_array($payload['activeColumns'] ?? null)) {
            return $this->error(
                'Active columns must be an array of field slugs.',
                422,
                'active_columns_invalid_payload'
            );
        }

        $validColumns = GeneralSettingsPayloadBuilder::getSelectableColumnSlugs($this->container);
        $activeColumns = array_values(array_filter(array_map(static function ($column) {
            return sanitize_text_field((string) $column);
        }, $payload['activeColumns']), static function ($column) use ($validColumns) {
            return $column !== '' && in_array($column, $validColumns, true);
        }));

        update_option(self::OPTION_NAME, $activeColumns);

        return $this->success($this->serializeActiveColumns($activeColumns), ['updated' => true]);
    }

    private function serializeActiveColumns(array $activeColumns): array
    {
        return [
            'activeColumns' => $activeColumns,
            'active_columns' => $activeColumns,
        ];
    }
}
