<?php
/**
 * GT BOGO Engine — Customer Journey Map
 * Visualises all active deal touchpoints across the customer purchase journey.
 * Shows which superpowers and rules fire at each stage.
 *
 * @package GT_BOGO_Engine
 * @since   3.11.0
 */
if ( ! defined( 'ABSPATH' ) ) exit;
if ( ! current_user_can( 'manage_options' ) ) return;

global $wpdb;
$rtbl = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->prefix . 'gtbogo_rules' ) );
if ( ! $rtbl ) {
    echo '<div class="gt-notice gt-notice-warn">Database tables not found. Please deactivate and reactivate the plugin.</div>';
    require_once __DIR__ . '/../ui-system/wrapper-end.php';
    return;
}

$active_rules = $wpdb->get_results(
    "SELECT * FROM {$wpdb->prefix}gtbogo_rules WHERE status='active' ORDER BY priority ASC",
    ARRAY_A
) ?: [];

$active_sp = [];
$sp_ids = [
    'progress_bar','announcement_bar','badge_generator','bundle_spotlight',
    'cart_recommendations','countdown_timer','deal_share','dynamic_pricing',
    'email_notifications','exit_intent','quick_add','savings_calculator',
    'smart_popup','social_proof','abandon_nudge','scarcity_bar','deal_unlock',
    'mobile_drawer','loyalty_widget','vip_badge','geo_banner','savings_history',
    'bundle_configurator','deal_comparison','referral_widget',
];
foreach ( $sp_ids as $id ) {
    if ( get_option( 'gtbogo_sp_' . esc_html( $id ) . '_enabled', 0 ) ) {
        $active_sp[] = $id;
    }
}

// Journey stages — each maps to superpowers and rule types that fire there
$stages = [
    [
        'id'     => 'discovery',
        'label'  => 'Discovery',
        'icon'   => '🔍',
        'desc'   => 'Customer arrives on the store — social, search, direct, referral',
        'sp'     => ['announcement_bar','geo_banner','mobile_drawer'],
        'rules'  => [],
        'emails' => ['Flash Sale Alert — drives customer to visit'],
        'color'  => '#6366f1',
    ],
    [
        'id'     => 'browsing',
        'label'  => 'Product Browsing',
        'icon'   => '🛍️',
        'desc'   => 'Customer browses shop, category, and product listing pages',
        'sp'     => ['badge_generator','dynamic_pricing','deal_comparison','social_proof','vip_badge','countdown_timer','quick_add','scarcity_bar'],
        'rules'  => ['badge_rules','display_rules','urgency_rules'],
        'emails' => [],
        'color'  => '#8b5cf6',
    ],
    [
        'id'     => 'product',
        'label'  => 'Product Page',
        'icon'   => '📦',
        'desc'   => 'Customer views a single product — decision point',
        'sp'     => ['savings_calculator','deal_comparison','bundle_spotlight','bundle_configurator','social_proof','scarcity_bar','countdown_timer','deal_share','vip_badge'],
        'rules'  => ['product_specific_rules','cross_sell_rules'],
        'emails' => [],
        'color'  => '#ec4899',
    ],
    [
        'id'     => 'cart',
        'label'  => 'Cart',
        'icon'   => '🛒',
        'desc'   => 'Customer reviews cart — highest-leverage conversion point',
        'sp'     => ['progress_bar','savings_calculator','cart_recommendations','loyalty_widget','savings_history','deal_unlock','deal_share','countdown_timer'],
        'rules'  => ['threshold_rules','quantity_rules','all_active_deals'],
        'emails' => ['Threshold Nudge — within $15 of deal unlock','Cart Abandonment — fires after idle window'],
        'color'  => '#f59e0b',
    ],
    [
        'id'     => 'checkout',
        'label'  => 'Checkout',
        'icon'   => '💳',
        'desc'   => 'Customer enters payment — deal must be confirmed and visible',
        'sp'     => ['progress_bar','savings_calculator','loyalty_widget'],
        'rules'  => ['all_active_deals'],
        'emails' => [],
        'color'  => '#10b981',
    ],
    [
        'id'     => 'confirmation',
        'label'  => 'Order Complete',
        'icon'   => '✅',
        'desc'   => 'Purchase confirmed — seed loyalty and referral',
        'sp'     => ['referral_widget','email_notifications','deal_unlock'],
        'rules'  => ['all_applied_deals'],
        'emails' => ['BOGO Deal Confirmation','Free Gift Notification','VIP Tier Unlocked','Streak Milestone Bonus'],
        'color'  => '#22c55e',
    ],
    [
        'id'     => 'retention',
        'label'  => 'Post-Purchase',
        'icon'   => '🔄',
        'desc'   => 'Drive repeat purchase, loyalty tier progression, and referrals',
        'sp'     => ['loyalty_widget','savings_history','referral_widget'],
        'rules'  => ['loyalty_rules','winback_rules','referral_rules'],
        'emails' => ['Deal Expiry Warning','Win-Back Campaign','Referral Progress Update','Birthday Deal','Tier Upgrade'],
        'color'  => '#e10000',
    ],
];

