<?php

namespace MyListing\Controllers\Promotions;

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

class Promotions_Admin_Controller extends \MyListing\Controllers\Base_Controller {

	protected function hooks() {
		$this->on( 'admin_menu', '@set_menu_location', 60 );
		$this->on( 'admin_footer-post.php', '@display_package_statuses' );
		$this->on( 'admin_footer-post-new.php', '@display_package_statuses' );
		$this->on( 'admin_footer-edit.php', '@display_package_statuses' );
		$this->on( 'edit_form_after_title', '@display_package_id_in_edit_screen' );
		$this->on( 'woocommerce_product_options_general_product_data', '@display_product_settings' );
		$this->on( 'manage_cts_promo_package_posts_custom_column', '@custom_table_column_contents', 5, 2 );
		$this->once( 'save_post', '@save_package_settings', 99, 2 );
		$this->filter( 'manage_cts_promo_package_posts_columns', '@custom_table_columns' );
		$this->filter( 'post_row_actions', '@remove_quick_edit_link', 10, 2 );
		$this->filter( 'bulk_actions-edit-cts_promo_package', '@remove_bulk_edit_setting' );
		$this->filter( 'woocommerce_process_product_meta_promotion_package', '@save_product_settings' );

		// Native replacement for ACF: Register metabox and save handler for Promotion Package fields
		$this->on( 'add_meta_boxes', '@add_promotion_package_metabox', 100 );
		// Save early so other handlers (e.g. status change logic) can read updated meta.
		$this->once( 'save_post', '@save_promotion_package_metabox', 10, 2 );
	}

	protected function set_menu_location() {
		if ( $post_type = get_post_type_object( 'cts_promo_package' ) ) {
			add_submenu_page(
				'users.php',
				$post_type->labels->name,
				$post_type->labels->menu_name,
				$post_type->cap->edit_posts,
				'edit.php?post_type=cts_promo_package'
			);
		}
	}

	protected function display_product_settings() {
		global $post;
		require locate_template( 'templates/admin/single-product-screen/promotion-product-settings.php' );
	}

	protected function save_product_settings( $post_id ) {
		delete_post_meta( $post_id, '_promotion_duration' );
		delete_post_meta( $post_id, '_promotion_priority' );

		if ( ! empty( $_POST['_promotion_duration'] ) ) {
			update_post_meta( $post_id, '_promotion_duration', absint( $_POST['_promotion_duration'] ) );
		}

		if ( ! empty( $_POST['_promotion_priority'] ) ) {
			update_post_meta( $post_id, '_promotion_priority', absint( $_POST['_promotion_priority'] ) );
		}
	}

	protected function save_package_settings( $post_id, $post = null ) {
		if (apply_filters('mylisting/promotions/save-package', true ) === false ) {
			return;
		}
		if ( ! ( $post && $post->post_type === 'cts_promo_package' ) || defined('DOING_AJAX') && DOING_AJAX ) {
			return;
		}

		// current listing expiry date
		$expiry_date = get_post_meta( $post_id, '_expires', true );

		// Get proper post status.
		$status = $post->post_status;
		$old_status = ! empty( $_POST['original_post_status'] ) ? $_POST['original_post_status'] : false;
		$action = ! empty( $_GET['action'] ) ? $_GET['action'] : false;

		// on status change handle activating/expiring the package
		if ( $status !== $old_status ) {
			if ( $status === 'publish' || $action === 'untrash' ) {
				\MyListing\Src\Promotions\activate_package( $post->ID );
			}

			if ( $status === 'trash' || $action === 'trash' ) {
				\MyListing\Src\Promotions\expire_package( $post->ID );
			}
		}

		// re-apply the custom expiry date set by the admin ("Promoted Until" setting)
		// since it's reset by the `activate_package` function call
		if ( $expiry_date && strtotime( $expiry_date, current_time('timestamp') ) ) {
			update_post_meta( $post->ID, '_expires', $expiry_date );
		}

		// handle priority change
		if ( $status === 'publish' ) {
			$listing_id = get_post_meta( $post_id, '_listing_id', true );
			$listing_priority = get_post_meta( $listing_id, '_featured', true );
			$package_priority = get_post_meta( $post_id, '_priority', true );
			if ( $listing_id && $listing_priority && absint( $listing_priority ) !== absint( $package_priority ) ) {
				update_post_meta( $listing_id, '_featured', absint( $package_priority ) );
			}
		}
	}

