<?php
/**
 * GT BOGO Engine — ROI Projector (Enterprise)
 * @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 = '';

// ── Save Projection Scenario ──────────────────────────────────────────────
if ($is_pro && isset($_POST['gtbogo_save_scenario']) && check_admin_referer('gtbogo_save_scenario')) {
    $scenarios = get_option('gtbogo_roi_scenarios', []);
    $sid = sanitize_text_field($_POST['scenario_id'] ?? uniqid('s_'));
    $scenarios[$sid] = [
        'name'           => sanitize_text_field($_POST['scenario_name']       ?? 'New Scenario'),
        'avg_order'      => floatval($_POST['avg_order']                      ?? 0),
        'margin'         => floatval($_POST['margin_pct']                     ?? 0),
        'monthly_orders' => intval($_POST['monthly_orders']                   ?? 0),
        'bogo_type'      => sanitize_text_field($_POST['bogo_type']           ?? 'bogo_100'),
        'lift_pct'       => floatval($_POST['lift_pct']                       ?? 15),
        'conversion_lift'=> floatval($_POST['conversion_lift']                ?? 0),
        'campaign_days'  => intval($_POST['campaign_days']                    ?? 30),
        'cogs_item'      => floatval($_POST['cogs_item']                      ?? 0),
        'note'           => sanitize_textarea_field($_POST['scenario_note']   ?? ''),
        'saved'          => current_time('mysql'),
    ];
    update_option('gtbogo_roi_scenarios', $scenarios);
    if (function_exists('gt_bogo_log')) gt_bogo_log('ROI scenario saved', $scenarios[$sid]['name'], 'info');
    $message = 'Scenario "'.esc_html($scenarios[$sid]['name']).'" saved.'; $message_type = 'success';
}

// ── Delete Scenario ───────────────────────────────────────────────────────
if ($is_pro && isset($_GET['delete_scenario']) && check_admin_referer('delete_s_'.sanitize_text_field($_GET['delete_scenario']))) {
    $scenarios = get_option('gtbogo_roi_scenarios', []);
    $sid = sanitize_text_field($_GET['delete_scenario']);
    unset($scenarios[$sid]);
    update_option('gtbogo_roi_scenarios', $scenarios);
    $message = 'Scenario deleted.'; $message_type = 'success';
}

$scenarios    = get_option('gtbogo_roi_scenarios', []);
$load_sid     = isset($_GET['load']) ? sanitize_text_field($_GET['load']) : '';
$loaded       = ($load_sid && isset($scenarios[$load_sid])) ? $scenarios[$load_sid] : null;

// Pull real analytics for benchmarking
global $wpdb;
$atbl = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->prefix.'gtbogo_analytics'));
$real = null;
if ($atbl) {
    $real = $wpdb->get_row($wpdb->prepare(
        "SELECT COUNT(DISTINCT order_id) AS orders,
                COALESCE(AVG(order_total),0) AS aov,
                COALESCE(SUM(discount_amount),0) AS total_discount,
                COALESCE(SUM(order_total),0) AS revenue
         FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created >= %s",
        gmdate('Y-m-d H:i:s', strtotime('-30 days'))
    ), ARRAY_A);
}

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div id="gtb-roi-content">
<div class="gt-page-header gt-animate-in">
    <div>
        <h1 class="gt-page-title">📊 ROI Projector</h1>
        <p class="gt-page-subtitle">Model campaign scenarios before you launch — project revenue lift, discount cost, and net margin impact</p>
    </div>
    <div style="display:flex;gap:8px;align-items:center">
        <span class="gt-badge gt-badge-active"><?php echo esc_html( count($scenarios) ); ?> Saved Scenario<?php echo count($scenarios)!==1?'s':''; ?></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; ?>

<?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 ROI Projector models your campaign economics before launch — project net profit impact, discount cost, and AOV lift across different BOGO structures.</p>
    <div style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px;max-width:480px;margin:24px auto 0">
        <?php foreach(['Live projection calculator with real-time math','Save and compare multiple scenarios','Benchmarked against your real 30-day analytics','Net margin impact with COGS-aware discount costing'] as $f): ?>
        <div style="display:flex;align-items:flex-start;gap:8px;text-align:left"><span style="color:#e10000;font-weight:700">—</span><span style="font-size:13px;color:var(--gt-soft)"><?php echo esc_html($f); ?></span></div>
        <?php endforeach; ?>
    </div>
    <div style="margin-top:24px;display:flex;justify-content:center;gap:12px">
        <a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" class="gt-btn gt-btn-primary">Purchase PRO — $149/yr</a>
    </div>
</div>
<?php else: ?>

<!-- REAL ANALYTICS BENCHMARK -->
<?php if ($real && $real['orders'] > 0): ?>
<div class="gt-notice gt-animate-in" style="background:rgba(59,130,246,0.06);border-color:rgba(59,130,246,0.2);margin-bottom:20px">
    <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px">
        <div style="font-size:13px;color:var(--gt-soft)">
            📈 <strong style="color:var(--gt-white)">Last 30 days (real data):</strong>
            <?php echo esc_html( number_format($real['orders']) ); ?> BOGO orders ·
            AOV $<?php echo esc_html( number_format($real['aov'],2) ); ?> ·
            Total discounts $<?php echo esc_html( number_format($real['total_discount'],2) ); ?> ·
            Revenue influenced $<?php echo esc_html( number_format($real['revenue'],2) ); ?>
        </div>
        <span style="font-size:13px;color:var(--gt-subtle)">Pre-filled into projector below</span>
    </div>
</div>
<?php endif; ?>

<!-- PROJECTOR -->
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px">

<!-- INPUTS -->
<div class="gt-card gt-animate-in">
    <div class="gt-card-header"><h2 class="gt-card-title">⚙️ Campaign Inputs</h2></div>
    <form method="post" action="" id="roi-form">
        <?php wp_nonce_field('gtbogo_save_scenario'); ?>
        <?php if ($loaded): ?><input type="hidden" name="scenario_id" value="<?php echo esc_attr($load_sid); ?>"><?php endif; ?>

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

            <div class="gt-form-group">
                <label class="gt-form-label">Scenario Name</label>
                <input type="text" name="scenario_name" id="in-name" class="gt-input" value="<?php echo esc_attr($loaded['name']??'New Scenario'); ?>" oninput="updateProjection()">
            </div>
            <div class="gt-form-group">
                <label class="gt-form-label">BOGO Deal Type</label>
                <select name="bogo_type" id="in-type" class="gt-select" onchange="updateProjection()">
                    <?php $types = [
                        'bogo_100' => 'Buy 1 Get 1 Free (100%)',
                        'bogo_50'  => 'Buy 1 Get 1 at 50% Off',
                        'bogo_25'  => 'Buy 1 Get 1 at 25% Off',
                        'b2g1'     => 'Buy 2 Get 1 Free',
                        'b3g1'     => 'Buy 3 Get 1 Free',
                        'fixed'    => 'Fixed Amount Off Item',
                    ];
                    foreach ($types as $k=>$v): ?>
                    <option value="<?php echo esc_html( $k ); ?>" <?php selected($loaded['bogo_type']??'bogo_100',$k); ?>><?php echo esc_html($v); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="gt-form-group">
                <label class="gt-form-label">Average Order Value ($)</label>
                <input type="number" name="avg_order" id="in-aov" class="gt-input" value="<?php echo esc_attr($loaded['avg_order'] ?? number_format($real['aov']??50,2,'.','')); ?>" step="0.01" min="1" oninput="updateProjection()">
                <div class="gt-form-hint">Avg cart value without the BOGO promotion</div>
            </div>
            <div class="gt-form-group">
                <label class="gt-form-label">Gross Margin (%)</label>
                <input type="number" name="margin_pct" id="in-margin" class="gt-input" value="<?php echo esc_attr($loaded['margin']??50); ?>" step="0.1" min="1" max="100" oninput="updateProjection()">
                <div class="gt-form-hint">Your gross margin before the BOGO discount</div>
            </div>

            <div class="gt-form-group">
                <label class="gt-form-label">Monthly Orders (baseline)</label>
                <input type="number" name="monthly_orders" id="in-orders" class="gt-input" value="<?php echo esc_attr($loaded['monthly_orders'] ?? max(1,intval($real['orders']??100))); ?>" min="1" oninput="updateProjection()">
                <div class="gt-form-hint">Orders per month without any promotion</div>
            </div>
            <div class="gt-form-group">
                <label class="gt-form-label">Expected Order Volume Lift (%)</label>
                <input type="number" name="lift_pct" id="in-lift" class="gt-input" value="<?php echo esc_attr($loaded['lift_pct']??15); ?>" step="0.1" min="0" max="500" oninput="updateProjection()">
                <div class="gt-form-hint">% more orders expected during the campaign</div>
            </div>

            <div class="gt-form-group">
                <label class="gt-form-label">AOV Lift from BOGO (%)</label>
                <input type="number" name="conversion_lift" id="in-aov-lift" class="gt-input" value="<?php echo esc_attr($loaded['conversion_lift']??0); ?>" step="0.1" min="0" oninput="updateProjection()">
                <div class="gt-form-hint">% AOV increase customers add to qualify (e.g. 5%)</div>
            </div>
            <div class="gt-form-group">
                <label class="gt-form-label">Campaign Duration (Days)</label>
                <input type="number" name="campaign_days" id="in-days" class="gt-input" value="<?php echo esc_attr($loaded['campaign_days']??30); ?>" min="1" max="365" oninput="updateProjection()">
            </div>

            <div class="gt-form-group" style="grid-column:span 2">
                <label class="gt-form-label">Average Item COGS ($) <span style="font-weight:400;color:var(--gt-subtle)">(for free item cost calculation)</span></label>
                <input type="number" name="cogs_item" id="in-cogs" class="gt-input" value="<?php echo esc_attr($loaded['cogs_item']??0); ?>" step="0.01" min="0" oninput="updateProjection()">
                <div class="gt-form-hint">Cost of the free/discounted item delivered to the customer. Used to calculate true discount cost including fulfillment.</div>
            </div>

            <div class="gt-form-group" style="grid-column:span 2">
                <label class="gt-form-label">Scenario Notes</label>
                <textarea name="scenario_note" class="gt-input" rows="2" placeholder="Internal notes about assumptions..."><?php echo esc_textarea($loaded['note']??''); ?></textarea>
            </div>
        </div>

        <div style="display:flex;gap:10px;margin-top:4px">
            <button type="submit" name="gtbogo_save_scenario" class="gt-btn gt-btn-primary" style="flex:1;padding:11px">💾 Save Scenario</button>
            <button type="button" onclick="resetProjector()" class="gt-btn gt-btn-ghost">↺ Reset</button>
        </div>
    </form>
</div>

<!-- LIVE PROJECTION OUTPUT -->
<div class="gt-card gt-animate-in" id="roi-output">
    <div class="gt-card-header"><h2 class="gt-card-title">📈 Live Projection</h2><span class="gt-text-soft" style="font-size:13px" id="proj-scenario-name">New Scenario</span></div>

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:20px">
        <?php foreach([
            ['proj-orders',   '🛒', 'Campaign Orders',       '#3b82f6'],
            ['proj-revenue',  '💰', 'Projected Revenue',     '#22c55e'],
            ['proj-discount', '🏷️', 'Total Discount Cost',   '#f59e0b'],
            ['proj-net',      '📊', 'Net Margin Impact',     '#e10000'],
            ['proj-cogs',     '📦', 'COGS of Free Items',    '#8b5cf6'],
            ['proj-roi',      '⭐', 'ROI Multiple',          '#64748b'],
        ] as $m): ?>
        <div style="padding:16px;border-radius:10px;background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);text-align:center">
            <div style="font-size:22px;margin-bottom:4px"><?php echo esc_html( $m[1] ); ?></div>
            <div style="font-size:13px;color:var(--gt-subtle);margin-bottom:6px;text-transform:uppercase;letter-spacing:0.8px"><?php echo esc_html($m[2]); ?></div>
            <div id="<?php echo esc_html( $m[0] ); ?>" style="font-size:22px;font-weight:800;color:<?php echo esc_html( $m[3] ); ?>;font-family:'DM Mono',monospace">—</div>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- BREAKDOWNS -->
    <div style="font-size:13px;font-weight:700;color:var(--gt-white);text-transform:uppercase;letter-spacing:1px;margin-bottom:10px">Detailed Breakdown</div>
    <div id="proj-detail" style="display:flex;flex-direction:column;gap:6px;font-size:13px;font-family:'DM Mono',monospace">
        <div style="color:var(--gt-subtle);text-align:center;padding:20px">Enter inputs to see projection</div>
    </div>

    <!-- MARGIN HEALTH BAR -->
    <div style="margin-top:16px">
        <div style="display:flex;justify-content:space-between;margin-bottom:4px">
            <span style="font-size:13px;color:var(--gt-soft)">Margin Health</span>
            <span id="proj-health-label" style="font-size:13px;font-weight:700"></span>
        </div>
        <div style="height:8px;background:rgba(255,255,255,0.05);border-radius:50px;overflow:hidden">
            <div id="proj-health-bar" style="height:100%;width:0%;border-radius:50px;transition:width 0.6s,background 0.3s"></div>
        </div>
    </div>

    <!-- RECOMMENDATION -->
    <div id="proj-recommendation" style="margin-top:16px;padding:12px 16px;border-radius:8px;font-size:13px;line-height:1.7;display:none"></div>
</div>
</div>

<!-- SCENARIO COMPARISON TABLE -->
<?php if (!empty($scenarios)): ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">📋 Saved Scenarios</h2>
        <span class="gt-text-soft" style="font-size:13px"><?php echo esc_html( count($scenarios) ); ?> scenario<?php echo count($scenarios)!==1?'s':''; ?> saved</span>
    </div>
    <div style="overflow-x:auto">
        <table class="gt-table">
            <thead><tr><th>Name</th><th>Type</th><th>AOV</th><th>Margin</th><th>Baseline Orders</th><th>Lift</th><th>Days</th><th>Saved</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach ($scenarios as $sid => $sc): ?>
            <tr>
                <td style="font-weight:700;color:var(--gt-white)"><?php echo esc_html($sc['name']); ?></td>
                <td style="font-size:13px;color:var(--gt-soft)"><?php echo esc_html($types[$sc['bogo_type']]??$sc['bogo_type']); ?></td>
                <td style="font-family:'DM Mono',monospace;color:var(--gt-white)">$<?php echo esc_html( number_format($sc['avg_order'],2) ); ?></td>
                <td style="font-family:'DM Mono',monospace;color:<?php echo $sc['margin']>=40?'#86efac':($sc['margin']>=25?'#fcd34d':'#fca5a5'); ?>"><?php echo esc_html( $sc['margin'] ); ?>%</td>
                <td style="font-family:'DM Mono',monospace;color:var(--gt-white)"><?php echo esc_html( number_format($sc['monthly_orders']) ); ?></td>
                <td style="font-family:'DM Mono',monospace;color:#86efac">+<?php echo esc_html( $sc['lift_pct'] ); ?>%</td>
                <td style="font-family:'DM Mono',monospace;color:var(--gt-soft)"><?php echo esc_html( $sc['campaign_days'] ); ?>d</td>
                <td style="font-size:13px;color:var(--gt-subtle)"><?php echo esc_html(substr($sc['saved'],0,10)); ?></td>
                <td>
                    <div style="display:flex;gap:6px">
                        <a href="?page=gt-bogo-engine&tab=roi-projector&load=<?php echo esc_attr($sid); ?>" class="gt-btn gt-btn-ghost gt-btn-sm" style="padding:4px 10px">📂 Load</a>
                        <a href="<?php echo esc_url(wp_nonce_url(add_query_arg(['delete_scenario'=>$sid,'page'=>'gt-bogo-engine','tab'=>'roi-projector'],admin_url('admin.php')),'delete_s_'.$sid)); ?>"
                           class="gt-btn gt-btn-ghost gt-btn-sm" style="padding:4px 10px;color:#fca5a5"
                           onclick="return confirm('Delete this scenario?')">✕</a>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- PROJECTION ENGINE JS -->
<script>
const BOGO_TYPES = {
    bogo_100: {discount_ratio: 0.5,  label: 'BOGO 100%'},
    bogo_50:  {discount_ratio: 0.25, label: 'BOGO 50%'},
    bogo_25:  {discount_ratio: 0.125,label: 'BOGO 25%'},
    b2g1:     {discount_ratio: 0.333,label: 'Buy 2 Get 1'},
    b3g1:     {discount_ratio: 0.25, label: 'Buy 3 Get 1'},
    fixed:    {discount_ratio: 0.1,  label: 'Fixed Discount'},
};

function fmt(n, prefix) { return (prefix||'') + parseFloat(n).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ','); }
function fmtInt(n) { return Math.round(n).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); }

function updateProjection() {
    var aov       = parseFloat(document.getElementById('in-aov').value)    || 0;
    var margin    = parseFloat(document.getElementById('in-margin').value)  || 0;
    var orders    = parseFloat(document.getElementById('in-orders').value)  || 0;
    var lift      = parseFloat(document.getElementById('in-lift').value)    || 0;
    var aovlift   = parseFloat(document.getElementById('in-aov-lift').value)|| 0;
    var days      = parseFloat(document.getElementById('in-days').value)    || 30;
    var cogs      = parseFloat(document.getElementById('in-cogs').value)    || 0;
    var typeKey   = document.getElementById('in-type').value;
    var scenName  = document.getElementById('in-name').value;
    var bt        = BOGO_TYPES[typeKey] || BOGO_TYPES.bogo_100;

    if (!aov || !margin || !orders) return;

    // Scale to campaign days
    var daily_baseline = orders / 30;
    var campaign_orders_baseline = daily_baseline * days;

    // Apply lifts
    var promo_aov     = aov * (1 + aovlift / 100);
    var promo_orders  = campaign_orders_baseline * (1 + lift / 100);

    // Revenue
    var gross_revenue = promo_orders * promo_aov;

    // Discount cost
    var discount_per_order = promo_aov * bt.discount_ratio;
    var total_discount     = promo_orders * discount_per_order;

    // COGS of free items
    var cogs_total = cogs > 0 ? promo_orders * cogs * bt.discount_ratio * 2 : 0;

    // Net revenue after discount
    var net_revenue = gross_revenue - total_discount;

    // Margin before discount
    var gross_margin_dollars = gross_revenue * (margin / 100);

    // Net margin after discount
    var net_margin = gross_margin_dollars - total_discount - cogs_total;

    // ROI
    var roi = total_discount > 0 ? net_margin / total_discount : 0;

    // Effective margin pct
    var eff_margin_pct = gross_revenue > 0 ? (net_margin / gross_revenue) * 100 : 0;

    // Update outputs
    document.getElementById('proj-scenario-name').textContent = scenName;
    document.getElementById('proj-orders').textContent   = fmtInt(promo_orders);
    document.getElementById('proj-revenue').textContent  = '$' + fmt(gross_revenue);
    document.getElementById('proj-discount').textContent = '$' + fmt(total_discount);
    document.getElementById('proj-net').textContent      = (net_margin >= 0 ? '+$' : '-$') + fmt(Math.abs(net_margin));
    document.getElementById('proj-net').style.color      = net_margin >= 0 ? '#86efac' : '#fca5a5';
    document.getElementById('proj-cogs').textContent     = cogs_total > 0 ? '$' + fmt(cogs_total) : '—';
    document.getElementById('proj-roi').textContent      = roi.toFixed(2) + 'x';

    // Detail breakdown
    var detail = document.getElementById('proj-detail');
    detail.innerHTML = [
        ['Daily orders (promo period)',    fmtInt(promo_orders/days) + '/day'],
        ['Promo AOV',                      '$' + fmt(promo_aov)],
        ['Gross revenue',                  '$' + fmt(gross_revenue)],
        ['Discount per order',             '-$' + fmt(discount_per_order)],
        ['Total discount cost',            '-$' + fmt(total_discount)],
        ['Gross margin pre-discount',      '$' + fmt(gross_margin_dollars) + ' (' + margin.toFixed(1) + '%)'],
        ['Effective margin post-discount', fmt(eff_margin_pct, '') + '%'],
        ['Net margin impact',              (net_margin>=0?'+':'-') + '$' + fmt(Math.abs(net_margin))],
    ].map(r =>
        '<div style="display:flex;justify-content:space-between;padding:5px 0;border-bottom:1px solid rgba(255,255,255,0.04)">' +
        '<span style="color:var(--gt-soft)">' + r[0] + '</span>' +
        '<span style="color:var(--gt-white);font-weight:700">' + r[1] + '</span></div>'
    ).join('');

    // Health bar
    var health = Math.max(0, Math.min(100, eff_margin_pct * 2));
    var hbar = document.getElementById('proj-health-bar');
    var hlbl = document.getElementById('proj-health-label');
    hbar.style.width    = health + '%';
    hbar.style.background = eff_margin_pct > 20 ? '#22c55e' : eff_margin_pct > 10 ? '#f59e0b' : '#e10000';
    hlbl.textContent  = eff_margin_pct > 20 ? 'Healthy' : eff_margin_pct > 10 ? 'Marginal' : 'At Risk';
    hlbl.style.color  = eff_margin_pct > 20 ? '#86efac' : eff_margin_pct > 10 ? '#fcd34d' : '#fca5a5';

    // Recommendation
    var rec = document.getElementById('proj-recommendation');
    rec.style.display = 'block';
    if (eff_margin_pct > 25) {
        rec.style.background = 'rgba(34,197,94,0.06)'; rec.style.borderLeft = '3px solid #22c55e';
        rec.style.color = '#86efac';
        rec.innerHTML = '✅ <strong>Strong projection.</strong> This campaign should be margin-positive. Proceed, and monitor your discount rate in Analytics after launch.';
    } else if (eff_margin_pct > 10) {
        rec.style.background = 'rgba(245,158,11,0.06)'; rec.style.borderLeft = '3px solid #f59e0b';
        rec.style.color = '#fcd34d';
        rec.innerHTML = '⚠ <strong>Marginal projection.</strong> Effective margin is thin. Consider switching to a 50% BOGO, reducing campaign duration, or adding a minimum cart threshold to protect margin.';
    } else {
        rec.style.background = 'rgba(225,0,0,0.06)'; rec.style.borderLeft = '3px solid #e10000';
        rec.style.color = '#fca5a5';
        rec.innerHTML = '🚨 <strong>High risk.</strong> This campaign is projected to be margin-negative. Revise the BOGO type, increase your baseline margin, or significantly increase the expected lift to justify the cost.';
    }
}

function resetProjector() {
    ['in-aov','in-margin','in-orders','in-lift','in-aov-lift','in-days','in-cogs'].forEach(id => {
        var el = document.getElementById(id);
        if (el) el.value = id==='in-lift'?'15':id==='in-days'?'30':id==='in-margin'?'50':'0';
    });
    updateProjection();
}

document.addEventListener('DOMContentLoaded', updateProjection);
</script>

<!-- GUIDANCE -->
<div class="gt-card gt-animate-in" style="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">🧠 How to Use the ROI Projector</h2></div>
    <div class="gt-feature-grid gt-feature-grid--2col">
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Model Three Scenarios</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Always create at minimum three scenarios: Conservative (5% lift), Base Case (15% lift), and Optimistic (30% lift). Save all three and compare them in the table above. Only proceed if even your Conservative case shows a positive net margin.</div></div>
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">The Lift % Assumption</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">If this is your first BOGO campaign, use 10–15% as your conservative lift. After your first campaign, replace this with your actual Analytics data — the 30-day order volume uplift measured against your baseline. This makes each subsequent scenario more accurate.</div></div>
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">COGS Matters for Full BOGO</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">For full 100% BOGO, the cost of the free item includes both the lost sale price AND the cost of goods. Enter your average COGS per item to see the true cost — stores frequently underestimate full BOGO cost by ignoring fulfillment and COGS.</div></div>
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Effective Margin Below 15% — Stop</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">If the projector shows effective post-discount margin below 15%, the campaign will likely hurt overall profitability unless your customer lifetime value is high enough to justify the acquisition cost. Switch to a less aggressive BOGO type or add a minimum order threshold.</div></div>
    </div>
</div>

<?php endif; ?>
</div><!-- #gtb-roi-content -->

<script>
(function() {
    var cid = 'gtb-roi-content';
    // Mark all internal filter/nav links for this tab
    document.querySelectorAll('a[href*="tab=roi-projector"]').forEach(function(a) {
        var href = a.getAttribute('href') || '';
        if (/load/.test(href) || href.indexOf('tab=roi-projector') !== -1) {
            if (!a.classList.contains('gtb-inline-link')) a.classList.add('gtb-inline-link');
        }
    });
    document.addEventListener('click', function(e) {
        var link = e.target.closest('a.gtb-inline-link');
        if (!link) return;
        var href = link.getAttribute('href') || '';
        if (!href || href.indexOf('#') === 0) return;
        e.preventDefault();
        var content = document.getElementById(cid);
        if (!content) { window.location.href = href; return; }
        content.style.opacity = '0.5';
        content.style.transition = 'opacity 0.1s ease';
        fetch(href, {credentials:'same-origin'})
            .then(function(r) { return r.text(); })
            .then(function(html) {
                var doc2 = new DOMParser().parseFromString(html, 'text/html');
                var nc = doc2.getElementById(cid);
                if (nc) {
                    content.innerHTML = nc.innerHTML;
                    content.style.opacity = '1';
                    history.pushState(null, '', href);
                    // Re-mark new links after swap
                    content.querySelectorAll('a[href*="tab=roi-projector"]').forEach(function(a) {
                        var h = a.getAttribute('href') || '';
                        if (/load/.test(h) || h.indexOf('tab=roi-projector') !== -1) a.classList.add('gtb-inline-link');
                    });
                } else {
                    window.location.href = href;
                }
            })
            .catch(function() { window.location.href = href; });
    });
})();
</script>
<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>
