<?php
/**
 * Plugin Name:       Platform Helm
 * Plugin URI:        https://wordpress.org/plugins/platform-helm/
 * Description:       A lean, modular content-operations suite for WordPress. Internal link suggestions, orphan-page linking, and role-aware dashboards — done well, together.
 * Version:           0.14.0
 * Requires at least: 6.0
 * Requires PHP:      8.0
 * Author:            Tshepho Joel
 * Author URI:        https://www.linkedin.com/in/tshepho/
 * License:           GPL-2.0-or-later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       platform-helm
 * Domain Path:       /languages
 *
 * @package Platform\Helm
 */

declare( strict_types = 1 );

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

/*
 * Plugin meta constants.
 *
 * IMPORTANT: these are plain string literals, NOT class constants in a
 * namespaced file. Namespaced class constants are compile-time folded by
 * OPcache, which has burned us before on hosts where OPcache is on and the
 * file is replaced in place. Plain define()s in the entry file are safe.
 */
define( 'PLATFORM_HELM_VERSION', '0.14.0' );
define( 'PLATFORM_HELM_FILE', __FILE__ );
define( 'PLATFORM_HELM_DIR', plugin_dir_path( __FILE__ ) );
define( 'PLATFORM_HELM_URL', plugin_dir_url( __FILE__ ) );
define( 'PLATFORM_HELM_BASENAME', plugin_basename( __FILE__ ) );

/*
 * PHP version guard — must pass before any class using 8.0+ syntax is loaded.
 * Fails gracefully with an admin notice rather than a white screen.
 */
if ( version_compare( PHP_VERSION, '8.0', '<' ) ) {
	add_action( 'admin_notices', function () {
		echo '<div class="notice notice-error"><p>';
		echo esc_html__( 'Platform Helm requires PHP 8.0 or higher.', 'platform-helm' );
		echo '</p></div>';
	} );
	return;
}

/*
 * Defensive shutdown handler. Writes any fatal originating inside this plugin
 * to wp-content/uploads/platform-helm-fatal.log so it can be retrieved without
 * SSH or PHP error-log access. Only logs fatals that name this plugin's path,
 * so it never captures unrelated errors.
 */
register_shutdown_function( function () {
	$error = error_get_last();
	if ( ! is_array( $error ) ) {
		return;
	}
	$fatal_types = [ E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR ];
	if ( ! in_array( $error['type'] ?? 0, $fatal_types, true ) ) {
		return;
	}
	$file = (string) ( $error['file'] ?? '' );
	if ( false === strpos( $file, 'platform-helm' ) ) {
		return; // Not us.
	}
	if ( ! function_exists( 'wp_upload_dir' ) ) {
		return;
	}
	$upload_dir = wp_upload_dir();
	if ( ! is_array( $upload_dir ) || empty( $upload_dir['basedir'] ) ) {
		return;
	}
	$log_file = trailingslashit( $upload_dir['basedir'] ) . 'platform-helm-fatal.log';
	$entry    = sprintf(
		"[%s] %s in %s:%d\n",
		gmdate( 'Y-m-d H:i:s' ),
		$error['message'] ?? 'Unknown error',
		$file,
		(int) ( $error['line'] ?? 0 )
	);
	@file_put_contents( $log_file, $entry, FILE_APPEND | LOCK_EX ); // phpcs:ignore
} );

// PSR-4 autoloader.
require_once PLATFORM_HELM_DIR . 'src/Autoloader.php';
\Platform\Helm\Autoloader::register();

/*
 * Freemius SDK — licensing, updates, and the opt-in screen.
 *
 * The freemius/ folder must be present for Pro features to unlock. If the
 * folder is missing (e.g. fresh .org install before the SDK is bundled) the
 * plugin runs in free-only mode without any fatal error.
 *
 * SECRET KEY: never put the secret key here. Public key only.
 */
if ( ! function_exists( 'phelm_fs' ) ) {
	function phelm_fs() {
		global $phelm_fs;
		if ( ! isset( $phelm_fs ) ) {
			$sdk = PLATFORM_HELM_DIR . 'freemius/start.php';
			if ( ! file_exists( $sdk ) ) {
				return null; // SDK not yet installed — free-only mode.
			}
			require_once $sdk;
			$phelm_fs = fs_dynamic_init( [
				'id'                  => '31622',
				'slug'                => 'platform-helm',
				'type'                => 'plugin',
				'public_key'          => 'pk_4301a1375d2a20cc8c7cd662c08da',
				'is_premium'          => false,
				'has_addons'          => false,
				'has_paid_plans'      => true,
				'menu'                => [
					'slug'       => 'platform-helm',
					'first-path' => 'admin.php?page=platform-helm',
					'account'    => false,
					'contact'    => false,
					'support'    => false,
				],
			] );
		}
		return $phelm_fs;
	}
	phelm_fs();
	do_action( 'phelm_fs_loaded' );
}

// Bootstrap. Any failure is logged and surfaced as an admin notice rather than
// taking down the site.
try {
	\Platform\Helm\Plugin::instance()->boot();
} catch ( \Throwable $e ) {
	if ( function_exists( 'error_log' ) ) {
		error_log( sprintf( // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
			'[Platform Helm] Bootstrap failed: %s in %s:%d',
			$e->getMessage(),
			$e->getFile(),
			$e->getLine()
		) );
	}
	add_action( 'admin_notices', function () use ( $e ) {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		echo '<div class="notice notice-error"><p><strong>';
		echo esc_html__( 'Platform Helm failed to load:', 'platform-helm' );
		echo '</strong> ';
		echo esc_html( $e->getMessage() );
		echo '</p></div>';
	} );
}
