<?php
/**
 * GT BOGO Engine — Superpowers Hub
 * Central control panel for all 25 superpowers.
 * Enable/disable, intensity, animation, and per-superpower config.
 *
 * @package GT_BOGO_Engine
 * @since   3.11.0
 */
if ( ! defined( 'ABSPATH' ) ) exit;
if ( ! current_user_can( 'manage_options' ) ) return;

$message = ''; $message_type = '';

// ── Save handler ──────────────────────────────────────────────────────────────
if ( isset( $_POST['gtbogo_sp_nonce'] ) && wp_verify_nonce( $_POST['gtbogo_sp_nonce'], 'gtbogo_sp_save' ) ) {
    $sp_ids = [
        'progress_bar','savings_calc','dynamic_pricing','email_notif',
        'bundle_configurator','cart_rec','savings_history','deal_comparison',
        'loyalty_widget','referral_widget',
    ];
    foreach ( $sp_ids as $id ) {
        update_option( 'gtbogo_sp_' . esc_html( $id ) . '_enabled',   isset( $_POST['sp_enabled_'   . $id] ) ? 1 : 0 );
        update_option( 'gtbogo_sp_' . esc_html( $id ) . '_anim',      isset( $_POST['sp_anim_'      . $id] ) ? 1 : 0 );
        $intensity = sanitize_text_field( $_POST['sp_intensity_' . $id] ?? 'subtle' );
        if ( in_array( $intensity, ['subtle','moderate','bold','off'], true ) ) {
            update_option( 'gtbogo_sp_' . esc_html( $id ) . '_intensity', $intensity );
        }
        // Per-superpower extras
        foreach ( ['message','threshold','label','text'] as $extra ) {
            $key = 'sp_' . esc_html( $extra ) . '_' . $id;
            if ( isset( $_POST[$key] ) ) {
                update_option( 'gtbogo_sp_' . esc_html( $id ) . '_' . $extra, sanitize_text_field( $_POST[$key] ) );
            }
        }
    }
    // Referral-specific
    update_option( 'gtbogo_sp_referral_widget_enabled',    isset($_POST['sp_enabled_referral_widget'])   ? 1 : 0 );
    update_option( 'gtbogo_flash_email_enabled',           isset($_POST['flash_email_enabled'])          ? 1 : 0 );
    update_option( 'gtbogo_sp_scarcity_bar_threshold',     intval($_POST['scarcity_threshold'] ?? 10) );
    update_option( 'gtbogo_sp_countdown_timer_message',    sanitize_text_field($_POST['countdown_message'] ?? '') );

    $message = 'Superpower settings saved.'; $message_type = 'success';
}

