<?php

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

declare(strict_types=1);

namespace LolaCore\PluginBuilder\Admin;

use LolaCore\PluginBuilder\Gate\PlaygroundGate;
use LolaCore\PluginBuilder\PostType\PluginPostType;

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

/**
 * Adds Version, Status columns and Playground / Install row actions.
 */
class LibraryColumns {

	/**
	 * Register list-table filters.
	 */
	public function register(): void {
		add_filter('manage_' . PluginPostType::POST_TYPE . '_posts_columns', array($this, 'addColumns'));
		add_action(
			'manage_' . PluginPostType::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 Existing 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_pb_version'] = __('Version', 'lolacore');
				$new['lc_pb_status']  = __('Status', 'lolacore');
			}
		}

		return $new;
	}

	/**
	 * @param string $column  Column key.
	 * @param int    $post_id Post ID.
	 */
	public function renderColumn( string $column, int $post_id ): void {
		switch ($column) {
			case 'lc_pb_version':
				echo esc_html((string) max(1, (int) get_post_meta($post_id, PluginPostType::META_VERSION, true)));
				break;

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

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

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

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

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

		if (PlaygroundGate::isInstallAllowed($post_id)) {
			$actions['lolacore_pb_install'] = sprintf(
				'<a href="#" class="lolacore-pb-action lolacore-pb-install" data-post-id="%1$d">%2$s</a>',
				$post_id,
				esc_html__('Install', 'lolacore')
			);
		} else {
			$actions['lolacore_pb_install'] = sprintf(
				'<span class="lolacore-pb-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')
			);
		}

		return $actions;
	}

	/**
	 * Human-readable install status for the list table.
	 */
	public static function installStatusLabel( int $post_id ): string {
		if (! self::isInstalledOnDisk($post_id)) {
			return __('Saved only', 'lolacore');
		}

		$slug = sanitize_title((string) get_post_meta($post_id, PluginPostType::META_SLUG, true));
		if ($slug !== '' && function_exists('is_plugin_active') && is_plugin_active($slug . '/' . $slug . '.php')) {
			return __('Installed (active)', 'lolacore');
		}

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

	/**
	 * Whether the generated plugin folder exists under wp-content/plugins.
	 */
	public static function isInstalledOnDisk( int $post_id ): bool {
		$slug = (string) get_post_meta($post_id, PluginPostType::META_SLUG, true);
		if ($slug === '') {
			return false;
		}

		$directory = self::pluginDirectoryForSlug($slug);

		return $directory !== '' && is_dir($directory);
	}

	/**
	 * Absolute path to wp-content/plugins/{slug}/.
	 */
	public static function pluginDirectoryForSlug( string $slug ): string {
		$slug = sanitize_title($slug);
		if ($slug === '' || ! defined('WP_PLUGIN_DIR')) {
			return '';
		}

		return rtrim(WP_PLUGIN_DIR, '/\\') . DIRECTORY_SEPARATOR . $slug;
	}
}
