<?php

namespace Limb_Chatbot\Includes\Admin;

use Limb_Chatbot\Includes\Data_Objects\Setting;
use Limb_Chatbot\Includes\Services\Dataset_Service;
use Limb_Chatbot\Includes\Traits\SingletonTrait;
use WP_User;

/**
 * Class Admin
 *
 * Initializes the admin dashboard for the Limb Chatbot plugin.
 * Registers admin pages, scripts, styles, vector service hooks, and admin actions.
 *
 * @package Limb_Chatbot\Includes\Admin
 * @since 1.0.0
 */
class Admin {

	use SingletonTrait;

	/**
	 * Slug identifier for the parent admin menu.
	 *
	 * @since 1.0.0
	 * @var string
	 */
	static string $menu_slug = 'lbaic-dashboard';

	/**
	 * Settings page instance.
	 *
	 * @since 1.0.0
	 * @var Pages\Setting\Page
	 */
	protected Pages\Setting\Page $setting_page;

	/**
	 * Default chatbot page instance.
	 *
	 * @since 1.0.0
	 * @var Pages\Default_Chatbot\Page
	 */
	protected Pages\Default_Chatbot\Page $default_chatbot_page;

	/**
	 * Actions page instance.
	 *
	 * @since 1.0.0
	 * @var Pages\Actions\Page
	 */
	protected Pages\Actions\Page $actions_page;

	/**
	 * Dataset service.
	 *
	 * @since 1.0.0
	 * @var Dataset_Service
	 */
	private Dataset_Service $dataset_service;
	private Pages\Leads\Page $leads_page;
	private Pages\Notifications\Page $notifications_page;

	/**
	 * Admin constructor.
	 * Initializes all admin page classes and vector service.
	 *
	 * @since 1.0.0
	 */
    public function __construct() {
        $this->setting_page         = new Pages\Setting\Page();
        $this->default_chatbot_page = new Pages\Default_Chatbot\Page( $this->setting_page );
        $this->leads_page           = new Pages\Leads\Page( $this->setting_page );
        $this->actions_page         = new Pages\Actions\Page( $this->setting_page );
        $this->notifications_page   = new Pages\Notifications\Page( $this->setting_page );
        $this->dataset_service      = new Dataset_Service();
    }

	/**
	 * Bootstraps the admin logic.
	 * Registers menu pages, actions, hooks, and initiates AJAX endpoints.
	 *
	 * @return void
	 * @since 1.0.0
	 *
	 */
	public function boot() {
		add_action( 'admin_menu', array( $this, 'add_options_page' ) );
		add_action( 'admin_init', array( Assets::class, 'admin_init' ) );
		add_action( 'transition_post_status', array( $this->dataset_service, 'post_object_created' ), 10, 3 );
		add_action( 'post_updated', array( $this->dataset_service, 'post_object_updated' ), 10, 3 );
		add_action( 'deleted_post', array( $this->dataset_service, 'post_object_deleted' ), 10, 2 );
		add_action( 'admin_notices', array( $this, 'limb_chatbot_free_activation_notice' ) );
		Ajax::init();
		add_filter( 'set-screen-option', array( $this->setting_page, 'set_screen_options' ), 10, 3 );
		add_filter( 'get_avatar_url', array( $this, 'get_custom_avatar_url' ), 10, 3 );
        add_filter( 'plugin_action_links', array( $this, 'add_action_links' ), 10, 4 );
	}

	/**
	 * Filter to return custom avatar URL for users (Slack or Telegram).
	 *
	 * @param string $url Current avatar URL.
	 * @param mixed  $id_or_email User ID or email.
	 * @param array  $args Avatar arguments.
	 *
	 * @return string Avatar URL.
	 * @since 1.0.0
	 * @since 1.0.11 Added Telegram avatar support.
	 */
	public function get_custom_avatar_url( $url, $id_or_email, $args ) {
		$user_id = false;

		// Get user ID from various input types
		if ( is_numeric( $id_or_email ) ) {
			$user_id = (int) $id_or_email;
		} elseif ( is_object( $id_or_email ) && isset( $id_or_email->user_id ) ) {
			$user_id = (int) $id_or_email->user_id;
		} elseif ( is_string( $id_or_email ) ) {
			$user = get_user_by( 'email', $id_or_email );
			if ( $user ) {
				$user_id = $user->ID;
			}
		} elseif ($id_or_email instanceof WP_User){
			$user_id = $id_or_email->ID;
		}
		if ( ! $user_id ) {
			return $url;
		}

		// Check if user has a custom Slack avatar
		$slack_avatar_url = get_user_meta( $user_id, 'slack_avatar_url', true );
		if ( ! empty( $slack_avatar_url ) ) {
			return $slack_avatar_url;
		}

		// Check if user has a custom Telegram avatar
		$telegram_avatar_url = get_user_meta( $user_id, 'telegram_avatar_url', true );
		if ( ! empty( $telegram_avatar_url ) ) {
			return $telegram_avatar_url;
		}

		return $url;
	}

	/**
	 * Add the settings link as plugin row meta.
	 *
	 * @param  array  $links Existing links.
	 * @param  string  $plugin_file Current plugin file.
	 *
	 * @return array The array of links.
	 */
	public function add_row_meta_links( array $links, string $plugin_file ): array {
        return $links;
	}

