<?php

namespace ProudNerds\Helpers;

class Ip
{
    /**
     * Get the client's IP address
     *
     * @return string
     */
    public static function getClientIp(): string
    {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }

        return $ip;
    }

    /**
     * Check if the client's IP address is localhost
     *
     * @return bool
     */
    public static function isLocalhost(): bool
    {
        return $_SERVER['REMOTE_ADDR'] === '127.0.0.1';
    }

    /**
     * Get the allowed IP addresses
     *
     * @return array
     */
    public static function getAllowedIps(): array
    {
        // Get allowed ips from ACF
        $allowedIps = get_field('allowed_ips', 'option') ?: [];

        if (empty($allowedIps)) {
            $allowedIps = [];
        }

        $allowedIps = array_map(function ($ip) {
            return $ip['ip'];
        }, $allowedIps);

        // Merge in the environment variable
        $envAllowedIps = explode(',', getenv('ALLOWED_IPS'));
        $envAllowedIps = array_filter($envAllowedIps);

        return array_merge($allowedIps, $envAllowedIps);
    }

    /**
     * Check if the client's IP address is allowed
     *
     * @return bool
     */
    public static function isAllowedIp(): bool
    {
        return static::isLocalhost() ?: in_array(static::getClientIp(), static::getAllowedIps());
    }
}