	protected function display_package_statuses() {
		global $post, $post_type;
		if ( $post_type !== 'cts_promo_package' ) {
			return;
		}

		$statuses = [
			'publish' => esc_html( __( 'Active', 'my-listing' ) ),
			'trash' => esc_html( __( 'Expired', 'my-listing' ) ),
		];

		// get all non-builtin post status and add them as <option>
		$options = $display = '';
		if ( $post instanceof \WP_Post ) {
			foreach ( $statuses as $status => $name ) {
				$selected = selected( $post->post_status, $status, false );

				// if one of our custom post statuses is selected, remember it
				$selected AND $display = $name;
				$options .= "<option{$selected} value='{$status}'>{$name}</option>";
			}
		}
		?>
		<script type="text/javascript">
			jQuery( function($) {
				<?php if ( ! empty( $display ) ): ?>
					jQuery('#post-status-display').html( '<?php echo $display; ?>' );
				<?php endif; ?>

				var select = jQuery('#post-status-select').find('select').html( "<?php echo $options ?>" );
				if ( $('body.post-type-cts_promo_package .subsubsub .trash a').length ) {
					var counter = $('body.post-type-cts_promo_package .subsubsub .trash a span').detach();
					$('body.post-type-cts_promo_package .subsubsub .trash a').html(
						'<?php echo esc_attr( _x( 'Expired', 'Admin view promotions - Expired Packages', 'my-listing' ) ) ?> '
					).append( counter );
				}

				// promoted listing cannot be changed after the package has been created
				if ( $('.promote-listing-setting select').val() ) {
					$('.promote-listing-setting').addClass('ml-overlay-disabled').css('pointer-events', 'none');
				}
			} );
		</script>
		<?php
	}

	protected function display_package_id_in_edit_screen( $post ) {
		if ( ! ( $post && $post->ID && $post->post_type === 'cts_promo_package' ) ) {
			return;
		}

		if ( empty( $_GET['action'] ) || $_GET['action'] !== 'edit' ) {
			return;
		} ?>
		<h1 class="wp-heading-inline-package">
			<?php printf( __( 'Edit Package #%d', 'my-listing' ), $post->ID ); ?>
			<a href="<?php echo esc_url( add_query_arg( 'post_type','cts_promo_package', admin_url( 'post-new.php' ) ) ) ?>" class="page-title-action">
				<?php esc_html_e( 'Add New', 'my-listing' ); ?>
			</a>
		</h1>
		<style>.wrap h1.wp-heading-inline {display:none;} .wrap > .page-title-action {display:none;} #poststuff {margin-top: 30px;}</style>
		<?php
	}

	protected function custom_table_columns( $columns ) {
		unset( $columns['date'] );
		$columns['title'] = esc_html( __( 'Package ID', 'my-listing' ) );
		$columns['user'] = esc_html( __( 'User', 'my-listing' ) );
		$columns['duration'] = esc_html( __( 'Promoted Until', 'my-listing' ) );
		$columns['product'] = esc_html( __( 'Product', 'my-listing' ) );
		$columns['order'] = esc_html( __( 'Order ID', 'my-listing' ) );

		return $columns;
	}

	protected function custom_table_column_contents(  $column, $post_id  ) {
		switch ( $column ) {
			case 'user':
				$title = esc_html( __( 'n/a', 'my-listing' ) );
				$user_id = absint( get_post_meta( $post_id, '_user_id', true ) );
				if ( $user_id ) {
					$user = get_userdata( $user_id );
					if ( $user ) {
						$title = '<a target="_blank" href="' . esc_url( get_edit_user_link( $user_id ) ) . '">';
						$title .= $user->user_login;
						$title .= '</a>';
					}
				}

				echo $title;
			break;

			case 'duration':
				$expires = get_post_meta( $post_id, '_expires', true );
				$expiry_time = strtotime( $expires, current_time( 'timestamp' ) );
				echo $expiry_time ? date_i18n( 'F j, Y g:i a', $expiry_time ) : '&ndash;';
			break;

			case 'product':
				$link = esc_html__( 'n/a', 'my-listing' );
				$product_id = get_post_meta( $post_id, '_product_id', true );
				if ( $product_id ) {
					$product = wc_get_product( $product_id );
					if ( $product ) {
						$link = '<a target="_blank" href="'.esc_url( get_edit_post_link( $product_id ) ).'">'.$product->get_name().'</a>';
					}
				}
				echo $link;
			break;

			case 'order':
				$link = esc_html__( 'n/a', 'my-listing' );
				$order_id = absint( get_post_meta( $post_id, '_order_id', true ) );
				if ( $order_id ) {
					$link = '<a target="_blank" href="'.esc_url( get_edit_post_link( $order_id ) ).'">#'.$order_id.'</a>';
				}
				echo $link;
			break;
		}
	}

