<?php
/**
 * Backup storage location.
 *
 * Per the WordPress.org guidelines, plugin-created files live in the uploads
 * directory under a folder named after the plugin slug:
 *
 *     wp_upload_dir()['basedir'] . '/backreload'
 *
 * The folder is created on demand and hardened with a deny-all `.htaccess`
 * plus an empty `index.php` so backup archives are never web-accessible. The
 * backup engine also skips this directory when archiving the uploads folder
 * (see ArchiveWriter's absolute skip), so it never backs up its own backups.
 *
 * @package Backreload
 */

namespace Backreload;

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

final class Storage {

	/** Cached absolute root for the current request. */
	private static ?string $root = null;

	/**
	 * Absolute path to the plugin's storage root, created + protected on first
	 * use. Example: /var/www/wp-content/uploads/backreload
	 */
	public static function root(): string {
		if ( null !== self::$root ) {
			return self::$root;
		}
		$uploads = wp_get_upload_dir();
		$dir     = rtrim( (string) $uploads['basedir'], '/\\' ) . '/backreload';

		if ( ! is_dir( $dir ) ) {
			wp_mkdir_p( $dir );
		}
		self::protect( $dir );

		return self::$root = $dir;
	}

	/**
	 * Drop a deny-all `.htaccess` and a silent `index.php` into $dir so the
	 * backup archives it holds can't be downloaded over HTTP.
	 */
	public static function protect( string $dir ): void {
		if ( is_dir( $dir ) && ! file_exists( $dir . '/.htaccess' ) ) {
			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- One-time write of a protective deny rule into the plugin's own storage dir; WP_Filesystem isn't loaded in cron/REST contexts.
			@file_put_contents( $dir . '/.htaccess', "deny from all\n" );
		}
		if ( is_dir( $dir ) && ! file_exists( $dir . '/index.php' ) ) {
			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- One-time write of a silence-is-golden index into the plugin's own storage dir.
			@file_put_contents( $dir . '/index.php', "<?php // silence is golden\n" );
		}
	}
}
