<?php
/**
 * Shared capability checks for the builder UI and REST API.
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Support;

final class Capabilities {

	/**
	 * Ensure administrator has builder caps (covers sites where activation hook never ran).
	 */
	public static function ensure_admin_caps(): void {
		$role = get_role( 'administrator' );
		if ( $role && ! $role->has_cap( 'edit_aura_builder' ) ) {
			$role->add_cap( 'edit_aura_builder' );
		}
		// Editors who design pages should reach Theme Builder pages too.
		$editor = get_role( 'editor' );
		if ( $editor && ! $editor->has_cap( 'edit_aura_builder' ) ) {
			$editor->add_cap( 'edit_aura_builder' );
		}
	}

	/**
	 * Can open the visual builder (pages, posts, or theme chrome).
	 */
	public static function can_use_builder(): bool {
		return current_user_can( 'manage_options' )
			|| current_user_can( 'edit_theme_options' )
			|| current_user_can( 'edit_pages' )
			|| current_user_can( 'edit_posts' )
			|| current_user_can( 'edit_aura_builder' );
	}

	/**
	 * Can edit header / footer / single theme parts (site chrome).
	 * Editors with edit_pages are allowed — they already redesign page layouts.
	 */
	public static function can_edit_theme_parts(): bool {
		return current_user_can( 'manage_options' )
			|| current_user_can( 'edit_theme_options' )
			|| current_user_can( 'edit_pages' )
			|| current_user_can( 'edit_aura_builder' );
	}

	/**
	 * Can edit a specific post/page document.
	 */
	public static function can_edit_post( int $post_id ): bool {
		if ( $post_id <= 0 ) {
			return false;
		}
		if ( current_user_can( 'edit_post', $post_id ) ) {
			return true;
		}
		// Fallback for admins on edge cases (custom post status / ownership).
		return current_user_can( 'manage_options' );
	}

	/**
	 * Plugin settings (construction mode, license, etc.).
	 */
	public static function can_manage_settings(): bool {
		return current_user_can( 'manage_options' );
	}
}
