<?php
/**
 * Admin Hooks Class.
 *
 * This file contains the Admin_Hooks class which manages admin-specific hooks
 * for the Postomatic plugin.
 *
 * @package Postomatic
 * @since      1.0.0
 * @subpackage Postomatic\Admin
 */

namespace Postomatic\Admin;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class for managing public-specific hooks.
 */
class Admin_Hooks {

	/**
	 * Initialize the public hooks.
	 */
	public function init() {
		// Public-facing actions.
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_styles' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		add_action( 'init', array( $this, 'register_shortcodes' ) );

		// Public-facing filters.
		add_filter( 'the_content', array( $this, 'maybe_modify_content' ) );

		// Add Postomatic icon to the admin bar when user is logged in.
		add_action( 'admin_bar_menu', array( $this, 'add_postomatic_icon_to_admin_bar' ), 999 );

		// Enqueue styles for the admin bar icon.
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_admin_bar_styles' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_bar_styles' ) );

		// Filter admin notices to only show plugin's own notices on plugin pages.
		add_action( 'admin_notices', array( $this, 'filter_admin_notices' ), -999 );

		// Add action links (Add Post, AutoPilot, Buy Credits) and row meta
		// (Support, Documentation) on the Plugins list screen.
		add_filter( 'plugin_action_links_' . POSTOMATIC_PLUGIN_BASENAME, array( $this, 'add_plugin_action_links' ) );
		add_filter( 'plugin_row_meta', array( $this, 'add_plugin_row_meta' ), 10, 2 );
	}

	/**
	 * Add quick-access action links for Postomatic on the Plugins list screen.
	 *
	 * These appear alongside the default "Deactivate" link under the plugin's
	 * name, giving users a fast path into the most common screens without
	 * hunting through the admin sidebar first.
	 *
	 * @param  array $links Existing plugin action links.
	 * @return array Modified plugin action links.
	 */
	public function add_plugin_action_links( $links ) {
		$custom_links = array(
			'add-post'   => sprintf(
				'<a href="%s">%s</a>',
				esc_url( admin_url( 'admin.php?page=' . \Postomatic\Constants::PAGE_MAIN ) ),
				esc_html__( 'Add Post', 'postomatic' )
			),
			'autopilot'  => sprintf(
				'<a href="%s">%s</a>',
				esc_url( admin_url( 'admin.php?page=' . \Postomatic\Constants::PAGE_AUTOPILOT ) ),
				esc_html__( 'AutoPilot', 'postomatic' )
			),
			'buy-credit' => sprintf(
				'<a href="%s" style="font-weight:600;">%s</a>',
				esc_url( admin_url( 'admin.php?page=' . \Postomatic\Constants::PAGE_ADD_CREDIT ) ),
				esc_html__( 'Buy Credits', 'postomatic' )
			),
		);

		return array_merge( $custom_links, $links );
	}

	/**
	 * Add extra reference links (Documentation, Support) under the plugin
	 * description on the Plugins list screen.
	 *
	 * @param  array  $plugin_meta Existing row meta links for this plugin row.
	 * @param  string $plugin_file Path to the plugin file relative to the plugins directory.
	 * @return array Modified row meta links.
	 */
	public function add_plugin_row_meta( $plugin_meta, $plugin_file ) {
		if ( POSTOMATIC_PLUGIN_BASENAME !== $plugin_file ) {
			return $plugin_meta;
		}

		$plugin_meta[] = sprintf(
			'<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
			esc_url( 'https://buildomatics.com/pages/postomatic/documentation' ),
			esc_html__( 'Documentation', 'postomatic' )
		);

		$plugin_meta[] = sprintf(
			'<a href="%s">%s</a>',
			esc_url( admin_url( 'admin.php?page=' . \Postomatic\Constants::PAGE_SUPPORT ) ),
			esc_html__( 'Support', 'postomatic' )
		);

		return $plugin_meta;
	}

	/**
	 * Register and enqueue public-facing styles.
	 */
	public function enqueue_styles() {
		wp_enqueue_style(
			'postomatic-public',
			POSTOMATIC_PLUGIN_URL . 'includes/public/css/wp-postomatic-public.css',
			array(),
			POSTOMATIC_VERSION,
			'all'
		);
	}

	/**
	 * Register and enqueue public-facing scripts.
	 */
	public function enqueue_scripts() {
		// Enqueue scripts code.
	}

	/**
	 * Register shortcodes.
	 */
	public function register_shortcodes() {
		// Register shortcodes.
	}

	/**
	 * Modify content if needed.
	 *
	 * @param  string $content The post content.
	 * @return string The filtered content.
	 */
	public function maybe_modify_content( $content ) {
		// Content filter logic.
		return $content;
	}

	/**
	 * Add Postomatic icon to the WordPress admin bar.
	 *
	 * @param  \WP_Admin_Bar $wp_admin_bar WordPress admin bar object.
	 * @return void
	 */
	public function add_postomatic_icon_to_admin_bar( $wp_admin_bar ) {
		// Only add the icon if user is logged in.
		if ( ! is_user_logged_in() ) {
			return;
		}

		// Add the main Postomatic icon/link.
		$wp_admin_bar->add_node(
			array(
				'id'    => 'postomatic',
				'title' => '<span class="ab-icon dashicons dashicons-text"></span><span class="ab-label">Postomatic</span>',
				'href'  => admin_url( 'admin.php?page=postomatic' ),
				'meta'  => array(
					'title' => __( 'Postomatic', 'postomatic' ),
				),
			)
		);

		// Add submenu items.
		// Main page (Dashboard).
		$wp_admin_bar->add_node(
			array(
				'id'     => 'postomatic-main',
				'parent' => 'postomatic',
				'title'  => __( 'Add Post', 'postomatic' ),
				'href'   => admin_url( 'admin.php?page=postomatic' ),
			)
		);

		// Membership page.
		$wp_admin_bar->add_node(
			array(
				'id'     => 'postomatic-membership',
				'parent' => 'postomatic',
				'title'  => __( 'Subscription', 'postomatic' ),
				'href'   => admin_url( 'admin.php?page=postomatic-membership' ),
			)
		);

		// Add Credit page.
		$wp_admin_bar->add_node(
			array(
				'id'     => 'postomatic-add-credit',
				'parent' => 'postomatic',
				'title'  => __( 'Buy Credit', 'postomatic' ),
				'href'   => admin_url( 'admin.php?page=postomatic-add-credit' ),
			)
		);

		// Support page.
		$wp_admin_bar->add_node(
			array(
				'id'     => 'postomatic-support',
				'parent' => 'postomatic',
				'title'  => __( 'Support', 'postomatic' ),
				'href'   => admin_url( 'admin.php?page=postomatic-support' ),
			)
		);

		// Autopilot page.
		$wp_admin_bar->add_node(
			array(
				'id'     => 'postomatic-autopilot',
				'parent' => 'postomatic',
				'title'  => __( 'AutoPilot', 'postomatic' ),
				'href'   => admin_url( 'admin.php?page=postomatic-autopilot' ),
			)
		);
	}

	/**
	 * Enqueue styles for the admin bar icon.
	 *
	 * @return void
	 */
	public function enqueue_admin_bar_styles() {
		// We're using dashicons-text now, so no custom CSS is needed.
		// Ensure dashicons are loaded.
		wp_enqueue_style( 'dashicons' );
	}

	/**
	 * Filter admin notices to only show plugin's own notices on plugin pages.
	 *
	 * This prevents notices from other plugins from appearing on Postomatic pages.
	 *
	 * @return void
	 */
	public function filter_admin_notices() {
		global $hook_suffix;

		// Check if we're on a Postomatic admin page.
		if ( strpos( $hook_suffix, 'postomatic' ) !== false ) {
			// Remove all admin notices.
			remove_all_actions( 'admin_notices' );
			remove_all_actions( 'all_admin_notices' );

			// Add back only our notices.
			add_action( 'admin_notices', array( $this, 'display_postomatic_notices' ) );
		}
	}

	/**
	 * Display only Postomatic-specific notices.
	 *
	 * @return void
	 */
	public function display_postomatic_notices() {
		// Display activation notice if it exists.
		if ( class_exists( '\Postomatic\Core\Activator' ) ) {
			\Postomatic\Core\Activator::activation_admin_notice();
		}

		// Display PHP version notice if needed.
		$this->maybe_display_php_version_notice();

		// Display low-credit warning if needed.
		$this->maybe_display_low_credit_notice();
	}

	/**
	 * Display a low-credit admin notice on Postomatic pages.
	 *
	 * Fetches the current credit balance (cached for 5 minutes) and shows a
	 * dismissible warning banner when the balance drops below 10 credits, which
	 * is enough to signal that active autopilots may be paused on their next run.
	 *
	 * @return void
	 */
	private function maybe_display_low_credit_notice() {
		// Only show on Postomatic admin pages.
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( ! $screen || strpos( $screen->id, 'postomatic' ) === false ) {
			return;
		}

		// Skip on the "Buy Credit" page itself — the user is already taking action.
		if ( isset( $_GET['page'] ) && \Postomatic\Constants::PAGE_ADD_CREDIT === sanitize_text_field( wp_unslash( $_GET['page'] ) ) ) {
			return;
		}

		// Use a short-lived transient to avoid hammering the API on every page load.
		$credit_data = get_transient( 'postomatic_credit_notice_data' );
		if ( false === $credit_data ) {
			$handler     = new \Postomatic\Api\Credit_Handler();
			$credit_data = $handler->postomatic_get_credits();
			set_transient( 'postomatic_credit_notice_data', $credit_data, 5 * MINUTE_IN_SECONDS );
		}

		if ( empty( $credit_data ) || ! isset( $credit_data['credit'] ) ) {
			return;
		}

		$credits   = (int) $credit_data['credit'];
		$threshold = 10; // Show notice when balance falls below this value.

		if ( $credits >= $threshold ) {
			return;
		}

		$add_credit_url = admin_url( 'admin.php?page=' . \Postomatic\Constants::PAGE_ADD_CREDIT );

		if ( $credits === 0 ) {
			$credit_msg = esc_html__( 'You have no credits left.', 'postomatic' );
		} else {
			$credit_msg = sprintf(
				/* translators: %d: current credit balance */
				esc_html__( 'Your balance is %d credit(s).', 'postomatic' ),
				$credits
			);
		}

		printf(
			'<div class="notice notice-warning is-dismissible" style="border-left-color:#dba617;"><p>'
			. '<strong>%1$s</strong> %2$s %3$s <a href="%4$s" style="font-weight:600;">%5$s</a></p></div>',
			esc_html__( 'Postomatic — Low Credits:', 'postomatic' ),
			wp_kses_post( $credit_msg ),
			esc_html__( 'Active autopilots may be paused on their next run.', 'postomatic' ),
			esc_url( $add_credit_url ),
			esc_html__( 'Buy more credits →', 'postomatic' )
		);
	}

	/**
	 * Display PHP version notice if PHP version is too low.
	 *
	 * @return void
	 */
	private function maybe_display_php_version_notice() {
		if ( version_compare( PHP_VERSION, '7.4', '<' ) ) {
			$message = sprintf(
				// translators: %1$s: Required PHP version, %2$s: Current PHP version.
				esc_html__(
					'Postomatic requires PHP %1$s+. You have %2$s. Please upgrade PHP.',
					'postomatic'
				),
				'7.4',
				esc_html( PHP_VERSION )
			);
			printf( '<div class="notice notice-error"><p>%s</p></div>', wp_kses_post( $message ) );
		}
	}
}