$sp_labels = [
    'progress_bar'=>'Cart Progress Bar','announcement_bar'=>'Announcement Bar',
    'badge_generator'=>'Badge Generator','bundle_spotlight'=>'Bundle Spotlight',
    'cart_recommendations'=>'Cart Recommendations','countdown_timer'=>'Countdown Timer',
    'deal_share'=>'Deal Share Button','dynamic_pricing'=>'Dynamic Pricing',
    'email_notifications'=>'Email Notifications','exit_intent'=>'Exit Intent Popup',
    'quick_add'=>'Quick Add Button','savings_calculator'=>'Savings Calculator',
    'smart_popup'=>'Smart Popup','social_proof'=>'Social Proof',
    'abandon_nudge'=>'Abandonment Nudge','scarcity_bar'=>'Scarcity Bar',
    'deal_unlock'=>'Deal Unlock Animation','mobile_drawer'=>'Mobile Drawer',
    'loyalty_widget'=>'Loyalty Widget','vip_badge'=>'VIP Badge',
    'geo_banner'=>'Geo Banner','savings_history'=>'Savings History',
    'bundle_configurator'=>'Bundle Configurator','deal_comparison'=>'Deal Comparison',
    'referral_widget'=>'Referral Widget',
];

require_once __DIR__ . '/../ui-system/wrapper-start.php';
$gt_journey_nonce = wp_create_nonce('gt_bogo_nonce');
?>
<div class="gt-page-header gt-animate-in">
    <div>
        <h1 class="gt-page-title">🗺️ Customer Journey Map</h1>
        <p class="gt-page-subtitle">Every deal touchpoint your customers experience from discovery to retention</p>
    </div>
    <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap">
        <span class="gt-badge gt-badge-active"><?php echo esc_html( count($active_rules) ); ?> <?php esc_html_e('active rules','gt-bogo-engine'); ?></span>
        <span class="gt-badge gt-badge-active"><?php echo esc_html( count($active_sp) ); ?>/25 <?php esc_html_e('superpowers on','gt-bogo-engine'); ?></span>
        <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=superpowers')); ?>" class="gt-btn gt-btn-ghost gt-btn-sm">
            ⚡ <?php esc_html_e('Configure Superpowers','gt-bogo-engine'); ?>
        </a>
    </div>
</div>

<?php if ( empty($active_rules) && empty($active_sp) ) : ?>
<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 Deals or Superpowers','gt-bogo-engine'); ?></h3>
    <p class="gt-text-soft" style="font-size:13px" style="margin-bottom:24px"><?php esc_html_e('Activate rules and superpowers to see your customer journey map.','gt-bogo-engine'); ?></p>
    <div style="display:flex;gap:12px;justify-content:center;flex-wrap:wrap">
        <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=pro-rules')); ?>" class="gt-btn gt-btn-primary"><?php esc_html_e('Activate Rules','gt-bogo-engine'); ?></a>
        <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=superpowers')); ?>" class="gt-btn gt-btn-ghost"><?php esc_html_e('Enable Superpowers','gt-bogo-engine'); ?></a>
    </div>
</div>
<?php else : ?>