	/**
	 * Registers the top-level "Limb" admin menu and its submenu pages.
	 *
	 * @return void
	 * @since 1.0.0
	 *
	 */
	public function add_options_page(): void {
		$lbaic_icon
			= 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTQ2IiBoZWlnaHQ9IjE1MCIgdmlld0JveD0iMCAwIDE0NiAxNTAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGQ9Ik01OC4zMDE4IDYuNTg5ODRDNjYuMzA0OSAtMS40MDMxOCA3OS4xODM2IC0xLjUyNzcyIDg3LjMzODkgNi4yMTU4Mkw4Ny43MjM2IDYuNTg5ODRMOTIuNzA1MSAxMS41NzIzTDcyLjc5NzkgMzEuNDcyN0g3Mi43ODcxTDcyLjY0MDYgMzEuNjE4Mkw0Ni42OTkyIDU3LjU1NDdDMzguMjk5IDY1Ljk0NDcgMzguMTY3OCA3OS40NzIxIDQ2LjMwNTcgODguMDIyNUw0Ni42OTkyIDg4LjQyNThMODQuMDM3MSAxMjUuNzM3Qzg5LjM4NjYgMTMxLjA4OCA4OS40NzA1IDEzOS43MTMgODQuMjg4MSAxNDUuMTY2TDg0LjAzNzEgMTQ1LjQyM0M3OC42ODc2IDE1MC43NzQgNzAuMDY1OSAxNTAuODU4IDY0LjYxNDMgMTQ1LjY3NEw2NC4zNTc0IDE0NS40MjNMNi42MDY0NSA4Ny43MDUxQy0xLjQwODQxIDc5LjY5OTYgLTEuNTMzMjYgNjYuNzkzMiA2LjIzMTQ1IDU4LjYzNDhMNi42MDY0NSA1OC4yNUw1OC4zMDE4IDYuNTg5ODRaTTEzOS4zOTQgNTguMjM3M0MxNDcuNDA5IDY2LjI0MjcgMTQ3LjUzMyA3OS4xNDkxIDEzOS43NjkgODcuMzA3NkwxMzkuMzk0IDg3LjY5MjRWODcuNjkzNEwxMjIuNzY4IDEwNC4zMTFWMTA0LjMxMkMxMTcuNDE5IDEwOS42NzQgMTA4LjgwOSAxMDkuNzQ3IDEwMy4zNDUgMTA0LjU2MkwxMDMuMDg3IDEwNC4zMTFDOTcuNzI2MiA5OC45NTk5IDk3LjY1MzYgOTAuMzM1NiAxMDIuODM3IDg0Ljg4MThMMTAzLjA4OCA4NC42MjVMMTAzLjY0IDg0LjA3MzJMMTAzLjYzOSA4NC4wNzIzQzEwOS43NzcgNzcuOTQ0NiAxMDkuNzc3IDY3Ljk5NjYgMTAzLjYzOSA2MS44NjkxSDEwMy42NEw4MC43OTEgMzkuMDM5MUwxMDAuNDc4IDE5LjM0NjdMMTM5LjM5NCA1OC4yMzczWiIgZmlsbD0iIzlFQTNBOCIgc3Ryb2tlPSJibGFjayIvPgo8L3N2Zz4K';
		add_menu_page( __( 'Limb', 'limb-chatbot' ), __( 'Limb', 'limb-chatbot' ), 'manage_options', self::$menu_slug, '', $lbaic_icon, 13 );
		$this->default_chatbot_page->add_submenu_page();
		$this->setting_page->add_submenu_page();
		$this->leads_page->add_submenu_page();
		$this->actions_page->add_submenu_page();
		$this->notifications_page->add_submenu_page();
	}

	/**
	 * Show admin notice after deactivating the free version.
	 */
	function limb_chatbot_free_activation_notice() {
		if ( Setting::exists( 'lbaic.plugin.pro_deactivated' ) ) { ?>
			<div class="notice notice-info is-dismissible"><p><?php esc_html_e( 'Limb AI Chatbot (PRO version) has been deactivated because Limb AI Chatbot is now active.', 'limb-chatbot' ); ?></p></div><?php
			Setting::delete( [ 'key' => 'lbaic.plugin.pro_deactivated' ] );
		}
	}

    /**
     * Add the settings link
     * @param array  $actions Existing action links.
     * @param string $plugin_file Current plugin file.
     * @param array  $plugin_data Plugin data.
     * @param string $context Context.
     *
     * @return array The array of action links.
     */
    function add_action_links($actions, $plugin_file, $plugin_data, $context) {

        if ( $plugin_file !== plugin_basename( LIMB_CHATBOT_FILE ) ) {
            return $actions;
        }

        $settings_link = sprintf(
                '<a href="%s">%s</a>',
                esc_url( admin_url( 'admin.php?page=lbaic-dashboard&menu=chatbot&tab=dashboard' ) ),
                __( 'Settings', 'limb-chatbot' )
        );

        array_unshift( $actions, $settings_link );

        return $actions;
    }
}