	protected function remove_quick_edit_link( $actions, $post ) {
		if ( $post->post_type !== 'cts_promo_package' ) {
			return $actions;
		}

		$actions['edit'] = sprintf(
			'<a href="%s">%s</a>',
			get_edit_post_link( $post ),
			_x( 'Edit Package', 'Promotions list in wp-admin', 'my-listing' )
		);

		if ( $listing_id = absint( $post->_listing_id ) ) {
			$actions['inline hide-if-no-js'] = sprintf(
				'<a href="%s">%s</a>',
				get_edit_post_link( $listing_id ),
				_x( 'Edit Listing', 'Promotions list in wp-admin', 'my-listing' )
			);
		} else {
			unset( $actions['inline hide-if-no-js'] );
		}

		return $actions;
	}

	protected function remove_bulk_edit_setting( $actions ) {
		unset( $actions['edit'] );
		return $actions;
	}

	/**
	 * Register native Promotion Package metabox (replaces ACF group "Promotion Package").
	 */
	protected function add_promotion_package_metabox() {
		add_meta_box(
			'ml-promotion-package',
			_x( 'Promotion Package', 'Promotions metabox title', 'my-listing' ),
			[ $this, 'render_promotion_package_metabox' ],
			'cts_promo_package',
			'normal',
			'high'
		);

		// Hide legacy ACF group metabox if present (to prevent duplicate UI).
		remove_meta_box( 'acf-group_5b1a02fc17912', 'cts_promo_package', 'normal' );
	}

