<?php
/**
 * GT BOGO Engine — Conflict Resolver
 * @package GT_BOGO_Engine
 * @since   3.10.1
 */
if (!defined('ABSPATH')) exit;
if (!current_user_can('manage_options')) return;

$is_pro = function_exists('gt_bogo_has_pro') ? gt_bogo_has_pro() : false;

global $wpdb;
$message = ''; $message_type = 'success';
$table_exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->prefix . 'gtbogo_rules'));
$rules = $table_exists ? $wpdb->get_results("SELECT * FROM {$wpdb->prefix}gtbogo_rules WHERE status='active' ORDER BY priority ASC") : [];

// 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', ['priority' => $fix_pri], ['id' => $fix_id], ['%d'], ['%d']);
        delete_transient('gtbogo_active_rules');
        if (function_exists('gt_bogo_log')) gt_bogo_log('Conflict Resolver', 'Priority fixed for rule #'.$fix_id.' → '.$fix_pri, 'success');
        $message = 'Priority updated. Re-checking for conflicts.'; $message_type = 'success';
        // Reload rules
        $rules = $table_exists ? $wpdb->get_results("SELECT * FROM {$wpdb->prefix}gtbogo_rules WHERE status='active' ORDER BY priority ASC") : [];
    }
}

// Detect conflicts
$conflicts = [];
$priority_map = [];
foreach ($rules as $rule) {
    $p = intval($rule->priority ?? 0);
    if (isset($priority_map[$p])) {
        $conflicts[] = [$priority_map[$p], $rule];
    } else {
        $priority_map[$p] = $rule;
    }
}

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
    <div>
        <h1 class="gt-page-title">⚔️ Conflict Resolver</h1>
        <p class="gt-page-subtitle">Visual map of rule overlaps — see exactly what fires and why</p>
    </div>
    <span class="gt-badge <?php echo count($conflicts) > 0 ? 'gt-badge-warn' : 'gt-badge-active'; ?>">
        <?php echo count($conflicts) > 0 ? count($conflicts) . ' Conflict' . (count($conflicts)>1?'s':'') : '✓ No Conflicts'; ?>
    </span>
</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>PRO License Required</h2>
    <p>The Conflict Resolver shows you exactly when two rules compete for the same cart and which one wins.</p>
    <div class="gt-flex" style="justify-content:center;gap:12px">
        <a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" class="gt-btn gt-btn-primary">Purchase PRO</a>
    </div>
</div>
<?php else: ?>

<?php if (count($conflicts) > 0): ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px;background:linear-gradient(135deg,rgba(245,158,11,0.06),rgba(7,12,28,0));border-color:rgba(245,158,11,0.2)">
    <div class="gt-card-header">
        <h2 class="gt-card-title">⚠️ Active Conflicts</h2>
        <span class="gt-text-soft gt-text-sm">Rules sharing the same priority compete on every cart</span>
    </div>
    <?php foreach ($conflicts as $pair): ?>
    <div style="padding:16px;margin-bottom:12px;border-radius:10px;background:rgba(245,158,11,0.04);border:1px solid rgba(245,158,11,0.15)">
        <div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap">
            <div style="flex:1;padding:12px;background:rgba(255,255,255,0.03);border-radius:8px;border:1px solid var(--gt-border)">
                <div style="font-size:11px;color:var(--gt-subtle);margin-bottom:4px">RULE A — Priority <?php echo intval($pair[0]->priority??0); ?></div>
                <div style="font-weight:700;color:var(--gt-white)"><?php echo esc_html($pair[0]->name ?? 'Unnamed'); ?></div>
            </div>
            <div style="font-size:20px;color:rgba(245,158,11,0.8)">⚔️</div>
            <div style="flex:1;padding:12px;background:rgba(255,255,255,0.03);border-radius:8px;border:1px solid var(--gt-border)">
                <div style="font-size:11px;color:var(--gt-subtle);margin-bottom:4px">RULE B — Priority <?php echo intval($pair[1]->priority??0); ?></div>
                <div style="font-weight:700;color:var(--gt-white)"><?php echo esc_html($pair[1]->name ?? 'Unnamed'); ?></div>
            </div>
        </div>
        <div style="margin-top:10px;padding:10px 14px;background:rgba(245,158,11,0.06);border-radius:6px;display:flex;align-items:center;gap:16px;flex-wrap:wrap">
            <span style="font-size:12px;color:var(--gt-soft);flex:1">Fix: give one rule a unique priority</span>
            <form method="post" action="" style="display:flex;align-items:center;gap:8px;flex-wrap:wrap">
                <?php wp_nonce_field('gtbogo_fix_priority'); ?>
                <input type="hidden" name="fix_rule_id" value="<?php echo intval($pair[1]->id); ?>">
                <input type="number" name="fix_priority" value="<?php echo intval(($pair[1]->priority??10)+1); ?>"
                    min="1" max="999" class="gt-input" style="width:80px;padding:6px 8px;font-size:13px">
                <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;white-space:nowrap">
                    Set Priority for "<?php echo esc_html(substr($pair[1]->name??'Rule',0,20)); ?>"
                </button>
            </form>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php else: ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px;background:linear-gradient(135deg,rgba(34,197,94,0.06),rgba(7,12,28,0));border-color:rgba(34,197,94,0.2)">
    <div style="text-align:center;padding:24px">
        <div style="font-size:48px;margin-bottom:12px">✅</div>
        <h3 style="color:var(--gt-white);margin:0 0 8px">No Conflicts Detected</h3>
        <p class="gt-text-soft gt-text-sm">All active rules have unique priorities. Your stack is clean.</p>
    </div>
