<?php

namespace GriffinForms\Admin\Secure;

use GriffinForms\Includes\Security\Capabilities;

class CapabilityMatrix extends \GriffinForms\Admin\Secure\Settings
{
    protected function secureApiFeatureEnabled($value): int
    {
        return !empty($value) ? 1 : 0;
    }

    protected function secureApiKillSwitch($value): int
    {
        return !empty($value) ? 1 : 0;
    }

    protected function secureApiRoleCapabilityMap($value): array
    {
        if (is_string($value)) {
            $decoded = json_decode($value, true);
            $value = is_array($decoded) ? $decoded : [];
        }

        return Capabilities::normalizeRoleMatrix($value);
    }

    protected function secureApiUserCapabilityOverrides($value): array
    {
        if (is_string($value)) {
            $decoded = json_decode($value, true);
            $value = is_array($decoded) ? $decoded : [];
        }

        return Capabilities::normalizeUserOverrides($value);
    }

    protected function secureApiWebhookSubmissionCreatedEnabled($value): int
    {
        return !empty($value) ? 1 : 0;
    }

    protected function secureApiWebhookSubmissionCreatedUrl($value): string
    {
        $url = esc_url_raw((string) $value);
        if ($url === '') {
            return '';
        }

        if (!wp_http_validate_url($url)) {
            $this->errors['api_webhook_submission_created_url'] = __('Invalid webhook URL.', 'griffinforms-form-builder');
            return '';
        }

        return $url;
    }

    protected function secureApiWebhookSubmissionCreatedSecret($value): string
    {
        return sanitize_text_field((string) $value);
    }

    protected function secureApiWebhookSubmissionCreatedTimeout($value): int
    {
        $timeout = absint($value);
        if ($timeout < 3) {
            $timeout = 3;
        }
        if ($timeout > 30) {
            $timeout = 30;
        }

        return $timeout;
    }
}
