<?php
/**
 * Keeps the form page out of every cache layer we know about.
 *
 * @package SkyServers\Retragere
 */

declare(strict_types=1);

namespace SkyServers\Retragere\Wp;

/**
 * A cached form page means a stale nonce and a silent submit failure - the kind
 * of defect a shop discovers through a complaint, not through a test.
 */
final class CacheExclusion
{
    public static function apply(): void
    {
        // phpcs:disable WordPress.NamingConventions.PrefixAllGlobals -- names owned by the cache plugins that read them.
        if (!defined('DONOTCACHEPAGE')) {
            define('DONOTCACHEPAGE', true);
        }

        if (!defined('DONOTCACHEOBJECT')) {
            define('DONOTCACHEOBJECT', true);
        }

        if (!defined('DONOTCACHEDB')) {
            define('DONOTCACHEDB', true);
        }

        do_action('litespeed_control_set_nocache', 'pagina de retragere din contract');
        // phpcs:enable WordPress.NamingConventions.PrefixAllGlobals

        add_filter('rocket_cache_reject_uri', [self::class, 'rejectUri']);

        nocache_headers();
    }

    /**
     * @param string[] $uris
     *
     * @return string[]
     */
    public static function rejectUri(array $uris): array
    {
        $pageId = (int) Settings::get('page_id');

        if ($pageId > 0) {
            $path = wp_parse_url((string) get_permalink($pageId), PHP_URL_PATH);

            if (is_string($path) && '' !== $path) {
                $uris[] = $path;
            }
        }

        return $uris;
    }
}