	/**
	 * Render native Promotion Package metabox fields.
	 */
	public function render_promotion_package_metabox( $post ) {
		if ( ! ( $post && $post->post_type === 'cts_promo_package' ) ) {
			return;
		}

		// Nonce for saving.
		wp_nonce_field( 'ml_promotion_package_save', 'ml_promotion_package_nonce' );

		// Read existing values.
		$listing_id  = absint( get_post_meta( $post->ID, '_listing_id', true ) );
		$expires_raw = get_post_meta( $post->ID, '_expires', true );
		$expires_dt  = $expires_raw ? date( 'Y-m-d\TH:i', strtotime( $expires_raw ) ) : '';
		$duration    = get_post_meta( $post->ID, '_duration', true );
		$priority    = get_post_meta( $post->ID, '_priority', true );
		$user_id     = absint( get_post_meta( $post->ID, '_user_id', true ) );
		$product_id  = absint( get_post_meta( $post->ID, '_product_id', true ) );
		$order_id    = absint( get_post_meta( $post->ID, '_order_id', true ) );

		// Prepare select options for convenience.
		$listings = get_posts( [
			'post_type'      => 'job_listing',
			'post_status'    => [ 'publish', 'pending', 'draft', 'private' ],
			'posts_per_page' => 30,
			'orderby'        => 'date',
			'order'          => 'DESC',
			'fields'         => 'ids',
		] );
		if ( $listing_id && ! in_array( $listing_id, $listings, true ) ) {
			$listings[] = $listing_id;
		}

		// Promotion products.
		$products = get_posts( [
			'post_type'      => 'product',
			'post_status'    => [ 'publish', 'private' ],
			'posts_per_page' => 50,
			'fields'         => 'ids',
			'tax_query'      => [ [
				'taxonomy' => 'product_type',
				'field'    => 'slug',
				'terms'    => [ 'promotion_package' ],
			] ],
		] );
		if ( $product_id && ! in_array( $product_id, $products, true ) ) {
			$products[] = $product_id;
		}

		// Recent orders.
		$orders = get_posts( [
			'post_type'      => 'shop_order',
			'post_status'    => array_keys( wc_get_order_statuses() ),
			'posts_per_page' => 30,
			'orderby'        => 'date',
			'order'          => 'DESC',
			'fields'         => 'ids',
		] );
		if ( $order_id && ! in_array( $order_id, $orders, true ) ) {
			$orders[] = $order_id;
		}

		echo '<div class="ml-admin-promo-package">';

		// Promoted Listing (keep class for legacy JS overlay behavior).
		echo '<p class="promote-listing-setting">';
		echo '<label class="ml-backend-label" for="ml_promo_listing_id">' . esc_html__( 'Promoted Listing', 'my-listing' ) . '</label>';
		echo '<select name="ml_promo_listing_id" id="ml_promo_listing_id" style="width:100%">';
		echo '<option value="">' . esc_html__( '— Select listing —', 'my-listing' ) . '</option>';
		foreach ( $listings as $lid ) {
			$title = get_the_title( $lid );
			printf( '<option value="%1$s" %2$s>#%1$s — %3$s</option>', esc_attr( $lid ), selected( $listing_id, $lid, false ), esc_html( $title ) );
		}
		echo '</select>';
		echo '</p>';

		// Promoted Until (datetime-local)
		echo '<p>';
		echo '<label class="ml-backend-label" for="ml_promo_expires">' . esc_html__( 'Promoted Until', 'my-listing' ) . '</label>';
		echo '<input type="datetime-local" id="ml_promo_expires" name="ml_promo_expires" value="' . esc_attr( $expires_dt ) . '" class="regular-text" />';
		echo '<span class="description" style="display:block;margin-top:4px">' . esc_html__( 'Listing will be promoted until this date, after which, the promotion package expires.', 'my-listing' ) . '</span>';
		echo '</p>';

		// Duration (hidden in UI but kept for compatibility).
		echo '<p class="cts-hidden">';
		echo '<label class="ml-backend-label" for="ml_promo_duration">' . esc_html__( 'Duration (days)', 'my-listing' ) . '</label>';
		echo '<input type="number" min="0" step="1" id="ml_promo_duration" name="ml_promo_duration" value="' . esc_attr( $duration ) . '" placeholder="' . esc_attr__( 'Default', 'my-listing' ) . '" class="small-text" />';
		echo '</p>';

		// Listing Priority
		echo '<p>';
		echo '<label class="ml-backend-label" for="ml_promo_priority">' . esc_html__( 'Listing Priority', 'my-listing' ) . '</label>';
		echo '<input type="number" min="0" step="1" id="ml_promo_priority" name="ml_promo_priority" value="' . esc_attr( $priority ) . '" class="small-text" />';
		echo '<span class="description" style="display:block;margin-top:4px">' . esc_html__( 'Higher value means the listing will have higher priority in search results.', 'my-listing' ) . '</span>';
		echo '</p>';

		// User
		echo '<p>';
		echo '<label class="ml-backend-label" for="ml_promo_user_id">' . esc_html__( 'User', 'my-listing' ) . '</label>';
		wp_dropdown_users( [
			'name'             => 'ml_promo_user_id',
			'selected'         => $user_id,
			'show_option_none' => esc_html__( '— None —', 'my-listing' ),
			'include_selected' => true,
			'class'            => 'widefat',
			'id'               => 'ml_promo_user_id',
		] );
		echo '</p>';

		// Product
		echo '<p>';
		echo '<label class="ml-backend-label" for="ml_promo_product_id">' . esc_html__( 'Product', 'my-listing' ) . '</label>';
		echo '<select name="ml_promo_product_id" id="ml_promo_product_id" style="width:100%">';
		echo '<option value="">' . esc_html__( '— None —', 'my-listing' ) . '</option>';
		foreach ( $products as $pid ) {
			$p = wc_get_product( $pid );
			if ( ! $p ) { continue; }
			printf( '<option value="%1$s" %2$s>#%1$s — %3$s</option>', esc_attr( $pid ), selected( $product_id, $pid, false ), esc_html( $p->get_name() ) );
		}
		echo '</select>';
		echo '</p>';

		// Order
		echo '<p>';
		echo '<label class="ml-backend-label" for="ml_promo_order_id">' . esc_html__( 'Order', 'my-listing' ) . '</label>';
		echo '<select name="ml_promo_order_id" id="ml_promo_order_id" style="width:100%" class="order-by-date prepend-item-id">';
		echo '<option value="">' . esc_html__( '— None —', 'my-listing' ) . '</option>';
		foreach ( $orders as $oid ) {
			$order = function_exists( 'wc_get_order' ) ? wc_get_order( $oid ) : null;
			$label = $order ? sprintf( '#%s — %s', $order->get_order_number(), $order->get_date_created() ? $order->get_date_created()->date_i18n( 'F j, Y g:i a' ) : '' ) : ( '#' . $oid );
			printf( '<option value="%1$s" %2$s>%3$s</option>', esc_attr( $oid ), selected( $order_id, $oid, false ), esc_html( $label ) );
		}
		echo '</select>';
		echo '</p>';

		echo '</div>';
	}

