<?php

namespace PDFEmbedder\Helpers;

use PDFEmbedder\Admin\MediaLibrary;

/**
 * Helper methods to perform various checks across the plugin.
 *
 * @since 4.7.0
 */
class Check {

	/**
	 * Check whether the string is json-encoded.
	 *
	 * @since 4.7.0
	 *
	 * @param string $json A string.
	 *
	 * @return bool
	 */
	public static function is_json( $json ): bool {

		return (
			is_string( $json ) &&
			is_array( json_decode( $json, true ) ) &&
			json_last_error() === JSON_ERROR_NONE
		);
	}

	/**
     * Check whether the site is in the debug mode.
	 *
	 * @since 4.7.0
	 */
	public static function is_debug(): bool {

		return defined( 'WP_DEBUG' ) && WP_DEBUG;
	}

	/**
	 * Check whether the site is in the script debug mode.
	 *
	 * @since 4.8.0
	 */
	public static function is_script_debug(): bool {

		return defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG;
	}

	/**
	 * Check whether the site is in the heartbeat mode.
	 *
	 * @since 4.8.0
	 */
	public static function is_heartbeat(): bool {

		// phpcs:ignore WordPress.Security.NonceVerification.Missing
		return wp_doing_ajax() && isset( $_POST['action'] ) && $_POST['action'] === 'heartbeat';
	}

	/**
	 * Whether a PDF URL points at the `/wp-content/uploads/securepdfs/` folder
	 * owned by the Pro plan's Secure\Process pipeline. Lives in lite because
	 * such URLs persist in post content after a Pro→lower-plan downgrade or
	 * a full premium uninstall, and lite remains the only renderer in that
	 * scenario.
	 *
	 * @since 5.0.0
	 *
	 * @param string $url Absolute or relative URL (works equally on file paths).
	 */
	public static function is_secure_pdf_url( string $url ): bool {

		return str_contains( $url, '/securepdfs/' );
	}

	/**
	 * We can't use is_attachment() here to process only PDF attachment pages files.
	 *
	 * @since 4.9.0
	 */
	public static function is_pdf_attachment(): bool {

		global $post;

		return isset( $post, $post->post_type, $post->post_mime_type ) &&
			$post->post_type === 'attachment' && $post->post_mime_type === MediaLibrary::MIME_TYPE &&
			is_singular();
	}
}
