<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput
// phpcs:disable WordPress.WP.EnqueuedResourceParameters
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable WordPress.DB.PreparedSQLPlaceholders
// phpcs:disable WordPress.DB.DirectDatabaseQuery
// phpcs:disable WordPress.DB.SlowDBQuery
// phpcs:disable PluginCheck.Security.DirectDB
// phpcs:disable PluginCheck.CodeAnalysis
// phpcs:disable WordPressVIPMinimum

/**
 * GT BOGO Engine — Conflict Resolver (v3.11.0)
 * Detects priority clashes, discount conflicts between packs,
 * scope overlaps, and customer type targeting conflicts.
 *
 * @package GT_BOGO_Engine
 * @since   3.11.0
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! current_user_can( 'manage_options' ) ) {
	return;
}

$is_pro       = function_exists( 'gt_bogo_has_pro' ) ? gt_bogo_has_pro() : false;
$message      = '';
$message_type = 'success';
global $wpdb;
$table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->prefix . 'gtbogo_rules' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
$rules        = $table_exists ? $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
	"SELECT * FROM {$wpdb->prefix}gtbogo_rules WHERE status='active' ORDER BY priority ASC",
	ARRAY_A
) : array();

// ── Handle inline priority fix ────────────────────────────────────────────────
if ( $is_pro && isset( $_POST['gtbogo_fix_priority'] ) && check_admin_referer( 'gtbogo_fix_priority' ) ) {
	$fix_id  = intval( $_POST['fix_rule_id'] ?? 0 );
	$fix_pri = intval( $_POST['fix_priority'] ?? 10 );
	if ( $fix_id && $table_exists ) {
		$wpdb->update( $wpdb->prefix . 'gtbogo_rules', array( 'priority' => $fix_pri ), array( 'id' => $fix_id ), array( '%d' ), array( '%d' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
		delete_transient( 'gtbogo_active_rules' );
		delete_transient( 'gtbogo_active_rules_summary' );
		$message      = 'Priority updated.';
		$message_type = 'success';
		$rules        = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}gtbogo_rules WHERE status='active' ORDER BY priority ASC", ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
	}
}

// ── Handle deactivate conflict rule ──────────────────────────────────────────
if ( $is_pro && isset( $_POST['gtbogo_deactivate_rule'] ) && check_admin_referer( 'gtbogo_deactivate_rule' ) ) {
	$deact_id = intval( $_POST['deact_rule_id'] ?? 0 );
	if ( $deact_id && $table_exists ) {
		$wpdb->update( $wpdb->prefix . 'gtbogo_rules', array( 'status' => 'inactive' ), array( 'id' => $deact_id ), array( '%s' ), array( '%d' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
		delete_transient( 'gtbogo_active_rules' );
		delete_transient( 'gtbogo_active_rules_summary' );
		$message      = 'Rule deactivated.';
		$message_type = 'success';
		$rules        = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}gtbogo_rules WHERE status='active' ORDER BY priority ASC", ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
	}
}

// ── Conflict detection ────────────────────────────────────────────────────────

// 1. Priority conflicts — two rules with same priority number
$priority_conflicts = array();
$priority_map       = array();
foreach ( $rules as $rule ) {
	$p = intval( $rule['priority'] ?? 0 );
	if ( isset( $priority_map[ $p ] ) ) {
		$priority_conflicts[] = array(
			'type'     => 'priority',
			'label'    => 'Same Priority — Unpredictable Firing Order',
			'desc'     => 'Both rules have priority ' . esc_html( $p ) . '. WooCommerce will apply one unpredictably. Fix by giving one a unique priority.',
			'rule_a'   => $priority_map[ $p ],
			'rule_b'   => $rule,
			'severity' => 'high',
		);
	} else {
		$priority_map[ $p ] = $rule;
	}
}

// 2. Discount conflicts — rules on same scope offering different discounts
$discount_conflicts = array();
for ( $i = 0; $i < count( $rules ); $i++ ) {
	for ( $j = $i + 1; $j < count( $rules ); $j++ ) {
		$a      = $rules[ $i ];
		$b      = $rules[ $j ];
		$disc_a = floatval( $a['discount_value'] ?? 0 );
		$disc_b = floatval( $b['discount_value'] ?? 0 );
		$type_a = $a['discount_type'] ?? 'percent';
		$type_b = $b['discount_type'] ?? 'percent';
		if ( $type_a !== $type_b ) {
			continue;
		}
		if ( abs( $disc_a - $disc_b ) < 0.01 ) {
			continue;
		}
		// Both global scope — will both fire on same cart
		$scope_a = $a['scope'] ?? 'global';
		$scope_b = $b['scope'] ?? 'global';
		if ( $scope_a === 'global' && $scope_b === 'global' ) {
			$cat_a  = json_decode( $a['categories'] ?? '[]', true ) ?: array();
			$cat_b  = json_decode( $b['categories'] ?? '[]', true ) ?: array();
			$prod_a = json_decode( $a['products'] ?? '[]', true ) ?: array();
			$prod_b = json_decode( $b['products'] ?? '[]', true ) ?: array();
			// If both global with no scope restriction
			if ( empty( $cat_a ) && empty( $cat_b ) && empty( $prod_a ) && empty( $prod_b ) ) {
				$discount_conflicts[] = array(
					'type'     => 'discount',
					'label'    => 'Discount Rate Conflict — Customers May See Inconsistent Pricing',
					'desc'     => sprintf(
						'Both rules are global scope. Rule "%s" offers %s%% off, rule "%s" offers %s%% off. Customers qualifying for both will have the higher-priority rule applied but may have seen the lower rate advertised on product pages.',
						esc_html( $a['name'] ?? 'Rule A' ),
						$disc_a,
						esc_html( $b['name'] ?? 'Rule B' ),
						$disc_b
					),
					'rule_a'   => $a,
					'rule_b'   => $b,
					'severity' => 'medium',
				);
			}
		}
		// Category overlap
		if ( ! empty( $cat_a ?? array() ) && ! empty( $cat_b ?? array() ) ) {
			$overlap = array_intersect(
				json_decode( $a['categories'] ?? '[]', true ) ?: array(),
				json_decode( $b['categories'] ?? '[]', true ) ?: array()
			);
			if ( ! empty( $overlap ) ) {
				$discount_conflicts[] = array(
					'type'     => 'discount_category',
					'label'    => 'Category Discount Conflict — Same Category, Different Rates',
					'desc'     => sprintf(
						'Rules "%s" (%s%% off) and "%s" (%s%% off) both target overlapping categories. Customers in those categories will receive the higher-priority deal, but product badge and savings display may show conflicting amounts.',
						esc_html( $a['name'] ?? 'Rule A' ),
						$disc_a,
						esc_html( $b['name'] ?? 'Rule B' ),
						$disc_b
					),
					'rule_a'   => $a,
					'rule_b'   => $b,
					'severity' => 'medium',
				);
			}
		}
	}
}

// 3. Customer type conflicts — rules targeting same segment with different deals
$segment_conflicts = array();
for ( $i = 0; $i < count( $rules ); $i++ ) {
	for ( $j = $i + 1; $j < count( $rules ); $j++ ) {
		$a       = $rules[ $i ];
		$b       = $rules[ $j ];
		$ctype_a = $a['conditions'] ?? array();
		$ctype_b = $b['conditions'] ?? array();
		if ( is_string( $ctype_a ) ) {
			$ctype_a = json_decode( $ctype_a, true ) ?: array();
		}
		if ( is_string( $ctype_b ) ) {
			$ctype_b = json_decode( $ctype_b, true ) ?: array();
		}
		$ct_a    = $ctype_a['customer_type'] ?? 'all';
		$ct_b    = $ctype_b['customer_type'] ?? 'all';
		$roles_a = (array) ( $ctype_a['user_roles'] ?? array() );
		$roles_b = (array) ( $ctype_b['user_roles'] ?? array() );
		// Same customer type, different discounts
		if ( $ct_a === $ct_b && $ct_a !== 'all' ) {
			$disc_a = floatval( $a['discount_value'] ?? 0 );
			$disc_b = floatval( $b['discount_value'] ?? 0 );
			if ( abs( $disc_a - $disc_b ) > 0.01 ) {
				$segment_conflicts[] = array(
					'type'     => 'segment',
					'label'    => ucfirst( $ct_a ) . ' Customer Segment Conflict',
					'desc'     => sprintf(
						'Two rules target "%s" customers with different discounts (%s%% vs %s%%). The highest-priority rule fires, but product-level displays may show the wrong rate.',
						$ct_a,
						$disc_a,
						$disc_b
					),
					'rule_a'   => $a,
					'rule_b'   => $b,
					'severity' => 'low',
				);
			}
		}
		// Role overlap
		if ( ! empty( $roles_a ) && ! empty( $roles_b ) ) {
			$role_overlap = array_intersect( $roles_a, $roles_b );
			if ( ! empty( $role_overlap ) ) {
				$segment_conflicts[] = array(
					'type'     => 'role_overlap',
					'label'    => 'Role Overlap — Same Customer Role, Competing Rules',
					'desc'     => sprintf(
						'Rules "%s" and "%s" both target role(s): %s. Customers with these roles will receive only the highest-priority rule but may see conflicting deal messages.',
						esc_html( $a['name'] ?? 'Rule A' ),
						esc_html( $b['name'] ?? 'Rule B' ),
						esc_html( implode( ', ', $role_overlap ) )
					),
					'rule_a'   => $a,
					'rule_b'   => $b,
					'severity' => 'low',
				);
			}
		}
	}
}

// 4. Scheduling conflicts — two scheduled rules with overlapping windows
$schedule_conflicts = array();
for ( $i = 0; $i < count( $rules ); $i++ ) {
	for ( $j = $i + 1; $j < count( $rules ); $j++ ) {
		$a       = $rules[ $i ];
		$b       = $rules[ $j ];
		$sched_a = $a['scheduling'] ?? array();
		$sched_b = $b['scheduling'] ?? array();
		if ( is_string( $sched_a ) ) {
			$sched_a = json_decode( $sched_a, true ) ?: array();
		}
		if ( is_string( $sched_b ) ) {
			$sched_b = json_decode( $sched_b, true ) ?: array();
		}
		$a_start = strtotime( $sched_a['start_date'] ?? '' );
		$a_end   = strtotime( $sched_a['end_date'] ?? '' );
		$b_start = strtotime( $sched_b['start_date'] ?? '' );
		$b_end   = strtotime( $sched_b['end_date'] ?? '' );
		if ( $a_start && $a_end && $b_start && $b_end ) {
			// Check overlap
			if ( $a_start < $b_end && $a_end > $b_start ) {
				$disc_a = floatval( $a['discount_value'] ?? 0 );
				$disc_b = floatval( $b['discount_value'] ?? 0 );
				if ( abs( $disc_a - $disc_b ) > 0.01 ) {
					$schedule_conflicts[] = array(
						'type'     => 'schedule_overlap',
						'label'    => 'Scheduled Rules Overlap — Competing Discounts in Same Window',
						'desc'     => sprintf(
							'Rules "%s" (%s%% off) and "%s" (%s%% off) have overlapping schedules. During the overlap window, both are active and the priority determines which fires — but customers may see both advertised.',
							esc_html( $a['name'] ?? 'Rule A' ),
							$disc_a,
							esc_html( $b['name'] ?? 'Rule B' ),
							$disc_b
						),
						'rule_a'   => $a,
						'rule_b'   => $b,
						'severity' => 'medium',
					);
				}
			}
		}
	}
}

$all_conflicts    = array_merge( $priority_conflicts, $discount_conflicts, $segment_conflicts, $schedule_conflicts );
$high_conflicts   = array_filter( $all_conflicts, fn( $c ) => $c['severity'] === 'high' );
$medium_conflicts = array_filter( $all_conflicts, fn( $c ) => $c['severity'] === 'medium' );
$low_conflicts    = array_filter( $all_conflicts, fn( $c ) => $c['severity'] === 'low' );

require_once __DIR__ . '/../ui-system/wrapper-start.php';

$conflict_badge_class = count( $high_conflicts ) > 0 ? 'gt-badge-error' : ( count( $medium_conflicts ) > 0 ? 'gt-badge-warn' : 'gt-badge-active' );
$conflict_label       = count( $all_conflicts ) > 0
	? count( $all_conflicts ) . ' Conflict' . ( count( $all_conflicts ) > 1 ? 's' : '' )
	: '✓ No Conflicts';
?>
<div class="gt-page-header gt-animate-in">
	<div>
		<h1 class="gt-page-title">⚔️ Conflict Resolver</h1>
		<p class="gt-page-subtitle">Priority clashes, discount conflicts, scope overlaps, and segment targeting issues</p>
	</div>
	<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
		<span class="gt-badge <?php echo esc_attr( $conflict_badge_class ); ?>"><?php echo esc_html( $conflict_label ); ?></span>
		<?php if ( count( $high_conflicts ) > 0 ) : ?>
		<span class="gt-badge" style="background:rgba(220,38,38,0.15);color:#f87171;border:1px solid rgba(220,38,38,0.3)"><?php echo esc_html( count( $high_conflicts ) ); ?> High</span>
		<?php endif; ?>
		<?php if ( count( $medium_conflicts ) > 0 ) : ?>
		<span class="gt-badge" style="background:rgba(245,158,11,0.15);color:#fcd34d;border:1px solid rgba(245,158,11,0.3)"><?php echo esc_html( count( $medium_conflicts ) ); ?> Medium</span>
		<?php endif; ?>
		<?php if ( count( $low_conflicts ) > 0 ) : ?>
		<span class="gt-badge" style="background:rgba(148,163,184,0.15);color:#94a3b8;border:1px solid rgba(148,163,184,0.3)"><?php echo esc_html( count( $low_conflicts ) ); ?> Low</span>
		<?php endif; ?>
	</div>
</div>

<?php if ( $message ) : ?>
<div class="gt-notice gt-notice-<?php echo esc_attr( $message_type ); ?> gt-animate-in"><?php echo esc_html( $message ); ?></div>
<?php endif; ?>

<?php if ( ! $is_pro ) : ?>
<div class="gt-pro-gate gt-animate-in">
	<span class="gt-pro-gate-icon">⚔️</span>
	<h2><?php esc_html_e( 'PRO License Required', 'gt-bogo-engine' ); ?></h2>
	<p><?php esc_html_e( 'The Conflict Resolver detects priority clashes, discount conflicts, and customer targeting overlaps across all your active rules.', 'gt-bogo-engine' ); ?></p>
	<div class="gt-flex" style="justify-content:center">
		<a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" class="gt-btn gt-btn-primary">Purchase PRO</a>
	</div>
</div>

<?php elseif ( empty( $rules ) ) : ?>
<div class="gt-card gt-animate-in" style="text-align:center;padding:48px 24px">
	<div style="font-size:48px;margin-bottom:16px">📋</div>
	<h3 style="color:var(--gt-white);margin:0 0 8px"><?php esc_html_e( 'No Active Rules', 'gt-bogo-engine' ); ?></h3>
	<p class="gt-text-soft" style="font-size:13px"><?php esc_html_e( 'Import and activate Pro Pack rules to check for conflicts.', 'gt-bogo-engine' ); ?></p>
	<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=pro-rules' ) ); ?>" class="gt-btn gt-btn-primary" style="margin-top:16px"><?php esc_html_e( 'Go to Pro Rules', 'gt-bogo-engine' ); ?></a>
</div>

<?php else : ?>

	<?php if ( empty( $all_conflicts ) ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px;border-color:rgba(34,197,94,0.3)">
	<div style="text-align:center;padding:32px">
		<div style="font-size:48px;margin-bottom:12px">✅</div>
		<h3 style="color:var(--gt-white);margin:0 0 8px"><?php esc_html_e( 'No Conflicts Detected', 'gt-bogo-engine' ); ?></h3>
		<p class="gt-text-soft" style="font-size:13px"><?php esc_html_e( 'All active rules have unique priorities and no overlapping discount conflicts. Your stack is clean.', 'gt-bogo-engine' ); ?></p>
	</div>
</div>
<?php endif; ?>

	<?php
	// Render each conflict group
	$groups = array(
		array( 'High Severity — Fix Immediately', $priority_conflicts, 'rgba(220,38,38,0.06)', 'rgba(220,38,38,0.2)', '#f87171', '🚨' ),
		array( 'Medium Severity — Review Recommended', $discount_conflicts, 'rgba(245,158,11,0.06)', 'rgba(245,158,11,0.2)', '#fcd34d', '⚠️' ),
		array( 'Medium Severity — Scheduling', $schedule_conflicts, 'rgba(245,158,11,0.04)', 'rgba(245,158,11,0.15)', '#fbbf24', '📅' ),
		array( 'Low Severity — Informational', array_merge( $segment_conflicts ), 'rgba(148,163,184,0.04)', 'rgba(148,163,184,0.15)', '#94a3b8', 'ℹ️' ),
	);
	foreach ( $groups as [$group_label, $group_items, $bg, $border_c, $color, $icon] ) :
		if ( empty( $group_items ) ) {
			continue;
		}
		?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px;background:<?php echo esc_html( $bg ); ?>;border-color:<?php echo esc_html( $border_c ); ?>">
	<div class="gt-card-header">
		<h2 class="gt-card-title"><?php echo esc_html( $icon ); ?> <?php echo esc_html( $group_label ); ?></h2>
		<span class="gt-badge" style="background:<?php echo esc_html( $bg ); ?>;color:<?php echo esc_html( $color ); ?>;border-color:<?php echo esc_html( $border_c ); ?>"><?php echo esc_html( count( $group_items ) ); ?></span>
	</div>
		<?php
		foreach ( $group_items as $conflict ) :
			$rule_a = $conflict['rule_a'];
			$rule_b = $conflict['rule_b'];
			$disc_a = ( $rule_a['discount_type'] === 'percentage' || $rule_a['discount_type'] === 'percent' ) ? floatval( $rule_a['discount_value'] ) . '%' : '$' . number_format( floatval( $rule_a['discount_value'] ), 2 );
			$disc_b = ( $rule_b['discount_type'] === 'percentage' || $rule_b['discount_type'] === 'percent' ) ? floatval( $rule_b['discount_value'] ) . '%' : '$' . number_format( floatval( $rule_b['discount_value'] ), 2 );
			?>
	<div style="padding:16px;margin:0 0 12px;border-radius:8px;background:rgba(255,255,255,0.02);border:1px solid <?php echo esc_html( $border_c ); ?>">
		<p style="font-size:13px;font-weight:700;color:<?php echo esc_html( $color ); ?>;margin:0 0 10px;text-transform:uppercase;letter-spacing:.6px"><?php echo esc_html( $conflict['label'] ); ?></p>
		<p style="font-size:13px;color:var(--gt-subtle);margin:0 0 14px;line-height:1.6"><?php echo esc_html( $conflict['desc'] ); ?></p>

		<!-- Rule pair display -->
		<div style="display:grid;grid-template-columns:1fr auto 1fr;gap:12px;align-items:center;margin-bottom:14px">
			<div style="padding:12px;background:rgba(255,255,255,0.03);border-radius:6px;border:1px solid var(--gt-border)">
				<div style="font-size:13px;color:var(--gt-subtle);margin-bottom:4px;text-transform:uppercase">Rule A · Priority <?php echo intval( $rule_a['priority'] ?? 0 ); ?></div>
				<div style="font-weight:700;color:var(--gt-white);margin-bottom:4px"><?php echo esc_html( $rule_a['name'] ?? 'Unnamed' ); ?></div>
				<div style="font-size:13px;color:var(--gt-soft)">Buy <?php echo intval( $rule_a['buy_quantity'] ?? 1 ); ?> Get <?php echo intval( $rule_a['get_quantity'] ?? 1 ); ?> · <?php echo esc_html( $disc_a ); ?></div>
				<?php if ( ! empty( $rule_a['pack_source'] ) ) : ?>
				<div style="font-size:13px;color:var(--gt-subtle);margin-top:4px">Pack: <?php echo esc_html( $rule_a['pack_source'] ); ?></div>
				<?php endif; ?>
			</div>
			<div style="text-align:center;font-size:20px;color:<?php echo esc_html( $color ); ?>">⚔️</div>
			<div style="padding:12px;background:rgba(255,255,255,0.03);border-radius:6px;border:1px solid var(--gt-border)">
				<div style="font-size:13px;color:var(--gt-subtle);margin-bottom:4px;text-transform:uppercase">Rule B · Priority <?php echo intval( $rule_b['priority'] ?? 0 ); ?></div>
				<div style="font-weight:700;color:var(--gt-white);margin-bottom:4px"><?php echo esc_html( $rule_b['name'] ?? 'Unnamed' ); ?></div>
				<div style="font-size:13px;color:var(--gt-soft)">Buy <?php echo intval( $rule_b['buy_quantity'] ?? 1 ); ?> Get <?php echo intval( $rule_b['get_quantity'] ?? 1 ); ?> · <?php echo esc_html( $disc_b ); ?></div>
				<?php if ( ! empty( $rule_b['pack_source'] ) ) : ?>
				<div style="font-size:13px;color:var(--gt-subtle);margin-top:4px">Pack: <?php echo esc_html( $rule_b['pack_source'] ); ?></div>
				<?php endif; ?>
			</div>
		</div>

		<!-- Resolution actions -->
		<div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
			<span style="font-size:13px;font-weight:600;color:var(--gt-soft)">Resolve:</span>
			<?php if ( $conflict['type'] === 'priority' ) : ?>
			<form method="post" style="display:inline-flex;align-items:center;gap:6px">
				<?php wp_nonce_field( 'gtbogo_fix_priority' ); ?>
				<input type="hidden" name="fix_rule_id" value="<?php echo intval( $rule_b['id'] ); ?>">
				<input type="number" name="fix_priority" value="<?php echo intval( ( $rule_b['priority'] ?? 10 ) + 1 ); ?>" min="1" max="999" class="gt-input" style="width:70px;padding:5px 8px;font-size:13px" id="gtbogo_fix_priority" aria-label="Fix Priority">
				<button type="submit" name="gtbogo_fix_priority" class="gt-btn gt-btn-sm" style="background:rgba(245,158,11,0.15);border:1px solid rgba(245,158,11,0.4);color:#fcd34d">
					Set Rule B Priority
				</button>
			</form>
			<?php else : ?>
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=my-packs' ) ); ?>" class="gt-btn gt-btn-sm gt-btn-ghost">Manage in My Packs</a>
			<?php endif; ?>
			<form method="post" style="display:inline-flex">
				<?php wp_nonce_field( 'gtbogo_deactivate_rule' ); ?>
				<input type="hidden" name="deact_rule_id" value="<?php echo intval( $rule_b['id'] ); ?>">
				<button type="submit" name="gtbogo_deactivate_rule" class="gt-btn gt-btn-sm" style="background:rgba(220,38,38,0.08);color:#f87171;border:1px solid rgba(220,38,38,0.2)"
					onclick="return confirm('Deactivate rule B to resolve this conflict?')">
					Deactivate Rule B
				</button>
			</form>
		</div>
	</div>
		<?php endforeach; ?>
</div>
	<?php endforeach; ?>

<!-- Full Priority Map -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">📊 Full Priority Map</h2>
		<span class="gt-text-soft" style="font-size:13px"><?php echo esc_html( count( $rules ) ); ?> active rules · lower priority = fires first</span>
	</div>
	<div style="overflow-x:auto">
		<table class="gt-table" style="margin:0">
			<thead><tr>
				<th>Priority</th><th>Rule Name</th><th>Pack</th><th>Type</th>
				<th>Buy/Get</th><th>Discount</th><th>Scope</th><th>Customer</th><th>Status</th>
			</tr></thead>
			<tbody>
			<?php
			foreach ( $rules as $i => $rule ) :
				$has_conflict  = false;
				$conflict_type = '';
				foreach ( $all_conflicts as $c ) {
					if ( $c['rule_a']['id'] == $rule['id'] || $c['rule_b']['id'] == $rule['id'] ) {
						$has_conflict  = true;
						$conflict_type = $c['severity'];
						break;
					}
				}
				$severity_color = array(
					'high'   => '#f87171',
					'medium' => '#fcd34d',
					'low'    => '#94a3b8',
				)[ $conflict_type ] ?? '';
				$disc           = ( $rule['discount_type'] === 'percentage' || $rule['discount_type'] === 'percent' )
					? floatval( $rule['discount_value'] ) . '%' : '$' . number_format( floatval( $rule['discount_value'] ), 2 );
				$conditions     = is_string( $rule['conditions'] ?? '' ) ? ( json_decode( $rule['conditions'] ?? '{}', true ) ?: array() ) : ( $rule['conditions'] ?? array() );
				$ctype          = $conditions['customer_type'] ?? 'all';
				$roles          = implode( ',', array_slice( (array) ( $conditions['user_roles'] ?? array() ), 0, 2 ) );
				?>
			<tr style="<?php echo esc_html( $has_conflict ) ? 'background:rgba(245,158,11,0.03)' : ''; ?>">
				<td>
					<span style="font-family:monospace;font-weight:800;color:<?php echo $has_conflict ? esc_attr( $severity_color ) : 'var(--gt-red)'; ?>;font-size:14px">
						<?php echo intval( $rule['priority'] ?? 0 ); ?>
					</span>
				</td>
				<td><strong style="color:var(--gt-white)"><?php echo esc_html( $rule['name'] ?? '' ); ?></strong></td>
				<td style="color:var(--gt-subtle);font-size:13px"><?php echo esc_html( $rule['pack_source'] ?? '—' ); ?></td>
				<td><span style="font-size:13px;background:rgba(59,130,246,0.1);border:1px solid rgba(59,130,246,0.2);color:#93c5fd;padding:2px 8px;border-radius:20px"><?php echo esc_html( strtoupper( $rule['type'] ?? 'bogo' ) ); ?></span></td>
				<td style="font-family:monospace;color:var(--gt-white)"><?php echo intval( $rule['buy_quantity'] ?? 1 ); ?>→<?php echo intval( $rule['get_quantity'] ?? 1 ); ?></td>
				<td style="font-weight:700;color:var(--gt-white)"><?php echo esc_html( $disc ); ?></td>
				<td style="font-size:13px;color:var(--gt-soft)"><?php echo esc_html( $rule['scope'] ?? 'global' ); ?></td>
				<td style="font-size:13px;color:var(--gt-soft)"><?php echo esc_html( $ctype . ( $roles ? ' ·' . $roles : '' ) ); ?></td>
				<td>
					<?php if ( $has_conflict ) : ?>
					<span style="font-size:13px;font-weight:700;padding:2px 8px;border-radius:20px;background:rgba(245,158,11,0.1);border:1px solid rgba(245,158,11,0.3);color:#fcd34d;white-space:nowrap">
						⚠ <?php echo esc_html( ucfirst( $conflict_type ) ); ?>
					</span>
					<?php else : ?>
					<span style="font-size:13px;font-weight:700;padding:2px 8px;border-radius:20px;background:rgba(34,197,94,0.1);border:1px solid rgba(34,197,94,0.3);color:#86efac">✓ Clean</span>
					<?php endif; ?>
				</td>
			</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
	</div>
</div>

<!-- Guide -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px;border-color:rgba(59,130,246,0.15)">
	<div class="gt-card-header"><h2 class="gt-card-title">💡 Conflict Resolution Guide</h2></div>
	<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:12px;padding:0 0 4px">
		<?php
		foreach ( array(
			array( '🚨 Priority Conflict', 'Two rules with identical priority numbers compete unpredictably. Fix by assigning unique priority numbers. Use the 10-gap convention — set priorities in multiples of 10 to leave room for insertion.' ),
			array( '💰 Discount Conflict', 'Two global-scope rules offering different discounts on the same products. The higher-priority rule fires at cart but product pages may display the rate from either rule. Resolve by scoping one rule or deactivating one.' ),
			array( '📅 Schedule Overlap', 'Two scheduled rules with overlapping date windows both become active during the overlap. Resolve by adjusting end_date on the first rule to end before the second starts, or by increasing the priority gap.' ),
			array( '👤 Segment Conflict', 'Two rules targeting the same customer segment with different rates. Customers with the qualifying role or type receive only the highest-priority deal but may see both advertised. Resolve by deactivating or merging the lower rule.' ),
		) as [$title, $desc] ) :
			?>
		<div style="background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:8px;padding:16px">
			<div style="font-weight:700;color:var(--gt-white);margin-bottom:6px;font-size:14px"><?php echo esc_html( $title ); ?></div>
			<p style="font-size:13px;color:var(--gt-subtle);line-height:1.65;margin:0"><?php echo esc_html( $desc ); ?></p>
		</div>
		<?php endforeach; ?>
	</div>
</div>

<?php endif; ?>
<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>