// ── Superpower definitions ────────────────────────────────────────────────────
$superpowers = [
    [
        'section'      => 'Cart Intelligence',
        'section_desc' => 'Backend superpowers that operate silently in the cart and checkout. Zero frontend injection. Zero theme conflicts.',
        'items'        => [
            [ 'id' => 'progress_bar',       'name' => 'Cart Progress Bar',      'icon' => '📊', 'desc' => 'Shows customers how close they are to unlocking a deal inside the cart totals area. AJAX-refreshed on every cart update. Cart page only — never injects into product pages.', 'hooks' => 'woocommerce_before_cart_totals', 'best' => 'Threshold and quantity deals', 'extra' => [] ],
            [ 'id' => 'savings_calc',       'name' => 'Savings Calculator',     'icon' => '💰', 'desc' => 'Shows the exact amount saved in the cart totals area. "You saved $X" — real-time calculated from active rule discount. Cart and checkout pages only.', 'hooks' => 'woocommerce_cart_totals_after_order_total', 'best' => 'All deal types', 'extra' => [] ],
            [ 'id' => 'deal_comparison',    'name' => 'Deal Comparison',        'icon' => '🔄', 'desc' => 'Before/after price comparison in cart totals showing savings as a percentage and absolute amount. Helps customers understand what the deal is worth.', 'hooks' => 'woocommerce_cart_totals_after_order_total', 'best' => 'Percentage and fixed deals', 'extra' => [] ],
            [ 'id' => 'cart_rec',           'name' => 'Cart Recommendations',   'icon' => '🛒', 'desc' => 'Suggests qualifying products inside the cart when the customer is close to unlocking a deal. Pulls from active rule product and category scope. No UI injection outside cart.', 'hooks' => 'woocommerce_after_cart_contents', 'best' => 'Buy X Get Y deals', 'extra' => [] ],
        ],
    ],
    [
        'section'      => 'Customer Lifecycle',
        'section_desc' => 'Backend superpowers that track and respond to customer behaviour over time. All run via WP-Cron or order hooks — zero page-load overhead.',
        'items'        => [
            [ 'id' => 'email_notif',        'name' => 'Email Notifications',    'icon' => '📧', 'desc' => 'Triggers white-labelled lifecycle emails from the store owner\'s own email address when BOGO events occur at order completion. Zero GT BOGO branding visible to customers.', 'hooks' => 'woocommerce_order_status_completed', 'best' => 'All deal types', 'extra' => [] ],
            [ 'id' => 'loyalty_widget',     'name' => 'Loyalty Tier Tracking',  'icon' => '🏆', 'desc' => 'Tracks customer loyalty tier in user meta and applies tier-specific rules automatically. Tiers: Silver ($500 LTV), Gold ($1,000 LTV), VIP ($2,500 LTV). Works with Customer LTV Scoring.', 'hooks' => 'woocommerce_order_status_completed', 'best' => 'VIP and loyalty deals', 'extra' => [] ],
            [ 'id' => 'referral_widget',    'name' => 'Referral Attribution',   'icon' => '🔗', 'desc' => 'Backend referral tracking via URL parameter and cookie. Attributes conversions to referrers, increments referral count, and triggers referral reward emails automatically.', 'hooks' => 'template_redirect, woocommerce_thankyou', 'best' => 'Referral reward deals', 'extra' => [] ],
            [ 'id' => 'savings_history',    'name' => 'Savings History',        'icon' => '📚', 'desc' => 'Records cumulative BOGO savings per customer in user meta. Used by the customer intelligence system and available for export in the PDF report.', 'hooks' => 'woocommerce_order_status_completed', 'best' => 'All deal types', 'extra' => [] ],
            [ 'id' => 'dynamic_pricing',    'name' => 'Dynamic Pricing',        'icon' => '💸', 'desc' => 'Backend price adjustment engine for role-based and segment-based pricing rules. Adjusts rule discount values based on customer role before cart calculation fires.', 'hooks' => 'gtbogo_rule_discount_value', 'best' => 'VIP and role-gated deals', 'extra' => [] ],
            [ 'id' => 'bundle_configurator','name' => 'Bundle Configurator',    'icon' => '⚙️', 'desc' => 'Backend logic for bundle rule validation. Verifies that a cart meets bundle composition requirements before applying a bundle discount. Works with bundle-builder pack rules.', 'hooks' => 'woocommerce_before_calculate_totals', 'best' => 'Bundle deals', 'extra' => [] ],
        ],
    ],
];

require_once __DIR__ . '/../ui-system/wrapper-start.php';
$is_pro = function_exists( 'gt_bogo_has_pro' ) ? gt_bogo_has_pro() : false;
?>
<div class="gt-page-header gt-animate-in">
    <div>
        <h1 class="gt-page-title">⚡ Superpowers</h1>
        <p class="gt-page-subtitle">Backend intelligence superpowers — zero frontend injection, works across all themes</p>
    </div>
    <div style="display:flex;gap:10px;align-items:center">
        <?php
        $total_enabled = 0;
        foreach( $superpowers as $sec ) {
            foreach( $sec['items'] as $sp ) {
                if( get_option('gtbogo_sp_'.$sp['id'].'_enabled', 0) ) $total_enabled++;
            }
        }
        ?>
        <span class="gt-badge gt-badge-active"><?php echo esc_html( $total_enabled ); ?>/25 <?php esc_html_e('active','gt-bogo-engine'); ?></span>
    </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; ?>

