<?php

declare(strict_types=1);

namespace SiteFort\Includes;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Proxy provider presets with known trusted IP ranges.
 *
 * Provides hardcoded CIDR ranges for popular reverse proxy providers
 * (Cloudflare, etc.) so users can select a preset instead of manually
 * entering IP ranges. Ranges sourced from official provider documentation.
 *
 */
class ProxyPresets {

    public const PRESET_NONE       = 'none';
    public const PRESET_CLOUDFLARE = 'cloudflare';
    public const PRESET_CUSTOM     = 'custom';

    public const VALID_PRESETS = [
        self::PRESET_NONE,
        self::PRESET_CLOUDFLARE,
        self::PRESET_CUSTOM,
    ];

    /**
     * Cloudflare IPv4 ranges.
     *
     * Source: https://www.cloudflare.com/ips-v4
     */
    private const CLOUDFLARE_IPV4 = [
        '173.245.48.0/20',
        '103.21.244.0/22',
        '103.22.200.0/22',
        '103.31.4.0/22',
        '141.101.64.0/18',
        '108.162.192.0/18',
        '190.93.240.0/20',
        '188.114.96.0/20',
        '197.234.240.0/22',
        '198.41.128.0/17',
        '162.158.0.0/15',
        '104.16.0.0/13',
        '104.24.0.0/14',
        '172.64.0.0/13',
        '131.0.72.0/22',
    ];

    /**
     * Cloudflare IPv6 ranges.
     *
     * Source: https://www.cloudflare.com/ips-v6
     */
    private const CLOUDFLARE_IPV6 = [
        '2400:cb00::/32',
        '2606:4700::/32',
        '2803:f800::/32',
        '2405:b500::/32',
        '2405:8100::/32',
        '2a06:98c0::/29',
        '2c0f:f248::/32',
    ];

    /**
     * Get CIDR ranges for a preset.
     *
     * @param string $preset One of the PRESET_* constants.
     * @return string[] Array of CIDR ranges.
     */
    public static function get_ranges( string $preset ): array {
        if ( $preset === self::PRESET_CLOUDFLARE ) {
            return array_merge( self::CLOUDFLARE_IPV4, self::CLOUDFLARE_IPV6 );
        }

        return [];
    }

    /**
     * Get all available presets with metadata for the frontend dropdown.
     *
     * @return array<string, array{label: string, range_count: int}>
     */
    public static function get_all(): array {
        return [
            self::PRESET_NONE => [
                'label'       => 'None',
                'range_count' => 0,
            ],
            self::PRESET_CLOUDFLARE => [
                'label'       => 'Cloudflare',
                'range_count' => count( self::CLOUDFLARE_IPV4 ) + count( self::CLOUDFLARE_IPV6 ),
            ],
            self::PRESET_CUSTOM => [
                'label'       => 'Custom',
                'range_count' => 0,
            ],
        ];
    }

    /**
     * Validate a preset value.
     *
     * @param string $preset Preset to validate.
     * @return bool
     */
    public static function is_valid( string $preset ): bool {
        return in_array( $preset, self::VALID_PRESETS, true );
    }
}
