<?php
/**
 * Plugin data-directory bootstrap.
 *
 * The plugin stores logs + trashed files under uploads/cwpm/ so it complies
 * with the wp.org rule that plugins must keep user data inside the uploads
 * basedir. This class ensures the cwpm/ parent directory exists on first
 * load and writes the .htaccess + index.php protection stubs that defend
 * the folder against direct HTTP access. Idempotent via an option flag.
 *
 * @package CoffeeWP_Media_Cleanup
 */

namespace CWPM\Core;

defined( 'ABSPATH' ) || exit;

class PathsMigration {

	/**
	 * Option flag — set to '1' once the migration completes.
	 */
	const OPTION_FLAG = 'cwpm_paths_migrated_v1';

	/**
	 * Ensure the plugin's data directory exists under uploads.
	 *
	 * Called on `plugins_loaded` from the plugin bootstrap. Idempotent: the
	 * option flag prevents repeat work after the first successful run.
	 *
	 * @return void
	 */
	public static function maybe_run() {
		if ( '1' === get_option( self::OPTION_FLAG ) ) {
			return;
		}

		$upload_dir = wp_upload_dir();
		if ( ! empty( $upload_dir['error'] ) ) {
			return;
		}

		self::ensure_parent( $upload_dir['basedir'] . '/cwpm' );

		update_option( self::OPTION_FLAG, '1', false );
	}

	/**
	 * Create the cwpm/ parent dir under uploads and write protection stubs.
	 *
	 * Logger::ensure_logs_dir() and Trash::ensure_trash_dir() write their own
	 * .htaccess+index.php into the leaf dirs. Adding them at the parent too
	 * defends against any future code that creates a sibling subdir before
	 * those leaf bootstrap calls run.
	 *
	 * @param string $dir Absolute path to create.
	 * @return void
	 */
	private static function ensure_parent( $dir ) {
		if ( ! is_dir( $dir ) ) {
			wp_mkdir_p( $dir );
		}

		$htaccess = $dir . '/.htaccess';
		if ( ! file_exists( $htaccess ) ) {
			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
			file_put_contents( $htaccess, "deny from all\n" );
		}

		$index = $dir . '/index.php';
		if ( ! file_exists( $index ) ) {
			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
			file_put_contents( $index, "<?php // Silence is golden.\n" );
		}
	}
}
