<?php
/**
 * Admin UI — menu registration, asset loading, AJAX handlers.
 *
 * @package Smart_Product_Sort
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class SPSORT_Admin
 */
class SPSORT_Admin {

	/**
	 * Single instance.
	 *
	 * @var SPSORT_Admin|null
	 */
	private static $instance = null;

	/**
	 * Admin page hook suffix.
	 *
	 * @var string
	 */
	private $page_hook = '';

	/**
	 * Get or create instance.
	 *
	 * @return SPSORT_Admin
	 */
	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor.
	 */
	private function __construct() {
		add_action( 'admin_menu', array( $this, 'register_menus' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );

		// AJAX handlers.
		add_action( 'wp_ajax_spsort_save_rule', array( $this, 'ajax_save_rule' ) );
		add_action( 'wp_ajax_spsort_delete_rule', array( $this, 'ajax_delete_rule' ) );
		add_action( 'wp_ajax_spsort_toggle_rule', array( $this, 'ajax_toggle_rule' ) );
	}

	/**
	 * Register WooCommerce submenu page.
	 *
	 * @return void
	 */
	public function register_menus() {
		$this->page_hook = add_submenu_page(
			'woocommerce',
			esc_html__( 'Smart Product Sort', 'smart-product-sort' ),
			esc_html__( 'Smart Product Sort', 'smart-product-sort' ),
			'manage_woocommerce',
			'smart-product-sort',
			array( $this, 'render_main_page' )
		);
	}

	/**
	 * Enqueue admin styles and scripts only on plugin page.
	 *
	 * @param string $hook Current admin page hook.
	 * @return void
	 */
	public function enqueue_assets( $hook ) {
		if ( $this->page_hook !== $hook ) {
			return;
		}

		wp_enqueue_style(
			'spsort-admin',
			SPSORT_PLUGIN_URL . 'admin/css/admin.css',
			array(),
			SPSORT_VERSION
		);

		wp_enqueue_script(
			'spsort-admin',
			SPSORT_PLUGIN_URL . 'admin/js/admin.js',
			array( 'jquery' ),
			SPSORT_VERSION,
			true
		);

		$localize_data = array(
			'ajaxUrl' => admin_url( 'admin-ajax.php' ),
			'nonce'   => wp_create_nonce( 'spsort_admin_nonce' ),
			'isPro'   => false,
			'i18n'    => array(
				'confirmDelete' => esc_html__( 'Delete this sort rule? This cannot be undone.', 'smart-product-sort' ),
				'saving'        => esc_html__( 'Saving…', 'smart-product-sort' ),
				'saveRule'      => esc_html__( 'Save Rule', 'smart-product-sort' ),
				'error'         => esc_html__( 'Something went wrong. Please try again.', 'smart-product-sort' ),
				'addSortRule'   => esc_html__( 'Add Sort Rule', 'smart-product-sort' ),
				'editSortRule'  => esc_html__( 'Edit Sort Rule', 'smart-product-sort' ),
				'active'        => esc_html__( 'Active', 'smart-product-sort' ),
				'inactive'      => esc_html__( 'Inactive', 'smart-product-sort' ),
				'noRules'       => esc_html__( 'No sort rules found. Add one above!', 'smart-product-sort' ),
			),
		);

		/**
		 * Filter the localized script data — allows Pro to add i18n strings and flags.
		 *
		 * @param array $localize_data Data to pass to JS.
		 */
		$localize_data = apply_filters( 'spsort_admin_localize', $localize_data );

		wp_localize_script( 'spsort-admin', 'spsortData', $localize_data );
	}

	/**
	 * Render the main admin page.
	 *
	 * @return void
	 */
	public function render_main_page() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'You do not have permission to access this page.', 'smart-product-sort' ) );
		}

		$rules      = SPSORT_Sort_Rules::get_all();
		$categories = get_terms(
			array(
				'taxonomy'   => 'product_cat',
				'hide_empty' => false,
				'orderby'    => 'name',
			)
		);

		include SPSORT_PLUGIN_DIR . 'admin/views/main-page.php';
	}

	// -------------------------------------------------------------------------
	// AJAX Handlers
	// -------------------------------------------------------------------------

	/**
	 * AJAX: create or update a sort rule.
	 *
	 * @return void
	 */
	public function ajax_save_rule() {
		check_ajax_referer( 'spsort_admin_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Permission denied.', 'smart-product-sort' ) ) );
		}

		$data = array(
			'rule_name'   => sanitize_text_field( wp_unslash( $_POST['rule_name'] ?? '' ) ),
			'sort_by'     => sanitize_key( $_POST['sort_by'] ?? 'date' ),
			'sort_order'  => sanitize_key( $_POST['sort_order'] ?? 'DESC' ),
			'category_id' => ! empty( $_POST['category_id'] ) ? absint( $_POST['category_id'] ) : null,
			'is_active'   => isset( $_POST['is_active'] ) ? (int) (bool) $_POST['is_active'] : 1,
			'priority'    => isset( $_POST['priority'] ) ? absint( $_POST['priority'] ) : 10,
		);

		$rule_id = ! empty( $_POST['rule_id'] ) ? absint( $_POST['rule_id'] ) : 0;

		if ( $rule_id ) {
			$result = SPSORT_Sort_Rules::update( $rule_id, $data );
			$id     = $rule_id;
		} else {
			$result = SPSORT_Sort_Rules::insert( $data );
			$id     = $result;
		}

		if ( $result ) {
			wp_send_json_success(
				array(
					'message' => esc_html__( 'Rule saved successfully.', 'smart-product-sort' ),
					'id'      => $id,
				)
			);
		} else {
			wp_send_json_error( array( 'message' => esc_html__( 'Could not save rule. Check all fields.', 'smart-product-sort' ) ) );
		}
	}

	/**
	 * AJAX: delete a sort rule.
	 *
	 * @return void
	 */
	public function ajax_delete_rule() {
		check_ajax_referer( 'spsort_admin_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Permission denied.', 'smart-product-sort' ) ) );
		}

		$rule_id = absint( $_POST['rule_id'] ?? 0 );
		if ( ! $rule_id ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Invalid rule ID.', 'smart-product-sort' ) ) );
		}

		if ( SPSORT_Sort_Rules::delete( $rule_id ) ) {
			wp_send_json_success( array( 'message' => esc_html__( 'Rule deleted.', 'smart-product-sort' ) ) );
		} else {
			wp_send_json_error( array( 'message' => esc_html__( 'Could not delete rule.', 'smart-product-sort' ) ) );
		}
	}

	/**
	 * AJAX: toggle a rule's active status.
	 *
	 * @return void
	 */
	public function ajax_toggle_rule() {
		check_ajax_referer( 'spsort_admin_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Permission denied.', 'smart-product-sort' ) ) );
		}

		$rule_id = absint( $_POST['rule_id'] ?? 0 );
		$rule    = SPSORT_Sort_Rules::get( $rule_id );

		if ( ! $rule ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Rule not found.', 'smart-product-sort' ) ) );
		}

		$new_status = $rule->is_active ? 0 : 1;
		SPSORT_Sort_Rules::update( $rule_id, array_merge( (array) $rule, array( 'is_active' => $new_status ) ) );

		wp_send_json_success(
			array(
				'is_active' => $new_status,
				'message'   => $new_status
					? esc_html__( 'Rule activated.', 'smart-product-sort' )
					: esc_html__( 'Rule deactivated.', 'smart-product-sort' ),
			)
		);
	}
}
