<?php
/**
 * Admin: menu registration, asset loading, settings save handler.
 * Renders a fully custom-styled dashboard shell (not default wp-admin look).
 */

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

class CPECS_Admin {

	const AJAX_SAVE_SETTINGS = 'cpecs_save_settings';

	/** @var CPECS_DB */
	private $db;

	/** @var CPECS_Settings */
	private $settings;

	/** @var CPECS_Cleanup */
	private $cleanup;

	public function __construct( CPECS_DB $db, CPECS_Settings $settings, CPECS_Cleanup $cleanup ) {
		$this->db       = $db;
		$this->settings = $settings;
		$this->cleanup  = $cleanup;

		add_action( 'admin_menu', array( $this, 'register_menu' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue' ) );
		add_action( 'wp_ajax_' . self::AJAX_SAVE_SETTINGS, array( $this, 'ajax_save_settings' ) );
	}

	public function register_menu() {
		$cap = self::capability();

		add_menu_page(
			__( 'Easy Chat Support', 'capripio-easy-chat-support' ),
			__( 'Chat Support', 'capripio-easy-chat-support' ),
			$cap,
			'cpecs-inbox',
			array( $this, 'render_inbox' ),
			'dashicons-format-chat',
			26
		);

		add_submenu_page(
			'cpecs-inbox',
			__( 'Inbox', 'capripio-easy-chat-support' ),
			__( 'Inbox', 'capripio-easy-chat-support' ),
			$cap,
			'cpecs-inbox',
			array( $this, 'render_inbox' )
		);

		add_submenu_page(
			'cpecs-inbox',
			__( 'Settings', 'capripio-easy-chat-support' ),
			__( 'Settings', 'capripio-easy-chat-support' ),
			$cap,
			'cpecs-settings',
			array( $this, 'render_settings' )
		);
	}

	/**
	 * Capability required to access the inbox/settings pages and admin
	 * REST/AJAX actions. Free hardcodes this to 'manage_options'. Pro's
	 * agents feature hooks 'cpecs_admin_capability' to swap in a
	 * dedicated 'cpecs_agent' capability so support staff who aren't
	 * full WP admins can be given access.
	 */
	public static function capability() {
		return apply_filters( 'cpecs_admin_capability', 'manage_options' );
	}

	public function enqueue( $hook ) {
		if ( 'toplevel_page_cpecs-inbox' !== $hook && 'chat-support_page_cpecs-settings' !== $hook ) {
			return;
		}

		wp_enqueue_style(
			'cpecs-admin',
			CPECS_PLUGIN_URL . 'assets/css/admin.css',
			array(),
			CPECS_VERSION
		);

		wp_enqueue_script(
			'cpecs-admin',
			CPECS_PLUGIN_URL . 'assets/js/admin-inbox.js',
			array(),
			CPECS_VERSION,
			true
		);

		wp_localize_script(
			'cpecs-admin',
			'CPECS_ADMIN',
			array(
				'restUrl'     => esc_url_raw( rest_url( 'cpecs/v1' ) ),
				'restNonce'   => wp_create_nonce( 'wp_rest' ),
				'ajaxUrl'     => admin_url( 'admin-ajax.php' ),
				'ajaxNonce'   => wp_create_nonce( 'cpecs_admin' ),
				'settings'    => $this->settings->get_all(),
				'lastCleanup' => array(
					'ran_at' => get_option( 'cpecs_last_cleanup_run', '' ),
					'count'  => get_option( 'cpecs_last_cleanup_count', 0 ),
				),
				// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only, used only to tell the JS which page it's on; no state changes here.
				'page'        => isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '',
				'navItems'    => apply_filters( 'cpecs_admin_nav_items', array(
					array( 'key' => 'inbox', 'label' => __( 'Inbox', 'capripio-easy-chat-support' ), 'url' => admin_url( 'admin.php?page=cpecs-inbox' ) ),
					array( 'key' => 'settings', 'label' => __( 'Settings', 'capripio-easy-chat-support' ), 'url' => admin_url( 'admin.php?page=cpecs-settings' ) ),
				) ),
				'proPromo'    => $this->pro_promo_data(),
			)
		);
	}

	/**
	 * Data for the persistent Pro promo card, shown in the sidebar of
	 * the plugin's own Inbox/Settings pages. Returns null once Pro is
	 * active, in which case the JS renders nothing.
	 */
	private function pro_promo_data() {
		if ( function_exists( 'cecs_fs' ) && cecs_fs()->can_use_premium_code() ) {
			return null;
		}

		return array(
			'url'      => CPECS_BRAND_URL,
			'title'    => __( 'Your inbox, built for a team', 'capripio-easy-chat-support' ),
			'tagline'  => __( "Bring teammates in, save time with canned replies, and see exactly who you're talking to.", 'capripio-easy-chat-support' ),
			'features' => array(
				__( 'Add agents & assign conversations', 'capripio-easy-chat-support' ),
				__( 'Canned replies for common questions', 'capripio-easy-chat-support' ),
				__( "Know when a reply's been seen", 'capripio-easy-chat-support' ),
				__( 'Full visitor context: browser, device, country', 'capripio-easy-chat-support' ),
			),
			'pricing'  => __( '$2.99/site/mo, or $19.99/mo for unlimited sites', 'capripio-easy-chat-support' ),
			'cta'      => __( 'Upgrade to Pro', 'capripio-easy-chat-support' ),
		);
	}

	public function render_inbox() {
		echo '<div id="cpecs-app" class="cpecs-app' . esc_attr( $this->extra_app_class() ) . '" data-view="inbox"></div>';
	}

	public function render_settings() {
		echo '<div id="cpecs-app" class="cpecs-app' . esc_attr( $this->extra_app_class() ) . '" data-view="settings"></div>';
	}

	private function extra_app_class() {
		$class = apply_filters( 'cpecs_admin_app_class', '' );
		return $class ? ' ' . $class : '';
	}

	public function ajax_save_settings() {
		check_ajax_referer( 'cpecs_admin', 'nonce' );

		if ( ! current_user_can( self::capability() ) ) {
			wp_send_json_error( array( 'message' => __( 'Not allowed.', 'capripio-easy-chat-support' ) ), 403 );
		}

		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- raw value is only ever passed to CPECS_Settings::update(), which sanitizes every recognized field individually before saving; nonce already verified above.
		$raw = isset( $_POST['settings'] ) ? wp_unslash( $_POST['settings'] ) : array();
		if ( is_string( $raw ) ) {
			$raw = json_decode( $raw, true );
		}
		if ( ! is_array( $raw ) ) {
			$raw = array();
		}

		$updated = $this->settings->update( $raw );

		wp_send_json_success( array( 'settings' => $updated ) );
	}
}
