<?php
/**
 * Bulk actions for the vehicle admin list table.
 *
 * Adds "Mark as Available/Sold/Reserved/Coming Soon" and "Set/Remove
 * Featured" entries to the bulk-actions dropdown. WP's built-in
 * Move-to-Trash / Delete-Permanently cover the destructive cases.
 *
 * Each action writes post meta (the canonical source) and pushes it into
 * `wp_trx_ad_vehicle_specs` via VehicleSpecsSync, then flushes the
 * aggregation cache so archive widgets pick up the change. Writing the
 * specs table directly (as versions <= 1.0.6 did) left post meta stale, so
 * the next save_post re-synced the OLD status over the bulk change and the
 * meta-reading surfaces (Reserve button, uninstall wipe) disagreed with the
 * table (demo-site finding D5, same divergence class as R2-8).
 *
 * @package ThemeREX\AutoDealer\Admin\ListTable
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Admin\ListTable;

defined( 'ABSPATH' ) || exit;

use ThemeREX\AutoDealer\Database\VehicleSpecsSync;
use ThemeREX\AutoDealer\PostTypes\VehiclePostType;

final class BulkActions {

	private const STATUS_ACTIONS = array(
		'trx_ad_mark_available'   => 'available',
		'trx_ad_mark_sold'        => 'sold',
		'trx_ad_mark_reserved'    => 'reserved',
		'trx_ad_mark_coming_soon' => 'coming_soon',
	);

	public function register(): void {
		$postType = VehiclePostType::POST_TYPE;
		add_filter( "bulk_actions-edit-{$postType}", array( $this, 'registerActions' ) );
		add_filter( "handle_bulk_actions-edit-{$postType}", array( $this, 'handleActions' ), 10, 3 );
		add_action( 'admin_notices', array( $this, 'renderNotice' ) );
	}

	/**
	 * @param array<string,string> $actions Existing actions.
	 * @return array<string,string>
	 */
	public function registerActions( array $actions ): array {
		$actions['trx_ad_mark_available']   = __( 'Mark as Available', 'trx-auto-dealer' );
		$actions['trx_ad_mark_sold']        = __( 'Mark as Sold', 'trx-auto-dealer' );
		$actions['trx_ad_mark_reserved']    = __( 'Mark as Reserved', 'trx-auto-dealer' );
		$actions['trx_ad_mark_coming_soon'] = __( 'Mark as Coming Soon', 'trx-auto-dealer' );
		$actions['trx_ad_feature']          = __( 'Set Featured', 'trx-auto-dealer' );
		$actions['trx_ad_unfeature']        = __( 'Remove Featured', 'trx-auto-dealer' );
		return $actions;
	}

	/**
	 * @param string         $redirect Redirect URL after handling.
	 * @param string         $doaction Action slug.
	 * @param array<int,int> $post_ids Selected post IDs.
	 * @return string Redirect URL with status query args appended.
	 */
	public function handleActions( string $redirect, string $doaction, array $post_ids ): string {
		if ( ! isset( self::STATUS_ACTIONS[ $doaction ] ) && ! in_array( $doaction, array( 'trx_ad_feature', 'trx_ad_unfeature' ), true ) ) {
			return $redirect;
		}

		if ( ! current_user_can( 'edit_posts' ) ) {
			return $redirect;
		}

		$sync  = new VehicleSpecsSync();
		$count = 0;

		foreach ( array_map( 'intval', $post_ids ) as $post_id ) {
			if ( get_post_type( $post_id ) !== VehiclePostType::POST_TYPE ) {
				continue;
			}
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
				continue;
			}

			if ( isset( self::STATUS_ACTIONS[ $doaction ] ) ) {
				update_post_meta( $post_id, '_trx_ad_status', self::STATUS_ACTIONS[ $doaction ] );
			} elseif ( 'trx_ad_feature' === $doaction ) {
				update_post_meta( $post_id, '_trx_ad_featured', '1' );
			} elseif ( 'trx_ad_unfeature' === $doaction ) {
				update_post_meta( $post_id, '_trx_ad_featured', '0' );
			}
			$sync->syncOnSave( $post_id );
			++$count;
		}

		do_action( 'trx_ad_cache_flush_aggregations' );

		return add_query_arg(
			array(
				'trx_ad_bulk_done'  => $doaction,
				'trx_ad_bulk_count' => $count,
			),
			$redirect
		);
	}

	public function renderNotice(): void {
		if ( ! isset( $_GET['trx_ad_bulk_done'], $_GET['trx_ad_bulk_count'] ) ) {
			return;
		}
		$count = (int) $_GET['trx_ad_bulk_count'];
		if ( $count <= 0 ) {
			return;
		}
		printf(
			'<div class="notice notice-success is-dismissible"><p>%s</p></div>',
			esc_html(
				sprintf(
					/* translators: %d: number of listings updated. */
					_n( '%d listing updated.', '%d listings updated.', $count, 'trx-auto-dealer' ),
					$count
				)
			)
		);
	}
}