	/**
	 * Save native Promotion Package metabox.
	 */
	protected function save_promotion_package_metabox( $post_id, $post ) {
		if ( ! ( $post && $post->post_type === 'cts_promo_package' ) ) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Reading nonce from $_POST to verify it.
		if ( empty( $_POST['ml_promotion_package_nonce'] ) || ! wp_verify_nonce( $_POST['ml_promotion_package_nonce'], 'ml_promotion_package_save' ) ) {
			return;
		}
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		// phpcs:disable WordPress.Security.NonceVerification.Missing -- Nonce verified above; safe to read $_POST values below.
		$listing_id  = isset( $_POST['ml_promo_listing_id'] ) ? absint( $_POST['ml_promo_listing_id'] ) : 0;
		$expires_in  = isset( $_POST['ml_promo_expires'] ) ? sanitize_text_field( wp_unslash( $_POST['ml_promo_expires'] ) ) : '';
		$duration    = isset( $_POST['ml_promo_duration'] ) ? absint( $_POST['ml_promo_duration'] ) : '';
		$priority    = isset( $_POST['ml_promo_priority'] ) ? absint( $_POST['ml_promo_priority'] ) : '';
		$user_id     = isset( $_POST['ml_promo_user_id'] ) ? absint( $_POST['ml_promo_user_id'] ) : 0;
		$product_id  = isset( $_POST['ml_promo_product_id'] ) ? absint( $_POST['ml_promo_product_id'] ) : 0;
		$order_id    = isset( $_POST['ml_promo_order_id'] ) ? absint( $_POST['ml_promo_order_id'] ) : 0;
		// phpcs:enable WordPress.Security.NonceVerification.Missing

		// Validate referenced objects.
		if ( $listing_id && 'job_listing' !== get_post_type( $listing_id ) ) {
			$listing_id = 0;
		}
		if ( $product_id && 'product' !== get_post_type( $product_id ) ) {
			$product_id = 0;
		}
		if ( $order_id && 'shop_order' !== get_post_type( $order_id ) ) {
			$order_id = 0;
		}
		if ( $user_id && ! get_userdata( $user_id ) ) {
			$user_id = 0;
		}

		// Convert datetime-local to Y-m-d H:i:s.
		$expires = '';
		if ( ! empty( $expires_in ) ) {
			$ts = strtotime( $expires_in );
			if ( $ts ) {
				$expires = date( 'Y-m-d H:i:s', $ts );
			}
		}

		// Persist meta (add/update or delete when empty).
		$listing_id ? update_post_meta( $post_id, '_listing_id', $listing_id ) : delete_post_meta( $post_id, '_listing_id' );
		$expires    ? update_post_meta( $post_id, '_expires', $expires )       : delete_post_meta( $post_id, '_expires' );
		( $duration !== '' ) ? update_post_meta( $post_id, '_duration', $duration ) : delete_post_meta( $post_id, '_duration' );
		( $priority !== '' ) ? update_post_meta( $post_id, '_priority', $priority ) : delete_post_meta( $post_id, '_priority' );
		$user_id    ? update_post_meta( $post_id, '_user_id', $user_id )       : delete_post_meta( $post_id, '_user_id' );
		$product_id ? update_post_meta( $post_id, '_product_id', $product_id ) : delete_post_meta( $post_id, '_product_id' );
		$order_id   ? update_post_meta( $post_id, '_order_id', $order_id )     : delete_post_meta( $post_id, '_order_id' );
	}
}