<!-- Journey progress indicator -->
<div class="gt-card gt-animate-in" style="margin-bottom:24px;padding:24px">
    <div style="display:flex;align-items:center;gap:0;overflow-x:auto;padding-bottom:4px">
        <?php foreach ( $stages as $si => $stage ) :
            $sp_active_here = array_intersect( $stage['sp'], $active_sp );
            $has_activity   = ! empty( $sp_active_here ) || ! empty( $stage['emails'] );
            $is_last = $si === count($stages) - 1;
        ?>
        <div style="display:flex;align-items:center;flex-shrink:0">
            <div style="display:flex;flex-direction:column;align-items:center;gap:6px;min-width:80px">
                <div style="width:44px;height:44px;border-radius:50%;background:<?php echo $has_activity ? esc_attr( $stage['color'] ) : 'rgba(255,255,255,0.06)'; ?>;display:flex;align-items:center;justify-content:center;font-size:18px;border:2px solid <?php echo $has_activity ? esc_attr( $stage['color'] ) : 'rgba(255,255,255,0.1)'; ?>;transition:all .3s">
                    <?php echo esc_html( $stage['icon'] ); ?>
                </div>
                <span style="font-size:13px;font-weight:600;color:<?php echo esc_html( $has_activity ) ? 'var(--gt-white)' : 'var(--gt-subtle)'; ?>;text-align:center;white-space:nowrap"><?php echo esc_html($stage['label']); ?></span>
                <?php if ($has_activity) : ?>
                <span style="font-size:13px;color:<?php echo esc_attr($stage['color']); ?>;font-weight:700"><?php echo esc_html( count($sp_active_here) ); ?> active</span>
                <?php endif; ?>
            </div>
            <?php if (!$is_last) : ?>
            <div style="width:32px;height:2px;background:rgba(255,255,255,0.08);margin:0 2px;margin-bottom:20px;flex-shrink:0"></div>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- Stage cards -->
<?php foreach ( $stages as $stage ) :
    $sp_active_here    = array_intersect( $stage['sp'], $active_sp );
    $sp_inactive_here  = array_diff( $stage['sp'], $active_sp );
    $has_rules         = ! empty( $active_rules );
    $stage_has_emails  = ! empty( $stage['emails'] );
    $email_enabled     = get_option( 'gtbogo_customer_emails_enabled', false );