<form method="post">
<?php wp_nonce_field('gtbogo_sp_save','gtbogo_sp_nonce'); ?>

<?php foreach ( $superpowers as $section ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:28px">
    <div class="gt-card-header" style="border-bottom:1px solid var(--gt-border);padding-bottom:20px;margin-bottom:0">
        <div>
            <h2 class="gt-card-title"><?php echo esc_html($section['section']); ?></h2>
            <p class="gt-text-soft" style="font-size:13px"><?php echo esc_html($section['section_desc']); ?></p>
        </div>
        <?php
        $sec_active = 0;
        foreach( $section['items'] as $sp ) { if( get_option('gtbogo_sp_'.$sp['id'].'_enabled',0) ) $sec_active++; }
        ?>
        <span class="gt-badge <?php echo $sec_active > 0 ? 'gt-badge-active' : 'gt-badge-free'; ?>">
            <?php echo esc_html( $sec_active ); ?>/<?php echo esc_html( count($section['items']) ); ?> <?php esc_html_e('active','gt-bogo-engine'); ?>
        </span>
    </div>

    <?php foreach ( $section['items'] as $idx => $sp ) :
        $enabled   = (bool) get_option( 'gtbogo_sp_' . esc_html( $sp['id'] ) . '_enabled',   0 );
        $anim      = (bool) get_option( 'gtbogo_sp_' . esc_html( $sp['id'] ) . '_anim',      0 );
        $intensity = get_option( 'gtbogo_sp_' . esc_html( $sp['id'] ) . '_intensity', 'subtle' );
        $is_last   = $idx === count($section['items']) - 1;
    ?>
    <div style="padding:24px;<?php echo ! $is_last ? 'border-bottom:1px solid var(--gt-border);' : ''; ?>">
        <div style="display:grid;grid-template-columns:1fr auto;gap:20px;align-items:start">

            <!-- Left: Info + config -->
            <div>
                <div style="display:flex;align-items:center;gap:10px;margin-bottom:8px;flex-wrap:wrap">
                    <span style="font-size:22px"><?php echo esc_html( $sp['icon'] ); ?></span>
                    <h3 style="margin:0;color:var(--gt-white);font-size:16px;font-weight:700"><?php echo esc_html($sp['name']); ?></h3>
                    <?php if ( $enabled ) : ?>
                    <span class="gt-badge gt-badge-active" style="font-size:13px">Active</span>
                    <?php endif; ?>
                </div>

                <p style="color:var(--gt-subtle);font-size:13px;line-height:1.65;margin:0 0 12px;max-width:680px"><?php echo esc_html($sp['desc']); ?></p>

                <div style="display:flex;gap:16px;flex-wrap:wrap;margin-bottom:<?php echo !empty($sp['extra']) ? '14px' : '0'; ?>">
                    <span style="font-size:13px;color:var(--gt-subtle)">
                        <strong style="color:var(--gt-soft)">Hooks:</strong> <?php echo esc_html($sp['hooks']); ?>
                    </span>
                    <span style="font-size:13px;color:var(--gt-subtle)">
                        <strong style="color:var(--gt-soft)">Best for:</strong> <?php echo esc_html($sp['best']); ?>
                    </span>
                </div>

                <!-- Extra config fields -->
                <?php if ( ! empty($sp['extra']) ) : ?>
                <div style="display:flex;gap:12px;flex-wrap:wrap;margin-top:12px">
                    <?php foreach ( $sp['extra'] as [$fname, $flabel, $fdesc, $fdefault] ) :
                        $fval = get_option('gtbogo_sp_'.$sp['id'].'_'.str_replace('sp_'.''.$sp['id'].'_','',$fname), $fdefault);
                        // Actually just use a direct option read
                        $opt_key = 'gtbogo_sp_' . esc_html( $sp['id'] ) . '_' . explode('_', $fname, 2)[0];
                        // Use fname directly as the post key
                    ?>
                    <div>
                        <div style="font-size:13px;font-weight:600;color:var(--gt-soft);margin-bottom:4px"><?php echo esc_html($flabel); ?></div>
                        <div style="font-size:13px;color:var(--gt-subtle);margin-bottom:6px"><?php echo esc_html($fdesc); ?></div>
                        <input type="<?php echo is_numeric($fdefault) ? 'number' : 'text'; ?>"
                               name="<?php echo esc_attr($fname); ?>"
                               class="gt-input"
                               style="max-width:180px;font-size:13px"
                               value="<?php echo esc_attr(get_option('gtbogo_sp_'.$sp['id'].'_'.explode('_',$fname)[0], $fdefault)); ?>"
                               placeholder="<?php echo esc_attr($fdefault); ?>">
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>

            <!-- Right: Controls -->
            <div style="display:flex;flex-direction:column;gap:14px;align-items:flex-end;min-width:200px">

                <!-- Enable toggle -->
                <div style="display:flex;align-items:center;gap:10px">
                    <span style="font-size:13px;color:var(--gt-soft);font-weight:600">Enable</span>
                    <label class="gt-toggle">
                        <input type="checkbox" name="sp_enabled_<?php echo esc_attr($sp['id']); ?>" value="1" <?php checked($enabled); ?>>
                        <span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span>
                    </label>
                </div>

                <!-- Intensity selector -->
                <div style="display:flex;align-items:center;gap:10px">
                    <span style="font-size:13px;color:var(--gt-soft);font-weight:600">Intensity</span>
                    <select name="sp_intensity_<?php echo esc_attr($sp['id']); ?>" class="gt-select" style="font-size:13px;padding:4px 8px">
                        <option value="subtle"   <?php selected($intensity,'subtle'); ?>><?php esc_html_e('Subtle','gt-bogo-engine'); ?></option>
                        <option value="moderate" <?php selected($intensity,'moderate'); ?>><?php esc_html_e('Moderate','gt-bogo-engine'); ?></option>
                        <option value="bold"     <?php selected($intensity,'bold'); ?>><?php esc_html_e('Bold','gt-bogo-engine'); ?></option>
                        <option value="off"      <?php selected($intensity,'off'); ?>><?php esc_html_e('Off','gt-bogo-engine'); ?></option>
                    </select>
                </div>

                <!-- Animate toggle -->
                <div style="display:flex;align-items:center;gap:10px">
                    <span style="font-size:13px;color:var(--gt-soft);font-weight:600">Animate</span>
                    <label class="gt-toggle">
                        <input type="checkbox" name="sp_anim_<?php echo esc_attr($sp['id']); ?>" value="1" <?php checked($anim); ?>>
                        <span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span>
                    </label>
                </div>

                <!-- Intensity preview -->
                <div style="text-align:right">
                    <div style="font-size:13px;color:var(--gt-subtle);margin-bottom:4px">Current: <?php echo esc_html(ucfirst($intensity)); ?></div>
                    <div style="display:flex;gap:3px">
                        <?php
                        $levels = ['subtle'=>1,'moderate'=>2,'bold'=>3];
                        $current_level = $levels[$intensity] ?? 0;
                        for ($i=1;$i<=3;$i++) : ?>
                        <div style="width:20px;height:6px;border-radius:3px;background:<?php echo $i<=$current_level ? 'var(--gt-red)' : 'rgba(255,255,255,0.1)'; ?>"></div>
                        <?php endfor; ?>
                    </div>
                </div>

            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endforeach; ?>

<!-- Global settings -->
<div class="gt-card gt-animate-in" style="margin-bottom:28px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">🌐 Global Superpower Settings</h2>
    </div>
    <div class="gt-card-body">
        <div class="gt-setting-row">
            <div>
                <div class="gt-setting-label"><?php esc_html_e('Flash Sale Broadcast Emails','gt-bogo-engine'); ?></div>
                <div class="gt-setting-desc"><?php esc_html_e('When a flash sale rule is activated in Pro Rules, automatically broadcast an email to recent customers. Requires Customer Emails enabled in Settings.','gt-bogo-engine'); ?></div>
            </div>
            <label class="gt-toggle">
                <input type="checkbox" name="flash_email_enabled" value="1" <?php checked(get_option('gtbogo_flash_email_enabled',0)); ?>>
                <span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span>
            </label>
        </div>
        <div class="gt-setting-row" style="border:none">
            <div>
                <div class="gt-setting-label"><?php esc_html_e('Countdown Timer Default Message','gt-bogo-engine'); ?></div>
                <div class="gt-setting-desc"><?php esc_html_e('Default text shown before the countdown clock when no rule-specific message is set.','gt-bogo-engine'); ?></div>
            </div>
            <input type="text" name="countdown_message" class="gt-input" style="max-width:240px"
                   value="<?php echo esc_attr(get_option('gtbogo_sp_countdown_timer_message', __('Deal ends in','gt-bogo-engine'))); ?>"
                   placeholder="<?php esc_attr_e('Deal ends in','gt-bogo-engine'); ?>">
        </div>
    </div>
</div>

<div style="display:flex;gap:12px;align-items:center;padding-bottom:40px">
    <button type="submit" class="gt-btn gt-btn-primary">Save All Superpower Settings</button>
    <span style="font-size:13px;color:var(--gt-subtle)"><?php esc_html_e('Settings apply immediately on save. No cache flush required.','gt-bogo-engine'); ?></span>
</div>

</form>

<style>
.gtbogo-toggle,.gt-toggle{display:inline-flex;align-items:center;width:40px;height:22px;background:rgba(255,255,255,0.1);border:1px solid rgba(255,255,255,0.2);border-radius:50px;cursor:pointer;transition:background .2s,border-color .2s;flex-shrink:0;position:relative}
.gt-toggle input:checked~.gt-toggle-track,.gtbogo-toggle-on{background:rgba(34,197,94,0.25);border-color:rgba(34,197,94,0.5)}
.gt-toggle-track{display:flex;align-items:center;width:40px;height:22px;background:rgba(255,255,255,0.1);border:1px solid rgba(255,255,255,0.2);border-radius:50px;cursor:pointer;transition:background .2s;position:relative}
.gt-toggle input{position:absolute;opacity:0;width:0;height:0}
.gt-toggle input:checked~.gt-toggle-track{background:rgba(34,197,94,0.25);border-color:rgba(34,197,94,0.5)}
.gt-toggle-thumb{width:16px;height:16px;border-radius:50%;background:#64748b;position:absolute;left:2px;transition:left .2s,background .2s;pointer-events:none}
.gt-toggle input:checked~.gt-toggle-track .gt-toggle-thumb{left:20px;background:#22c55e}
</style>


<script>
(function() {
    var nonce = '<?php echo esc_js(wp_create_nonce("gt_bogo_sp_toggle")); ?>';
    var ajaxUrl = '<?php echo esc_js(admin_url("admin-ajax.php")); ?>';

    function saveSP(sp_id, field, value, callback) {
        var data = new FormData();
        data.append('action',  'gt_bogo_save_superpower_field');
        data.append('nonce',   nonce);
        data.append('sp_id',   sp_id);
        data.append('field',   field);
        data.append('value',   value);
        fetch(ajaxUrl, { method:'POST', body:data, credentials:'same-origin' })
        .then(function(r){ return r.json(); })
        .then(function(res){
            if (res.success) {
                if (field === 'enabled' && window.gtBogoSPBroadcast) {
                    gtBogoSPBroadcast(sp_id, value === '1');
                }
                if (callback) callback(true);
            } else {
                if (callback) callback(false);
            }
        })
        .catch(function(){ if (callback) callback(false); });
    }

    function getSpId(el) {
        var name = el.name || '';
        // sp_enabled_cart_progress_bar -> cart_progress_bar
        var m = name.match(/^sp_(?:enabled|intensity|anim)_(.+)$/);
        return m ? m[1] : null;
    }

    function showFeedback(el, ok) {
        var wrap = el.closest('div') || el.parentNode;
        var tick = document.createElement('span');
        tick.textContent = ok ? ' ✓' : ' ✗';
        tick.style.cssText = 'font-size:11px;font-weight:700;margin-left:4px;transition:opacity .5s;color:' + (ok ? '#22c55e' : '#ef4444');
        wrap.appendChild(tick);
        setTimeout(function(){ tick.style.opacity='0'; }, 1200);
        setTimeout(function(){ if(tick.parentNode) tick.parentNode.removeChild(tick); }, 1800);
    }

    document.addEventListener('DOMContentLoaded', function() {
        // Hide Save button — all saves are now instant
        var saveBtn = document.querySelector('button[type="submit"].gt-btn-primary');
        if (saveBtn) {
            saveBtn.style.display = 'none';
            // Add live-save indicator next to where button was
            var ind = document.createElement('div');
            ind.style.cssText = 'font-size:13px;color:var(--gt-subtle);padding:10px 0';
            ind.textContent = 'All changes save instantly';
            saveBtn.parentNode.insertBefore(ind, saveBtn);
        }

        // Enable toggles
        document.querySelectorAll('input[name^="sp_enabled_"]').forEach(function(el) {
            el.addEventListener('change', function() {
                var sp_id = getSpId(el);
                if (!sp_id) return;
                saveSP(sp_id, 'enabled', el.checked ? '1' : '0', function(ok) {
                    showFeedback(el, ok);
                    // Update active count badge
                    var active = document.querySelectorAll('input[name^="sp_enabled_"]:checked').length;
                    var badge = document.querySelector('.gt-badge-active');
                    if (badge) badge.textContent = active + '/25 active';
                    // Update section active count
                    var section = el.closest('.gt-card');
                    if (section) {
                        var secActive = section.querySelectorAll('input[name^="sp_enabled_"]:checked').length;
                        var secTotal  = section.querySelectorAll('input[name^="sp_enabled_"]').length;
                        var secBadge  = section.querySelector('.gt-badge');
                        if (secBadge) secBadge.textContent = secActive + '/' + secTotal + ' active';
                    }
                });
            });
        });

        // Intensity selects
        document.querySelectorAll('select[name^="sp_intensity_"]').forEach(function(el) {
            el.addEventListener('change', function() {
                var sp_id = getSpId(el);
                if (!sp_id) return;
                saveSP(sp_id, 'intensity', el.value, function(ok) {
                    showFeedback(el, ok);
                    // Update intensity preview bars and label
                    var wrap = el.closest('div[style*="flex-direction:column"]');
                    if (wrap) {
                        var preview = wrap.querySelector('[style*="Current:"]');
                        if (preview) preview.textContent = 'Current: ' + el.value.charAt(0).toUpperCase() + el.value.slice(1);
                        var levels = {subtle:1, moderate:2, bold:3, off:0};
                        var lvl = levels[el.value] || 0;
                        var bars = wrap.querySelectorAll('[style*="width:20px"]');
                        bars.forEach(function(bar, i) {
                            bar.style.background = (i < lvl) ? 'var(--gt-red)' : 'rgba(255,255,255,0.1)';
                        });
                    }
                });
            });
        });

        // Animate toggles
        document.querySelectorAll('input[name^="sp_anim_"]').forEach(function(el) {
            el.addEventListener('change', function() {
                var sp_id = getSpId(el);
                if (!sp_id) return;
                saveSP(sp_id, 'animate', el.checked ? '1' : '0', function(ok) {
                    showFeedback(el, ok);
                });
            });
        });
    });
})();
</script>

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