</div>
<?php endif; ?>

<!-- Rule Priority Map -->
<div class="gt-card gt-animate-in">
    <div class="gt-card-header">
        <h2 class="gt-card-title">📊 Rule Priority Map</h2>
        <span class="gt-text-soft gt-text-sm">Lower number = fires first</span>
    </div>
    <?php if ($rules): ?>
    <div style="display:flex;flex-direction:column;gap:8px">
        <?php foreach ($rules as $i => $rule):
            $has_conflict = false;
            foreach ($conflicts as $pair) {
                if ($pair[0]->id === $rule->id || $pair[1]->id === $rule->id) { $has_conflict = true; break; }
            }
        ?>
        <div style="display:flex;align-items:center;gap:16px;padding:12px 16px;border-radius:10px;background:rgba(255,255,255,0.02);border:1px solid <?php echo $has_conflict?'rgba(245,158,11,0.25)':' var(--gt-border)'; ?>">
            <div style="width:36px;height:36px;border-radius:50%;background:<?php echo $has_conflict?'rgba(245,158,11,0.15)':' rgba(225,0,0,0.1)'; ?>;border:2px solid <?php echo $has_conflict?'rgba(245,158,11,0.4)':' rgba(225,0,0,0.3)'; ?>;display:flex;align-items:center;justify-content:center;font-weight:800;color:<?php echo $has_conflict?'#fcd34d':' var(--gt-red)'; ?>;font-size:13px;flex-shrink:0">
                <?php echo intval($rule->priority ?? ($i+1)); ?>
            </div>
            <div style="flex:1">
                <div style="font-weight:600;color:var(--gt-white)"><?php echo esc_html($rule->name ?? 'Unnamed Rule'); ?></div>
                <div style="font-size:11px;color:var(--gt-soft)">
                    <?php
                    echo esc_html(strtoupper($rule->type ?? 'bogo'));
                    ?>
                </div>
            </div>
            <?php if ($has_conflict): ?>
            <span style="font-size:11px;font-weight:700;padding:3px 10px;border-radius:50px;background:rgba(245,158,11,0.1);border:1px solid rgba(245,158,11,0.3);color:#fcd34d">⚠ CONFLICT</span>
            <?php else: ?>
            <span style="font-size:11px;font-weight:700;padding:3px 10px;border-radius:50px;background:rgba(34,197,94,0.1);border:1px solid rgba(34,197,94,0.2);color:#86efac">✓ CLEAN</span>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>
    <?php else: ?>
    <div 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">No Active Rules</h3>
        <p class="gt-text-soft gt-text-sm">Import a PRO Pack to create rules, then check back here for conflicts.</p>
    </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<div class="gt-card gt-animate-in" style="margin-bottom:20px;background:linear-gradient(135deg,rgba(59,130,246,0.06),rgba(7,12,28,0));border-color:rgba(59,130,246,0.15)">
    <div class="gt-card-header"><h2 class="gt-card-title">💡 Priority Architecture Guide</h2><span class="gt-text-soft gt-text-sm">How to design a conflict-free rule stack</span></div>
    <div class="gt-feature-grid gt-feature-grid--2col" style="gap:12px">
        <div style="background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:10px;padding:16px">
            <div style="font-size:15px;font-weight:700;color:var(--gt-white);margin-bottom:8px">📐 The 10-Gap Convention</div>
            <p style="font-size:13px;color:var(--gt-soft);line-height:1.6;margin:0">Set rule priorities in multiples of 10 — 10, 20, 30, 40. This leaves room to insert new rules between existing ones without renumbering. Emergency deals get priority 5, permanent VIP rules get 15, flash sales get 25. The gaps let you act fast.</p>
        </div>
        <div style="background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:10px;padding:16px">
            <div style="font-size:15px;font-weight:700;color:var(--gt-white);margin-bottom:8px">⚔️ Intentional vs Accidental Conflicts</div>
            <p style="font-size:13px;color:var(--gt-soft);line-height:1.6;margin:0">If you want two rules covering the same products for A/B testing, use the A/B Testing page instead. Conflicts here represent unintended priority clashes that produce unpredictable behaviour for customers and waste cart evaluation cycles.</p>
        </div>
        <div style="background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:10px;padding:16px">
            <div style="font-size:15px;font-weight:700;color:var(--gt-white);margin-bottom:8px">🔄 Seasonal Rule Rotation</div>
            <p style="font-size:13px;color:var(--gt-soft);line-height:1.6;margin:0">Deactivate rules you are not currently running rather than deleting them. Inactive rules are excluded from the priority map but preserved for future campaigns. This prevents collisions when you re-activate a seasonal rule at the same priority as a newer permanent one.</p>
        </div>
        <div style="background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:10px;padding:16px">
            <div style="font-size:15px;font-weight:700;color:var(--gt-white);margin-bottom:8px">✅ Weekly Health Check</div>
            <p style="font-size:13px;color:var(--gt-soft);line-height:1.6;margin:0">Bookmark this page and check it every time you create or import a new rule. Conflicts left unresolved can result in the wrong deal firing on high-value carts, silently costing you margin every single day.</p>
        </div>
    </div>
</div>

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