?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px;border-top:3px solid <?php echo esc_attr($stage['color']); ?>">
    <div class="gt-card-header" style="padding-bottom:16px;border-bottom:1px solid var(--gt-border)">
        <div style="display:flex;align-items:center;gap:12px">
            <span style="font-size:26px"><?php echo esc_html( $stage['icon'] ); ?></span>
            <div>
                <h2 class="gt-card-title" style="margin:0 0 4px"><?php echo esc_html($stage['label']); ?></h2>
                <p style="margin:0;font-size:13px;color:var(--gt-subtle)"><?php echo esc_html($stage['desc']); ?></p>
            </div>
        </div>
        <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
            <?php if (!empty($sp_active_here)) : ?>
            <span class="gt-badge gt-badge-active"><?php echo esc_html( count($sp_active_here) ); ?> superpower<?php echo count($sp_active_here)>1?'s':''; ?> active</span>
            <?php endif; ?>
            <?php if ($stage_has_emails && $email_enabled) : ?>
            <span class="gt-badge" style="background:rgba(59,130,246,0.15);color:#93c5fd;border:1px solid rgba(59,130,246,0.3)"><?php echo esc_html( count($stage['emails']) ); ?> email<?php echo count($stage['emails'])>1?'s':''; ?></span>
            <?php elseif ($stage_has_emails && !$email_enabled) : ?>
            <span class="gt-badge gt-badge-free">Emails off</span>
            <?php endif; ?>
        </div>
    </div>

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;padding:20px">

        <!-- Active Superpowers -->
        <div>
            <p style="margin:0 0 12px;font-size:13px;font-weight:700;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.8px">Active Superpowers</p>
            <?php if (!empty($sp_active_here)) : ?>
            <div style="display:flex;flex-direction:column;gap:6px">
                <?php foreach ($sp_active_here as $sp_id) :
                    $intensity = get_option('gtbogo_sp_'.$sp_id.'_intensity','subtle');
                    $anim      = get_option('gtbogo_sp_'.$sp_id.'_anim',0);
                ?>
                <div style="display:flex;align-items:center;justify-content:space-between;padding:8px 12px;background:rgba(34,197,94,0.06);border:1px solid rgba(34,197,94,0.2);border-radius:6px">
                    <span style="font-size:13px;font-weight:600;color:var(--gt-white)"><?php echo esc_html($sp_labels[$sp_id] ?? $sp_id); ?></span>
                    <div style="display:flex;gap:6px;align-items:center">
                        <span style="font-size:13px;color:#4ade80;font-weight:600"><?php echo esc_html(ucfirst($intensity)); ?></span>
                        <?php if ($anim) : ?><span style="font-size:13px;color:var(--gt-subtle)">✨ Animated</span><?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php else : ?>
            <p style="color:var(--gt-subtle);font-size:13px;margin:0">No superpowers active at this stage.</p>
            <?php endif; ?>

            <?php if (!empty($sp_inactive_here)) : ?>
            <p style="margin:12px 0 8px;font-size:13px;font-weight:700;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.8px">Available but Inactive</p>
            <div style="display:flex;flex-direction:column;gap:4px">
                <?php foreach ($sp_inactive_here as $sp_id) : ?>
                <div style="display:flex;align-items:center;justify-content:space-between;padding:6px 12px;background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:6px;opacity:0.6">
                    <span style="font-size:13px;color:var(--gt-soft)"><?php echo esc_html($sp_labels[$sp_id] ?? $sp_id); ?></span>
                    <label class="gt-toggle" style="transform:scale(0.85);transform-origin:right center" title="Enable <?php echo esc_attr($sp_labels[$sp_id] ?? $sp_id); ?>">
                        <input type="checkbox" data-sp="<?php echo esc_attr($sp_id); ?>" onchange="gtJourneyToggleSP(this)">
                        <span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span>
                    </label>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>

        <!-- Emails + Rules -->
        <div>
            <!-- Email triggers -->
            <?php if ($stage_has_emails) : ?>
            <p style="margin:0 0 12px;font-size:13px;font-weight:700;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.8px">Email Triggers</p>
            <div style="display:flex;flex-direction:column;gap:6px;margin-bottom:16px">
                <?php foreach ($stage['emails'] as $email_label) : ?>
                <div style="display:flex;align-items:center;gap:8px;padding:8px 12px;background:<?php echo esc_html( $email_enabled ) ? 'rgba(59,130,246,0.06)' : 'rgba(255,255,255,0.02)'; ?>;border:1px solid <?php echo esc_html( $email_enabled ) ? 'rgba(59,130,246,0.2)' : 'var(--gt-border)'; ?>;border-radius:6px;opacity:<?php echo esc_html( $email_enabled ) ? '1' : '0.5'; ?>">
                    <span style="font-size:14px"><?php echo esc_html( $email_enabled ) ? '📧' : '🔇'; ?></span>
                    <span style="font-size:13px;color:<?php echo esc_html( $email_enabled ) ? 'var(--gt-white)' : 'var(--gt-subtle)'; ?>"><?php echo esc_html($email_label); ?></span>
                </div>
                <?php endforeach; ?>
                <?php if (!$email_enabled) : ?>
                <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=settings')); ?>" style="font-size:13px;color:var(--gt-red);display:block;margin-top:4px">Enable Customer Emails in Settings →</a>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <!-- Active rules at this stage -->
            <?php if ($has_rules && !empty($stage['rules'])) : ?>
            <p style="margin:0 0 12px;font-size:13px;font-weight:700;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.8px">Active Deal Rules</p>
            <div style="display:flex;flex-direction:column;gap:4px">
                <?php
                $shown = 0;
                foreach ($active_rules as $r) :
                    if ($shown >= 5) break;
                    $disc = ($r['discount_type']==='percentage'||$r['discount_type']==='percent')
                          ? floatval($r['discount_value']).'%' : '$'.number_format(floatval($r['discount_value']),2);
                    $shown++;
                ?>
                <div style="padding:6px 12px;background:rgba(225,0,0,0.05);border:1px solid rgba(225,0,0,0.15);border-radius:5px;display:flex;justify-content:space-between;align-items:center">
                    <span style="font-size:13px;color:var(--gt-white);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:160px"><?php echo esc_html($r['name']); ?></span>
                    <span style="font-size:13px;color:var(--gt-red);font-weight:700;flex-shrink:0;margin-left:8px"><?php echo esc_html($r['buy_quantity']); ?>→<?php echo esc_html($r['get_quantity']); ?> <?php echo esc_html($disc); ?></span>
                </div>
                <?php endforeach; ?>
                <?php if (count($active_rules) > 5) : ?>
                <span style="font-size:13px;color:var(--gt-subtle);padding:4px 12px">+<?php echo count($active_rules)-5; ?> more active rules</span>
                <?php endif; ?>
            </div>
            <?php elseif (empty($active_rules)) : ?>
            <div style="padding:12px;background:rgba(255,255,255,0.02);border-radius:6px;border:1px solid var(--gt-border)">
                <p style="margin:0;font-size:13px;color:var(--gt-subtle)">No active deal rules. <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=pro-rules')); ?>" style="color:var(--gt-red)">Activate rules →</a></p>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php endforeach; ?>

