<?php

/**
 * Ping Service
 *
 * @package ArraySubs\Features\MainAdmin\Services
 */

namespace ArraySubs\Features\MainAdmin\Services;

defined('ABSPATH') || exit;

/**
 * Send a lightweight site ping to the update checker endpoint.
 */
class Updater
{
    /**
     * Enable auto-loading.
     *
     * @var bool
     */
    public static $loadable = true;

    private const TRANSIENT_KEY = 'arraysubs_mainadmin_ping_schedule';
    private const ENDPOINT_URL  = 'https://arrayhash.com/update-checker/';

    public function __construct()
    {
        \add_action('wp_loaded', [$this, 'maybeSendPing']);
    }

    /**
     * Send a ping at most once per hour.
     *
     * @return void
     */
    public function maybeSendPing(): void
    {
        if (!$this->shouldSendPing()) {
            return;
        }

        $payload = $this->getPayload();

        foreach (['plugin_version', 'site_title', 'site_url', 'site_email'] as $field) {
            if (empty($payload[$field])) {
                return;
            }
        }

        \set_transient(self::TRANSIENT_KEY, 1, HOUR_IN_SECONDS);

        $res = \wp_remote_post(
            self::ENDPOINT_URL,
            [
                'timeout'     => 5,
                'blocking'    => true,
                'sslverify'   => true,
                'user-agent'  => \sprintf('WordPress/%s; %s', \get_bloginfo('version'), \home_url('/')),
                'headers'     => [
                    'Content-Type'     => 'application/json; charset=utf-8',
                    'X-ArraySubs-Ping' => '1',
                ],
                'body'        => \wp_json_encode($payload) ?: '{}',
                'data_format' => 'body',
            ]
        );
    }

    /**
     * Determine whether the current request should trigger a ping.
     *
     * @return bool
     */
    private function shouldSendPing(): bool
    {
        if (\wp_doing_ajax() || \wp_doing_cron() || \wp_installing()) {
            return false;
        }

        if ((\defined('REST_REQUEST') && REST_REQUEST) || (\defined('XMLRPC_REQUEST') && XMLRPC_REQUEST) || (\defined('WP_CLI') && WP_CLI)) {
            return false;
        }

        return false === \get_transient(self::TRANSIENT_KEY);
    }

    /**
     * Build the ping payload.
     *
     * @return array<string, string>
     */
    private function getPayload(): array
    {
        return [
            'plugin_version' => \sanitize_text_field((string) ARRAYSUBS_VERSION),
            'site_title'     => \sanitize_text_field(\html_entity_decode(\get_bloginfo('name'), ENT_QUOTES | ENT_HTML5, 'UTF-8')),
            'site_url'       => \esc_url_raw(\home_url('/')),
            'site_email'     => \sanitize_email((string) \get_option('admin_email')),
        ];
    }
}
