<?php
/**
 * Cache purge helpers for automatic translation flows.
 *
 * @package WPR_Translate
 */

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

/**
 * Trigger the WPResidence cache purge admin action.
 *
 * @return true|WP_Error
 */
function wpr_translate_purge_wpestate_cache() {
    // Build a signed purge request for the WPResidence admin-post action.
    $purge_url = admin_url( 'admin-post.php' );
    $nonce     = wp_create_nonce( 'wpestate_purge_cache' );
    $cookies   = array();

    foreach ( $_COOKIE as $cookie_name => $cookie_value ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        $cookies[] = new WP_Http_Cookie(
            array(
                'name'  => sanitize_text_field( $cookie_name ),
                'value' => sanitize_text_field( wp_unslash( $cookie_value ) ),
            )
        );
    }

    $response = wp_remote_post(
        $purge_url,
        array(
            'timeout'     => 30,
            'redirection' => 5,
            'cookies'     => $cookies,
            'body'        => array(
                'action'   => 'wpestate_purge_cache',
                '_wpnonce' => $nonce,
            ),
        )
    );

    if ( is_wp_error( $response ) ) {
        return $response;
    }

    $status_code = (int) wp_remote_retrieve_response_code( $response );

    if ( $status_code < 200 || $status_code >= 400 ) {
        $error = new WP_Error(
            'wpr_translate_cache_purge_failed',
            sprintf(
                /* translators: %d: HTTP status code returned by purge endpoint. */
                __( 'Cache purge failed with HTTP status %d.', 'wpr-translate' ),
                $status_code
            )
        );

        return $error;
    }

    return true;
}