<!-- Coverage summary -->
<div class="gt-card gt-animate-in" style="margin-bottom:24px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">📋 Journey Coverage Summary</h2>
    </div>
    <div style="padding:20px;display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:16px">
        <?php
        $stats = [
            ['Active Rules',    count($active_rules),  'var(--gt-red)'],
            ['Active Superpowers', count($active_sp),  '#22c55e'],
            ['Email Triggers', $email_enabled ? 14 : 0, '#93c5fd'],
            ['Journey Stages', 7,                       '#f59e0b'],
            ['Stages Covered', count(array_filter($stages, function($s) use ($active_sp) { return !empty(array_intersect($s['sp'],$active_sp)); })), '#8b5cf6'],
        ];
        foreach ($stats as [$label,$val,$color]) : ?>
        <div style="text-align:center;padding:16px;background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:8px">
            <div style="font-size:28px;font-weight:900;color:<?php echo esc_html( $color ); ?>;line-height:1;margin-bottom:6px"><?php echo esc_html( $val ); ?></div>
            <div style="font-size:13px;color:var(--gt-subtle);font-weight:600;text-transform:uppercase;letter-spacing:.6px"><?php echo esc_html($label); ?></div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<?php endif; ?>


<script>
function gtJourneyToggleSP(checkbox) {
    var sp  = checkbox.dataset.sp;
    var row = checkbox.closest('div[style*="justify-content:space-between"]');
    if (!row) return;
    checkbox.disabled = true;
    var data = new FormData();
    data.append('action',  'gt_bogo_toggle_superpower');
    data.append('nonce',   '<?php echo esc_js(wp_create_nonce("gt_bogo_sp_toggle")); ?>');
    data.append('sp_id',   sp);
    data.append('enabled', checkbox.checked ? '1' : '0');
    fetch('<?php echo esc_js(admin_url("admin-ajax.php")); ?>', {
        method: 'POST', body: data, credentials: 'same-origin'
    })
    .then(function(r){ return r.json(); })
    .then(function(res) {
        if (res.success) {
            if (window.gtBogoSPBroadcast) gtBogoSPBroadcast(sp, checkbox.checked);
            row.style.opacity = checkbox.checked ? '1' : '0.6';
        } else {
            checkbox.checked = !checkbox.checked;
            alert(res.data ? res.data.message : 'Failed to update.');
        }
        checkbox.disabled = false;
    })
    .catch(function() { checkbox.checked = !checkbox.checked; checkbox.disabled = false; });
}
</script>


<script>
(function(){
    var _pollInterval = 30000;
    var _tabName = 'customer-journey';
    function gtbPollRefresh() {
        if (window.location.href.indexOf('tab=' + _tabName) === -1) return;
        var wrap = document.querySelector('.gt-admin-content-wrap, #wpbody-content, .wrap');
        if (!wrap) return;
        fetch(window.location.href, {credentials:'same-origin'})
            .then(function(r){ return r.text(); })
            .then(function(html){
                var doc2 = new DOMParser().parseFromString(html,'text/html');
                var nc = doc2.querySelector('.gt-admin-content-wrap, #wpbody-content .gt-card');
                // Selective update — only refresh KPI numbers, not whole page
                var kpis = document.querySelectorAll('[data-live]');
                var kpis2 = doc2.querySelectorAll('[data-live]');
                kpis.forEach(function(el, i){ if(kpis2[i]) el.textContent = kpis2[i].textContent; });
            }).catch(function(){});
    }
    if (document.querySelector('[data-live]')) {
        setInterval(gtbPollRefresh, _pollInterval);
    }
})();
</script>
<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>
