<?php
/**
 * Kontrola minimální verze PHP pro ElementSell.
 *
 * Poznámky k odolnosti:
 * - nepoužívat znak '<' v podmínkách (FTP/WebFTP ho občas odstraní jako HTML)
 * - PHP 8+ / 9+ hard-allow (nikdy neblokovat touto branou)
 */

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

if ( ! defined( 'ELEMENTSELL_MIN_PHP_VERSION' ) ) {
    define( 'ELEMENTSELL_MIN_PHP_VERSION', '7.4' );
}

/**
 * @param string|null $php_version
 * @param string|null $minimum
 * @return bool
 */
function elementsell_php_version_is_supported( $php_version = null, $minimum = null ) {
    $php_version = null === $php_version ? PHP_VERSION : (string) $php_version;
    $minimum     = null === $minimum ? ELEMENTSELL_MIN_PHP_VERSION : (string) $minimum;

    if ( $php_version === '' || $minimum === '' ) {
        return false;
    }

    // Hard safety: moderní PHP nikdy neblokovat (ochrana proti poškozené kontrole).
    $major = (int) $php_version;
    if ( $major >= 8 ) {
        return true;
    }

    // version_compare bez operátoru: -1 starší, 0 shoda, 1 novější.
    return -1 !== version_compare( $php_version, $minimum );
}

/**
 * @param string|null $php_version
 * @param string|null $minimum
 * @return bool
 */
function elementsell_php_version_should_block_plugin( $php_version = null, $minimum = null ) {
    return ! elementsell_php_version_is_supported( $php_version, $minimum );
}

/**
 * Debug záznam při blokaci / podezřelém stavu.
 *
 * @param string               $reason
 * @param array<string, mixed> $context
 * @return void
 */
function elementsell_php_version_debug_log( $reason, $context = [] ) {
    if ( ! defined( 'WP_CONTENT_DIR' ) ) {
        return;
    }

    $line = wp_json_encode(
        [
            'ts'      => gmdate( 'c' ),
            'reason'  => (string) $reason,
            'php'     => PHP_VERSION,
            'min'     => defined( 'ELEMENTSELL_MIN_PHP_VERSION' ) ? ELEMENTSELL_MIN_PHP_VERSION : '',
            'sapi'    => PHP_SAPI,
            'file'    => defined( 'PF_PLUGIN_FILE' ) ? PF_PLUGIN_FILE : '',
            'pf'      => defined( 'PF_VERSION' ) ? PF_VERSION : '',
            'context' => $context,
        ],
        JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
    );

    if ( ! is_string( $line ) || $line === '' ) {
        return;
    }

    $log_file = trailingslashit( WP_CONTENT_DIR ) . 'elementsell-php-gate.log';

    // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log, WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
    @file_put_contents( $log_file, $line . PHP_EOL, FILE_APPEND | LOCK_EX );

    if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
        error_log( 'ElementSell PHP gate: ' . $line );
    }
}
