<?php
/**
 * Hooks Class
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/includes/common/hooks
 * @author     miniOrange
 */

declare(strict_types=1);

namespace MOMCS_Sync\Includes\Common\Hooks;

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

use MOMCS_Sync\Includes\Common\Controllers\Dashboard_Controller;

/**
 * Handles plugin hooks.
 */
class Hooks {
	/**
	 * Plugin file path.
	 *
	 * @var string
	 */
	private string $plugin_file;

	/**
	 * Constructor.
	 *
	 * @param string $plugin_file Plugin file path.
	 */
	public function __construct( string $plugin_file ) {
		$this->plugin_file = $plugin_file;
		$this->register_hooks();

		// Core defaults for free plan: single template only, limit=1.
		add_filter( 'momcs_allow_multiple_templates', '__return_false', 1, 0 );
		add_filter(
			'momcs_templates_limits',
			function ( $limits ) {
				if ( ! is_array( $limits ) ) {
					$limits = array();
				}
				if ( ! isset( $limits['max_templates'] ) ) {
					$limits['max_templates'] = 1;
				}
				return $limits;
			},
			1,
			1
		);

		// Core defaults for free plan: single Amazon connection only.
		add_filter( 'momcs_allow_multiple_amazon_connections', '__return_false', 1, 0 );
		add_filter(
			'momcs_channel_limits',
			function ( $limits ) {
				if ( ! is_array( $limits ) ) {
					$limits = array();
				}
				if ( ! isset( $limits['max_amazon_connections'] ) ) {
					$limits['max_amazon_connections'] = 1;
				}
				return $limits;
			},
			1,
			1
		);
	}

	/**
	 * Register hooks.
	 *
	 * @return void
	 */
	public function register_hooks() {
		// Register admin hooks.
		$this->register_asset_hooks();
		$this->register_ajax_hooks();
		$this->register_nonces();
		add_filter( 'admin_body_class', array( $this, 'admin_body_class_dark_mode' ) );
	}

	/**
	 * Register asset hooks.
	 *
	 * @return void
	 */
	private function register_asset_hooks(): void {
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_styles' ) );
	}

	/**
	 * Register AJAX hooks.
	 *
	 * @return void
	 */
	private function register_ajax_hooks(): void {
		// Register product search AJAX handler.
		add_action( 'wp_ajax_momcs_search_products', array( $this, 'ajax_search_products' ) );

		// Register per-page preference AJAX handler.
		add_action( 'wp_ajax_momcs_save_products_per_page', array( $this, 'ajax_save_products_per_page' ) );

		// Register order search AJAX handler.
		add_action( 'wp_ajax_momcs_search_orders', array( $this, 'ajax_search_orders' ) );

		// Register dark mode preference AJAX handler.
		add_action( 'wp_ajax_momcs_save_dark_mode', array( $this, 'ajax_save_dark_mode' ) );
	}

