<?php
namespace PEVFSLite;

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

if ( ! trait_exists( __NAMESPACE__ . '\\OptIn' ) ) {
	trait OptIn {
		public function init_optin() {
			\add_action( 'admin_notices', array( $this, 'maybe_display_optin_notice' ) );
			\add_action( 'wp_ajax_fs_connect_' . $this->id, array( $this, 'ajax_connect' ) );
			\add_action( 'wp_ajax_fs_dismiss_' . $this->id, array( $this, 'ajax_dismiss' ) );
			\add_action( 'wp_ajax_fs_toggle_tracking_' . $this->id, array( $this, 'ajax_toggle_tracking' ) );
			\add_action( 'admin_footer', array( $this, 'render_optin_popup' ) );
			\add_action( 'admin_init', array( $this, 'add_tracking_links' ) );
			\add_action( 'admin_init', array( $this, 'maybe_redirect_after_activation' ) );
		}

		public function ajax_connect() {
			\check_ajax_referer( 'fs_connect_' . $this->id, 'security' );

			if ( ! \current_user_can( 'manage_options' ) ) {
				\wp_send_json_error( 'Permission denied.' );
			}

			$current_user = \wp_get_current_user();
			
			$params = array(
				'user_email'                     => isset( $_POST['user_email'] ) ? \sanitize_email( $_POST['user_email'] ) : $current_user->user_email,
				'user_firstname'                 => isset( $_POST['user_firstname'] ) ? \sanitize_text_field( $_POST['user_firstname'] ) : $current_user->first_name,
				'user_lastname'                  => isset( $_POST['user_lastname'] ) ? \sanitize_text_field( $_POST['user_lastname'] ) : $current_user->last_name,
				'is_marketing_allowed'           => isset( $_POST['is_marketing_allowed'] ) ? \sanitize_text_field( $_POST['is_marketing_allowed'] ) : '1',
				'is_diagnostic_tracking_allowed' => isset( $_POST['is_diagnostic_tracking_allowed'] ) ? \sanitize_text_field( $_POST['is_diagnostic_tracking_allowed'] ) : '1',
			);

			$response_data = $this->call_service_api( $params );

			if ( ! empty( $response_data['id'] ) ) {
				$install_id = $response_data['id'];
				$user_id    = $response_data['user_id'];
			} else {
				$install_id = 'pending_' . \time();
				$user_id    = 'pending';
			}

			$accounts = $this->get_accounts();
			$install_key = ( 'plugin' === $this->type ) ? 'plugins' : 'themes';
			if ( ! isset( $accounts[ $install_key ] ) ) {
				$accounts[ $install_key ] = array();
			}

			$accounts[ $install_key ][ $this->slug ] = array(
				'id'            => $install_id,
				'user_id'       => $user_id,
				'public_key'    => $this->public_key,
				'slug'          => $this->slug,
				'version'       => $this->get_plugin_data( 'plugin_version', $this->version ),
				'is_connected'  => true,
				'connected_at'  => \time(),
			);

			// Standardize boolean checks from React (sends 'true'/'false' as strings)
			$is_tracking_allowed  = ( '1' === $params['is_diagnostic_tracking_allowed'] || 'true' === $params['is_diagnostic_tracking_allowed'] || true === $params['is_diagnostic_tracking_allowed'] );
			$is_marketing_allowed = ( '1' === $params['is_marketing_allowed'] || 'true' === $params['is_marketing_allowed'] || true === $params['is_marketing_allowed'] );

			// Update global ID -> Slug map for cross-SDK compatibility
			if ( ! isset( $accounts['id_slug_type_path_map'] ) ) {
				$accounts['id_slug_type_path_map'] = array();
			}
			$accounts['id_slug_type_path_map'][ $this->id ] = array(
				'slug' => $this->slug,
				'type' => $this->type,
				'path' => $this->plugin_basename,
			);

			// Ensure unique_id is at root if not already set
			if ( empty( $accounts['unique_id'] ) ) {
				$accounts['unique_id'] = $this->get_anonymous_id();
			}

			// Batch update plugin_data to avoid racing conditions
			if ( ! isset( $accounts['plugin_data'] ) ) {
				$accounts['plugin_data'] = array();
			}
			if ( ! isset( $accounts['plugin_data'][ $this->slug ] ) ) {
				$accounts['plugin_data'][ $this->slug ] = array();
			}
			
			$accounts['plugin_data'][ $this->slug ]['is_tracking_allowed']  = $is_tracking_allowed;
			$accounts['plugin_data'][ $this->slug ]['is_marketing_allowed'] = $is_marketing_allowed;
			$accounts['plugin_data'][ $this->slug ]['id']                   = $install_id;
			$accounts['plugin_data'][ $this->slug ]['user_id']              = $user_id;
			$accounts['plugin_data'][ $this->slug ]['is_anonymous']         = false;

			$this->save_accounts( $accounts );

			\wp_send_json_success();
		}

		public function ajax_dismiss() {
			\check_ajax_referer( 'fs_dismiss_' . $this->id, 'security' );
			if ( ! \current_user_can( 'manage_options' ) ) {
				\wp_send_json_error( 'Permission denied.' );
			}
			$this->set_plugin_data( 'is_anonymous', array( 'is' => true ) );
			\wp_send_json_success();
		}

		public function maybe_display_optin_notice() {
			if ( ! \current_user_can( 'manage_options' ) || $this->is_connected() || $this->is_anonymous() ) {
				return;
			}
			
			$is_plugin_page = false;
			$screen			= \get_current_screen();
			$is_standalone	= isset( $_GET['fs_connect'] );
			
			if ( $is_standalone ) {
				$is_plugin_page = true;
				\add_filter( 'admin_body_class', array( $this, 'add_standalone_body_class' ) );
			} elseif ( $screen ) {
				$page = $_GET['page'] ?? '';
				if ( $page === $this->slug || ( isset($this->params['menu']['slug']) && $page === $this->params['menu']['slug'] ) ) {
					$is_plugin_page = true;
				}
			}
			
			if ( ! $is_plugin_page ) {
				return;
			}
			
			$react_data = $this->get_common_ui_data( $is_standalone );
			
			echo '<div id="pev-fs-lite-root-' . \esc_attr( $this->id ) . '" class="pev-fs-lite-root pevFSLite" data-info="' . \esc_attr( \wp_json_encode( $react_data ) ) . '"></div>';
			
			if ( $is_standalone ) {
				\wp_deregister_script( 'wp-auth-check' );
				include( ABSPATH . 'wp-admin/admin-footer.php' );
				die();
			}
		}

		public function render_optin_popup() {
			$screen = \get_current_screen();
			
			if ( ! $screen || 'plugins' !== $screen->base || ( $this->is_connected() && $this->is_tracking_allowed() ) || ! \current_user_can( 'manage_options' ) ) {
				return;
			}
			
			$popup_data = $this->get_common_ui_data();
			
			echo '<div id="pev-fs-lite-popup-root-' . \esc_attr( $this->id ) . '" class="pev-fs-lite-popup-root" data-info="' . \esc_attr( \wp_json_encode( $popup_data ) ) . '"></div>';
		}

		private function get_common_ui_data( $is_standalone = false ) {
			$accounts = $this->get_accounts();
			$current_user = \wp_get_current_user();
			global $wp_version;
			$site_url = \home_url();

			return array(
				'id'            => $this->id,
				'slug'          => $this->slug,
				'name'          => $this->name,
				'version'       => $this->version,
				'sdk_version'   => $this->sdk_version,
				'is_connected'  => $this->is_connected(),
				'public_key'    => $this->public_key,
				'is_premium'    => $this->is_premium(),
				'user'          => array(
					'email'      => $current_user->user_email,
					'first_name' => $current_user->first_name,
					'last_name'  => $current_user->last_name,
				),
				'site'          => array(
					'name' => \get_bloginfo( 'name' ),
					'url'  => $site_url,
					'uid'  => $accounts['unique_id'] ?? $this->get_anonymous_id(),
					'icon' => ( \function_exists( 'get_site_icon_url' ) && \get_site_icon_url() ) ? \get_site_icon_url() : '',
				),
				'technical'     => array(
					'wp_version'   => $wp_version,
					'php_version'  => \phpversion(),
					'language'     => \get_bloginfo( 'language' ),
					'is_localhost' => ( \strpos( $site_url, 'localhost' ) !== false || \strpos( $site_url, '127.0.0.1' ) !== false ),
				),
				'urls'          => array(
					'return'  => $is_standalone ? $this->get_opt_in_url() : \admin_url( 'plugins.php' ),
					'account' => \admin_url( 'admin.php?page=' . $this->slug . '-account' ),
				),
				'standalone'    => $is_standalone,
				'ajax_url'      => \admin_url( 'admin-ajax.php' ),
				'nonces'        => array(
					'connect' => \wp_create_nonce( 'fs_connect_' . $this->id ),
					'dismiss' => \wp_create_nonce( 'fs_dismiss_' . $this->id ),
				),
			);
		}

		public function maybe_redirect_after_activation() {
			if ( \get_transient( 'fs_was_activated_' . $this->slug ) ) {
				\delete_transient( 'fs_was_activated_' . $this->slug );
				if ( \is_admin() && ! isset( $_GET['activate-multi'] ) ) {
					if ( $this->is_connected() ) {
						$install_id = $this->get_install_id();
						if ( $install_id ) {
							$this->call_api( "/plugins/{$this->id}/installs/{$install_id}.json", 'PUT', array( 'is_active' => true, 'is_uninstalled' => false ) );
						}
						return;
					}
					if ( $this->is_anonymous() ) {
						return;
					}
					$redirect_url = isset( $this->params['menu']['slug'] ) ? \admin_url( 'admin.php?page=' . $this->params['menu']['slug'] ) : ( $this->is_plugin() ? \admin_url( 'plugins.php' ) : '' );
					if ( $redirect_url ) {
						\wp_safe_redirect( \add_query_arg( 'fs_connect', '1', $redirect_url ) );
						exit;
					}
				}
			}
		}

		public function add_tracking_links() {
			if ( ! \current_user_can( 'manage_options' ) || ! $this->is_plugin() ) {
				return;
			}
			
			$link_text	= '';
			$url		= '#';
			$is_popup	= false;
			
			if ( $this->is_connected() ) {
				if ( $this->is_tracking_allowed() ) {
					$link_text		= \__( 'Opt Out', 'pev-fs-lite' );
					$url			= \wp_nonce_url( \add_query_arg( array( 'action' => 'fs_toggle_tracking_' . $this->id, 'tracking' => '0' ), \admin_url( 'admin-ajax.php' ) ), 'fs_toggle_tracking_' . $this->id );
				} else {
					$link_text	= \__( 'Opt In', 'pev-fs-lite' );
					$is_popup	= true;
				}
			} else {
				$link_text	= \__( 'Opt In', 'pev-fs-lite' );
				$is_popup	= true;
			}

			if ( $link_text ) {
				$this_id		= $this->id;
				$this_basename	= $this->plugin_basename;
				\add_filter( 'plugin_action_links_' . $this_basename, function( $links ) use ( $link_text, $url, $is_popup, $this_id ) {
					if ( $is_popup ) {
						$onclick	= 'event.preventDefault(); document.dispatchEvent(new CustomEvent("fsLiteOpenOptIn_' . \esc_js( $this_id ) . '"));';
						$link		= \sprintf( '<a href="#" onclick="%s" class="fs-opt-in-popup-trigger" data-module-id="%s">%s</a>', \esc_attr( $onclick ), \esc_attr( $this_id ), \esc_html( $link_text ) );
					} else {
						$link		= \sprintf( '<a href="%s">%s</a>', \esc_url( $url ), \esc_html( $link_text ) );
					}
					\array_unshift( $links, $link );
					return $links;
				}, 10 );
			}
		}

		public function ajax_toggle_tracking() {
			\check_admin_referer( 'fs_toggle_tracking_' . $this->id );
			if ( ! \current_user_can( 'manage_options' ) ) {
				\wp_die( 'Permission denied.' );
			}
			
			$enable = isset( $_GET['tracking'] ) && '1' === $_GET['tracking'];
			
			$this->set_plugin_data( 'is_tracking_allowed', $enable );
			
			if ( $this->is_connected() ) {
				$install_id = $this->get_install_id();
				if ( $install_id ) {
					$this->call_service_api( array( 
						'is_diagnostic_tracking_allowed' => $enable ? '1' : '0', 
						'is_marketing_allowed'          => $enable ? '1' : '0' 
					) );
				}
			}
			
			\wp_safe_redirect( \admin_url( 'plugins.php' ) );
			exit;
		}
	}
}
