<?php

/**
 * List-table columns and row actions for the built-blocks library.
 *
 * @package LolaCore\BlockBuilder\Admin
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

namespace LolaCore\BlockBuilder\Admin;

use LolaCore\BlockBuilder\Gate\BlockBuilderGate;
use LolaCore\BlockBuilder\PostType\BlockPostType;

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

/**
 * Adds Version, Status columns and Playground / Install row actions.
 *
 * Extension point: `lolacore_block_builder_row_actions` lets addons inject
 * attributed actions (e.g. FSE Studio "Place in template") without renaming
 * the Block Builder screen.
 */
class LibraryColumns {

	public function register(): void {
		add_filter('manage_' . BlockPostType::POST_TYPE . '_posts_columns', array($this, 'addColumns'));
		add_action(
			'manage_' . BlockPostType::POST_TYPE . '_posts_custom_column',
			array($this, 'renderColumn'),
			10,
			2
		);
		add_filter('post_row_actions', array($this, 'addRowActions'), 10, 2);
	}

	/**
	 * @param array<string, string> $columns
	 * @return array<string, string>
	 */
	public function addColumns( array $columns ): array {
		$new = array();

		foreach ($columns as $key => $label) {
			$new[ $key ] = $label;

			if ($key === 'title') {
				$new['lc_bb_version'] = __('Version', 'lolacore');
				$new['lc_bb_status']  = __('Status', 'lolacore');
				$new['lc_bb_block']   = __('Block name', 'lolacore');
			}
		}

		return $new;
	}

	public function renderColumn( string $column, int $post_id ): void {
		switch ($column) {
			case 'lc_bb_version':
				echo esc_html((string) max(1, (int) get_post_meta($post_id, BlockPostType::META_VERSION, true)));
				break;

			case 'lc_bb_status':
				echo esc_html(self::installStatusLabel($post_id));
				break;

			case 'lc_bb_block':
				echo esc_html((string) get_post_meta($post_id, BlockPostType::META_NAME, true));
				break;
		}
	}

	/**
	 * @param array<string, string> $actions
	 * @param \WP_Post              $post
	 * @return array<string, string>
	 */
	public function addRowActions( array $actions, \WP_Post $post ): array {
		if ($post->post_type !== BlockPostType::POST_TYPE) {
			return $actions;
		}

		if (! current_user_can('manage_options')) {
			return $actions;
		}

		$post_id = (int) $post->ID;

		$actions['lolacore_bb_playground'] = sprintf(
			'<a href="#" class="lolacore-bb-action lolacore-bb-playground" data-post-id="%1$d">%2$s</a>',
			$post_id,
			esc_html__('Try in Playground', 'lolacore')
		);

		if (BlockBuilderGate::isInstallAllowed($post_id)) {
			$actions['lolacore_bb_install'] = sprintf(
				'<a href="#" class="lolacore-bb-action lolacore-bb-install" data-post-id="%1$d">%2$s</a>',
				$post_id,
				esc_html__('Install', 'lolacore')
			);
		} else {
			$actions['lolacore_bb_install'] = sprintf(
				'<span class="lolacore-bb-action-disabled" title="%1$s">%2$s</span>',
				esc_attr__('Test in Playground first, then confirm it works before installing.', 'lolacore'),
				esc_html__('Install', 'lolacore')
			);
		}

		if (self::isInstalledOnDisk($post_id)) {
			$actions['lolacore_bb_uninstall'] = sprintf(
				'<a href="#" class="lolacore-bb-action lolacore-bb-uninstall" data-post-id="%1$d">%2$s</a>',
				$post_id,
				esc_html__('Uninstall', 'lolacore')
			);
		}

		/**
		 * Filters row actions on the Block Builder library list table.
		 *
		 * @param array<string, string> $actions Row action HTML keyed by slug.
		 * @param \WP_Post              $post    Built block post.
		 */
		return apply_filters('lolacore_block_builder_row_actions', $actions, $post);
	}

	public static function installStatusLabel( int $post_id ): string {
		if (! self::isInstalledOnDisk($post_id)) {
			return __('Saved only', 'lolacore');
		}

		return __('Installed', 'lolacore');
	}

	public static function isInstalledOnDisk( int $post_id ): bool {
		$block_slug = (string) get_post_meta($post_id, BlockPostType::META_BLOCK_SLUG, true);
		$stored     = (string) get_post_meta($post_id, BlockPostType::META_PLUGIN_SLUG, true);
		$install_slug = BlockPostType::resolveInstallSlug($block_slug, $stored);

		if ($install_slug === '') {
			return false;
		}

		$directory = BlockPostType::runtimePathForSlug($install_slug);

		return $directory !== '' && is_dir($directory) && file_exists($directory . '/block.json');
	}

	public static function runtimeDirectoryForSlug( string $install_slug ): string {
		return BlockPostType::runtimePathForSlug($install_slug);
	}
}