	/**
	 * AJAX handler for product search.
	 *
	 * Returns matching products with thumbnail, name, price for search dropdown.
	 *
	 * @return void
	 */
	public function ajax_search_products(): void {
		// Verify nonce - use the same nonce key as defined in Plugin_Constants::NONCE_MAIN.
		if ( ! check_ajax_referer( 'momcs_sync_nonce', 'nonce', false ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'multi-channel-for-woocommerce' ) ) );
		}

		// Verify user capability.
		if ( ! current_user_can( 'edit_products' ) ) {
			wp_send_json_error( array( 'message' => __( 'Unauthorized access.', 'multi-channel-for-woocommerce' ) ) );
		}

		// Get and sanitize search query.
		$query = isset( $_POST['query'] ) ? sanitize_text_field( wp_unslash( $_POST['query'] ) ) : '';

		if ( strlen( $query ) < 2 ) {
			wp_send_json_error( array( 'message' => __( 'Query too short.', 'multi-channel-for-woocommerce' ) ) );
		}

		// Search for products.
		$args = array(
			'post_type'      => 'product',
			'posts_per_page' => 10,
			's'              => $query,
			'tax_query'      => array(
				array(
					'taxonomy' => 'product_type',
					'field'    => 'slug',
					'terms'    => array( 'simple', 'variable' ),
					'operator' => 'IN',
				),
			),
		);

		$products_query = new \WP_Query( $args );
		$products       = array();

		if ( $products_query->have_posts() ) {
			while ( $products_query->have_posts() ) {
				$products_query->the_post();
				$product = wc_get_product( get_the_ID() );

				if ( ! $product instanceof \WC_Product ) {
					continue;
				}

				$products[] = array(
					'id'              => $product->get_id(),
					'name'            => $product->get_name(),
					'sku'             => $product->get_sku(),
					'price'           => $product->get_price(),
					'formatted_price' => wp_strip_all_tags( wc_price( $product->get_price() ) ),
					'image'           => get_the_post_thumbnail_url( $product->get_id(), 'thumbnail' ) ? get_the_post_thumbnail_url( $product->get_id(), 'thumbnail' ) : wc_placeholder_img_src(),
					'edit_link'       => get_edit_post_link( $product->get_id(), 'raw' ),
				);
			}
			wp_reset_postdata();
		}

		wp_send_json_success( array( 'products' => $products ) );
	}

	/**
	 * AJAX handler for saving products per page preference.
	 *
	 * @return void
	 */
	public function ajax_save_products_per_page(): void {
		// Verify nonce - use the same nonce key as defined in Plugin_Constants::NONCE_MAIN.
		if ( ! check_ajax_referer( 'momcs_sync_nonce', 'nonce', false ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'multi-channel-for-woocommerce' ) ) );
		}

		// Verify user capability.
		if ( ! current_user_can( 'edit_products' ) ) {
			wp_send_json_error( array( 'message' => __( 'Unauthorized access.', 'multi-channel-for-woocommerce' ) ) );
		}

		// Get and validate per page value.
		$per_page = isset( $_POST['per_page'] ) ? absint( $_POST['per_page'] ) : 10;
		$allowed  = array( 10, 25, 50, 100 );

		if ( ! in_array( $per_page, $allowed, true ) ) {
			$per_page = 10;
		}

		// Save user preference.
		$user_id = get_current_user_id();
		update_user_meta( $user_id, 'momcs_products_per_page', $per_page );

		wp_send_json_success( array( 'per_page' => $per_page ) );
	}

	/**
	 * AJAX handler for order search.
	 *
	 * Returns matching orders with Order ID, Customer Name, Total for search dropdown.
	 *
	 * @return void
	 */
	public function ajax_search_orders(): void {
		// Verify nonce - use the same nonce key as defined in Plugin_Constants::NONCE_MAIN.
		if ( ! check_ajax_referer( 'momcs_sync_nonce', 'nonce', false ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'multi-channel-for-woocommerce' ) ) );
		}

		// Verify user capability.
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( array( 'message' => __( 'Unauthorized access.', 'multi-channel-for-woocommerce' ) ) );
		}

		// Get and sanitize search query.
		$query = isset( $_POST['query'] ) ? sanitize_text_field( wp_unslash( $_POST['query'] ) ) : '';

		if ( strlen( $query ) < 2 ) {
			wp_send_json_error( array( 'message' => __( 'Query too short.', 'multi-channel-for-woocommerce' ) ) );
		}

		// Search for orders.
		$handler = new \MOMCS_Sync\Includes\Common\Handlers\Dashboard_Handler();
		$result  = $handler->fetch_orders( 1, 10, '', '', $query, false, '', '' );

		$orders = array();

		if ( isset( $result['orders'] ) && is_array( $result['orders'] ) ) {
			foreach ( $result['orders'] as $order_data ) {
				// Get WooCommerce order ID.
				$wc_order_id = isset( $order_data['WooCommerceOrderId'] ) ? $order_data['WooCommerceOrderId'] : 0;

				// Get customer name.
				$customer_name = '';
				if ( $wc_order_id ) {
					$wc_order = wc_get_order( $wc_order_id );
					if ( $wc_order instanceof \WC_Order ) {
						$customer_name = $wc_order->get_billing_first_name() . ' ' . $wc_order->get_billing_last_name();
						if ( trim( $customer_name ) === '' ) {
							$customer_name = $wc_order->get_formatted_billing_full_name();
						}
						if ( trim( $customer_name ) === '' ) {
							$customer_name = $wc_order->get_billing_company();
						}
					}
				}

				// Get order total.
				$formatted_total = '-';
				if ( isset( $order_data['OrderTotal'] ) && is_array( $order_data['OrderTotal'] ) ) {
					$currency = isset( $order_data['OrderTotal']['CurrencyCode'] ) ? $order_data['OrderTotal']['CurrencyCode'] : '';
					$amount   = isset( $order_data['OrderTotal']['Amount'] ) ? $order_data['OrderTotal']['Amount'] : '';
					if ( $currency && $amount ) {
						$formatted_total = $currency . ' ' . $amount;
					}
				}

				$orders[] = array(
					'order_id'        => $wc_order_id,
					'amazon_order_id' => isset( $order_data['AmazonOrderId'] ) ? $order_data['AmazonOrderId'] : '',
					'customer'        => trim( $customer_name ) !== '' ? $customer_name : __( 'Customer', 'multi-channel-for-woocommerce' ),
					'customer_name'  => trim( $customer_name ) !== '' ? $customer_name : __( 'Customer', 'multi-channel-for-woocommerce' ),
					'total'           => $formatted_total,
					'formatted_total' => $formatted_total,
				);
			}
		}

		wp_send_json_success( array( 'orders' => $orders ) );
	}

	/**
	 * AJAX handler for saving dark mode preference.
	 *
	 * Saves per-user dark mode preference to user meta. Only users with
	 * manage_woocommerce capability can change the setting.
	 *
	 * @return void
	 */
	public function ajax_save_dark_mode(): void {
		if ( ! check_ajax_referer( 'momcs_sync_save_dark_mode_nonce', 'nonce', false ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'multi-channel-for-woocommerce' ) ) );
		}

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( array( 'message' => __( 'Unauthorized access.', 'multi-channel-for-woocommerce' ) ) );
		}

		$enabled = isset( $_POST['enabled'] ) ? sanitize_text_field( wp_unslash( $_POST['enabled'] ) ) : '0';
		$enabled = ( '1' === $enabled ) ? '1' : '0';

		update_user_meta( get_current_user_id(), 'momcs_dark_mode', $enabled );

		wp_send_json_success( array( 'enabled' => $enabled ) );
	}

	/**
	 * Add dark mode body class on plugin admin pages when user has dark mode enabled.
	 *
	 * @param string|array $classes Space-separated string or array of body classes.
	 * @return string|array Unchanged or updated classes.
	 */
	public function admin_body_class_dark_mode( $classes ) {
		$screen = get_current_screen();
		if ( ! $screen ) {
			return $classes;
		}

		$enabled = get_user_meta( get_current_user_id(), 'momcs_dark_mode', true );
		if ( '1' !== $enabled ) {
			return $classes;
		}

		// Apply on plugin admin pages (screen id contains momcs-sync).
		$is_plugin_page = strpos( $screen->id, 'momcs-sync' ) !== false;
		// Apply on WooCommerce order edit so shipment sync and fulfillment status UIs are dark.
		$is_order_edit = in_array( $screen->id, array( 'shop_order', 'woocommerce_page_wc-orders' ), true );

		if ( ! $is_plugin_page && ! $is_order_edit ) {
			return $classes;
		}

		if ( is_array( $classes ) ) {
			$classes[] = 'momcs-dark-mode';
			return $classes;
		}

		return $classes . ' momcs-dark-mode';
	}

	/**
	 * Enqueue admin styles.
	 *
	 * @return void
	 */
	public function enqueue_admin_styles(): void {
		// Enqueue WordPress dashicons.
		wp_enqueue_style( 'dashicons' );

		wp_enqueue_style(
			'momcs-sync-admin',
			MOMCS_PLUGIN_URL . 'assets/css/admin.css',
			array(),
			MOMCS_VERSION
		);

		wp_enqueue_script(
			'momcs-sync-admin',
			MOMCS_PLUGIN_URL . 'assets/js/admin.js',
			array( 'jquery' ),
			MOMCS_VERSION,
			true
		);

		wp_localize_script(
			'momcs-sync-admin',
			'momcsDarkMode',
			array(
				'enabled' => get_user_meta( get_current_user_id(), 'momcs_dark_mode', true ) === '1',
				'nonce'   => wp_create_nonce( 'momcs_sync_save_dark_mode_nonce' ),
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
			)
		);

		// Dark mode CSS is enqueued in admin_footer (see class-enqueue-scripts.php) so it loads
		// after styles registered during the page callback (e.g. product list, sync queue).

		// Add custom inline styles to override header background.
		$custom_css = '
			#wpbody-content .momcs-sync-header {
				background: transparent !important;
				box-shadow: none !important;
			}
			#wpbody-content .momcs-sync-header h1 {
				color: #000000 !important;
			}
			.momcs-marketplace-stepper-container {
				margin: 20px 0 !important;
				padding: 20px !important;
			}
		';
		wp_add_inline_style( 'momcs-sync-admin', $custom_css );
	}

	/**
	 * Register nonces.
	 *
	 * @return void
	 */
	public function register_nonces() {
		// Register nonces for AJAX requests.
		add_filter(
			'nonce_user_logged_in_gateways',
			function ( $gateways ) {
				return array_merge(
					$gateways,
					array(
						'momcs_sync_save_template_mapping_nonce',
						'momcs_sync_get_template_mapping_nonce',
						'momcs_sync_save_field_mapping_nonce',
						'momcs_sync_get_field_mapping_nonce',
						'momcs_sync_get_product_type_schema_nonce',
						'momcs_sync_save_unified_mapping_nonce',
						'momcs_sync_get_unified_mapping_nonce',
						'momcs_sync_save_mapping_nonce',
						'momcs_sync_update_step_nonce',
						'momcs_sync_save_sync_settings_nonce',
						'momcs_sync_get_sync_settings_nonce',
						'momcs_sync_get_categories_nonce',
						'momcs_order_fulfillment_retry_nonce',
						'momcs_sync_save_dark_mode_nonce',
					)
				);
			}
		);
	}
}
