<?php
/**
 * AJAX handler class.
 *
 * @package BW_Admin_Column
 */

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

class BW_Admin_Column_Ajax {

	/**
	 * Singleton instance.
	 *
	 * @var BW_Admin_Column_Ajax|null
	 */
	private static $instance = null;

	/**
	 * Get singleton instance.
	 *
	 * @return BW_Admin_Column_Ajax
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor.
	 */
	private function __construct() {
		add_action( 'wp_ajax_bw_set_featured_image', array( $this, 'bw_ajax_set_featured_image' ) );
		add_action( 'wp_ajax_bw_scan_meta_keys', array( $this, 'bw_ajax_scan_meta_keys' ) );
	}

	/**
	 * AJAX: Set or remove a post's featured image.
	 */
	public function bw_ajax_set_featured_image() {
		$post_id      = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
		$thumbnail_id = isset( $_POST['thumbnail_id'] ) ? intval( $_POST['thumbnail_id'] ) : 0;

		if ( ! $post_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid post ID.', 'bw-admin-column' ) ) );
		}

		if ( ! check_ajax_referer( 'bw_set_featured_image_' . $post_id, 'nonce', false ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'bw-admin-column' ) ) );
		}

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'bw-admin-column' ) ) );
		}

		// Remove featured image.
		if ( $thumbnail_id <= 0 ) {
			delete_post_thumbnail( $post_id );
			wp_send_json_success( array(
				'html'         => $this->bw_get_image_cell_html( $post_id ),
				'thumbnail_id' => 0,
			) );
		}

		// Set featured image.
		if ( set_post_thumbnail( $post_id, $thumbnail_id ) ) {
			wp_send_json_success( array(
				'html'         => $this->bw_get_image_cell_html( $post_id ),
				'thumbnail_id' => $thumbnail_id,
			) );
		}

		wp_send_json_error( array( 'message' => __( 'Could not set featured image.', 'bw-admin-column' ) ) );
	}

	/**
	 * Generate the HTML for a featured image cell.
	 *
	 * @param int $post_id Post ID.
	 * @return string HTML string.
	 */
	private function bw_get_image_cell_html( $post_id ) {
		ob_start();
		$thumbnail_id = get_post_thumbnail_id( $post_id );
		$nonce        = wp_create_nonce( 'bw_set_featured_image_' . $post_id );
		?>
		<div class="bw-featured-image-cell" data-post-id="<?php echo esc_attr( $post_id ); ?>" data-nonce="<?php echo esc_attr( $nonce ); ?>" title="<?php esc_attr_e( 'Click to change featured image', 'bw-admin-column' ); ?>">
			<?php if ( $thumbnail_id ) : ?>
				<?php echo get_the_post_thumbnail( $post_id, array( 50, 50 ), array( 'class' => 'bw-admin-thumb' ) ); ?>
			<?php else : ?>
				<span class="dashicons dashicons-format-image bw-no-thumb-icon"></span>
			<?php endif; ?>
		</div>
		<?php
		return ob_get_clean();
	}

	/**
	 * AJAX: Scan and return meta keys for a post type.
	 */
	public function bw_ajax_scan_meta_keys() {
		if ( ! check_ajax_referer( 'bw_admin_column_nonce', 'nonce', false ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'bw-admin-column' ) ) );
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'bw-admin-column' ) ) );
		}

		$post_type    = isset( $_POST['post_type'] ) ? sanitize_key( $_POST['post_type'] ) : '';
		$show_private = ! empty( $_POST['show_private'] );

		if ( empty( $post_type ) || ! post_type_exists( $post_type ) ) {
			wp_send_json_error( array( 'message' => __( 'Invalid post type.', 'bw-admin-column' ) ) );
		}

		$settings_instance = BW_Admin_Column_Settings::get_instance();
		$meta_keys         = $settings_instance->bw_get_meta_keys_for_post_type( $post_type, $show_private );

		$current_settings = $settings_instance->bw_get_post_type_settings( $post_type );
		$selected         = isset( $current_settings['meta_keys'] ) ? $current_settings['meta_keys'] : array();

		wp_send_json_success( array(
			'meta_keys' => $meta_keys,
			'selected'  => $selected,
		) );
	}
}
