<?php
/**
 * GT BOGO Engine — ROI & Analytics Dashboard Section
 *
 * Included by dashboard.php. Shows real WooCommerce performance data
 * for BOGO campaigns. All data comes from GT_BOGO_Analytics class.
 *
 * @package GT_BOGO_Engine
 * @since   3.10.1
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

if ( ! class_exists( 'GT_BOGO_Analytics' ) ) {
    return;
}

// ── Period selector ────────────────────────────────────────────────────────
$days = isset( $_GET['roi_days'] ) ? intval( $_GET['roi_days'] ) : 30;
if ( ! in_array( $days, array( 7, 30, 90 ), true ) ) {
    $days = 30;
}

// ── Data ───────────────────────────────────────────────────────────────────
$stats    = GT_BOGO_Analytics::get_roi_stats( $days );
$activity = GT_BOGO_Analytics::get_recent_activity( 8 );
$rules    = GT_BOGO_Analytics::get_active_rules_summary();
$trend    = GT_BOGO_Analytics::get_daily_trend( $days );

$has_data = $stats['total_bogo_orders'] > 0;

// Period label
$period_labels = array( 7 => 'Last 7 Days', 30 => 'Last 30 Days', 90 => 'Last 90 Days' );
$period_label  = $period_labels[ $days ];

// Current page URL for period links
$base_url = admin_url( 'admin.php?page=gt-bogo-dashboard' );
?>

<!-- ── Section Header ──────────────────────────────────────────────────── -->
<div style="display:flex;align-items:center;justify-content:space-between;margin:var(--gt-space-2xl) 0 var(--gt-space-lg);">
    <div>
        <h2 style="color:var(--gt-white);margin:0;font-size:22px;font-weight:700;">📊 Campaign Performance</h2>
        <p class="gt-text-soft gt-text-sm" style="margin:4px 0 0;">Real-time data from your WooCommerce orders</p>
    </div>
    <!-- Period Selector -->
    <div class="gt-flex" style="gap:var(--gt-space-xs);">
        <?php foreach ( array( 7, 30, 90 ) as $d ): ?>
        <a href="<?php echo esc_url( $base_url . '&roi_days=' . $d ); ?>"
           class="gt-btn gt-btn-sm <?php echo $days === $d ? 'gt-btn-primary' : 'gt-btn-secondary'; ?>">
            <?php echo esc_html( $period_labels[ $d ] ); ?>
        </a>
        <?php endforeach; ?>
    </div>
</div>

<!-- ── 6 Metric Cards ─────────────────────────────────────────────────── -->
<div class="gt-metrics-grid" style="grid-template-columns:repeat(3,1fr);margin-bottom:var(--gt-space-xl);">

    <div class="gt-metric-card gt-animate-in" style="--gt-metric-color:#22c55e;">
        <span class="gt-metric-icon">💰</span>
        <div class="gt-metric-label">Revenue Influenced</div>
        <div class="gt-metric-value" style="color:#22c55e;">
            <?php echo $has_data ? wp_kses_post( wc_price( $stats['revenue_influenced'] ) ) : '<span style="font-size:20px;opacity:.4">—</span>'; ?>
        </div>
        <div class="gt-metric-trend">Total value of BOGO orders — <?php echo esc_html( $period_label ); ?></div>
    </div>

    <div class="gt-metric-card gt-animate-in" style="--gt-metric-color:#f59e0b;">
        <span class="gt-metric-icon">🏷️</span>
        <div class="gt-metric-label">Discounts Granted</div>
        <div class="gt-metric-value" style="color:#f59e0b;">
            <?php echo $has_data ? wp_kses_post( wc_price( $stats['total_discounts'] ) ) : '<span style="font-size:20px;opacity:.4">—</span>'; ?>
        </div>
        <div class="gt-metric-trend">Total savings given to customers</div>
    </div>

    <div class="gt-metric-card gt-animate-in" style="--gt-metric-color:#3b82f6;">
        <span class="gt-metric-icon">🛒</span>
        <div class="gt-metric-label">BOGO Orders</div>
        <div class="gt-metric-value" style="color:#3b82f6;">
            <?php echo $has_data ? esc_html( number_format( $stats['total_bogo_orders'] ) ) : '—'; ?>
        </div>
        <div class="gt-metric-trend">
            <?php if ( $has_data ): ?>
            <?php echo esc_html( $stats['bogo_percentage'] ); ?>% of <?php echo esc_html( number_format( $stats['total_orders'] ) ); ?> total orders
            <?php else: ?>
            No BOGO orders recorded yet
            <?php endif; ?>
        </div>
    </div>

    <div class="gt-metric-card gt-animate-in" style="--gt-metric-color:#8b5cf6;">
        <span class="gt-metric-icon">📈</span>
        <div class="gt-metric-label">Avg Order Value (BOGO)</div>
        <div class="gt-metric-value" style="color:#8b5cf6;">
            <?php echo $has_data ? wp_kses_post( wc_price( $stats['avg_bogo_aov'] ) ) : '—'; ?>
        </div>
        <div class="gt-metric-trend">vs <?php echo $has_data ? wp_kses_post( wc_price( $stats['non_bogo_aov'] ) ) : '—'; ?> without BOGO</div>
    </div>

    <div class="gt-metric-card gt-animate-in" style="--gt-metric-color:<?php echo ( isset( $stats['aov_lift_pct'] ) && $stats['aov_lift_pct'] > 0 ) ? '#22c55e' : '#94a3b8'; ?>;">
        <span class="gt-metric-icon">🚀</span>
        <div class="gt-metric-label">AOV Lift</div>
        <div class="gt-metric-value" style="color:<?php echo ( isset( $stats['aov_lift_pct'] ) && $stats['aov_lift_pct'] > 0 ) ? '#22c55e' : '#94a3b8'; ?>;">
            <?php echo $has_data ? esc_html( ( $stats['aov_lift_pct'] > 0 ? '+' : '' ) . $stats['aov_lift_pct'] . '%' ) : '—'; ?>
        </div>
        <div class="gt-metric-trend">BOGO vs non-BOGO avg order value</div>
    </div>

    <div class="gt-metric-card gt-animate-in" style="--gt-metric-color:#ff0000;">
        <span class="gt-metric-icon">💵</span>
        <div class="gt-metric-label">Avg Discount / Order</div>
        <div class="gt-metric-value" style="color:#ff0000;">
            <?php echo $has_data ? wp_kses_post( wc_price( $stats['avg_discount_per_order'] ) ) : '—'; ?>
        </div>
        <div class="gt-metric-trend">Average savings per BOGO order</div>
    </div>

</div>

<!-- ── Revenue Trend Chart ─────────────────────────────────────────────── -->
<?php if ( $has_data && ! empty( $trend ) ): ?>
<div class="gt-card gt-animate-in" style="margin-bottom:var(--gt-space-xl);">
    <div class="gt-card-header">
        <h3 class="gt-card-title">📅 Revenue Trend — <?php echo esc_html( $period_label ); ?></h3>
    </div>
    <div style="position:relative;height:200px;padding:var(--gt-space-md) 0;">
        <canvas id="gtbogo-trend-chart" style="width:100%;height:100%;"></canvas>
    </div>
</div>
<script>
(function() {
    var ctx = document.getElementById('gtbogo-trend-chart');
    if (!ctx) return;
    var labels = <?php echo wp_json_encode( array_column( $trend, 'label' ) ); ?>;
    var revenue = <?php echo wp_json_encode( array_column( $trend, 'revenue' ) ); ?>;
    var discounts = <?php echo wp_json_encode( array_column( $trend, 'discounts' ) ); ?>;
    if (typeof Chart === 'undefined') {
        var s = document.createElement('script');
        s.src = 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js';
        s.onload = function() { renderChart(ctx, labels, revenue, discounts); };
        document.head.appendChild(s);
    } else {
        renderChart(ctx, labels, revenue, discounts);
    }
    function renderChart(ctx, labels, revenue, discounts) {
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: 'Revenue',
                        data: revenue,
                        backgroundColor: 'rgba(34,197,94,0.7)',
                        borderRadius: 4,
                        order: 2
                    },
                    {
                        label: 'Discounts',
                        data: discounts,
                        backgroundColor: 'rgba(245,158,11,0.7)',
                        borderRadius: 4,
                        order: 1
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { labels: { color: '#94a3b8', font: { size: 12 } } },
                    tooltip: {
                        callbacks: {
                            label: function(ctx) {
                                return ctx.dataset.label + ': $' + parseFloat(ctx.raw).toFixed(2);
                            }
                        }
                    }
                },
                scales: {
                    x: { ticks: { color: '#64748b', font: { size: 11 } }, grid: { color: 'rgba(148,163,184,0.08)' } },
                    y: {
                        ticks: {
                            color: '#64748b',
                            callback: function(v) { return '$' + v; }
                        },
                        grid: { color: 'rgba(148,163,184,0.08)' }
                    }
                }
            }
        });
    }
})();
</script>
<?php endif; ?>

<!-- ── Two-column: Recent Activity + Top Rules ─────────────────────────── -->
<div style="display:grid;grid-template-columns:1fr 1fr;gap:var(--gt-space-lg);margin-bottom:var(--gt-space-xl);">

    <!-- Recent BOGO Orders -->
    <div class="gt-card gt-animate-in">
        <div class="gt-card-header">
            <h3 class="gt-card-title">⚡ Recent BOGO Orders</h3>
        </div>
        <?php if ( ! empty( $activity ) ): ?>
        <div>
            <?php foreach ( $activity as $i => $a ): ?>
            <div style="display:flex;justify-content:space-between;align-items:center;padding:var(--gt-space-sm) 0;<?php echo $i < count( $activity ) - 1 ? 'border-bottom:1px solid rgba(148,163,184,0.08);' : ''; ?>">
                <div>
                    <div style="display:flex;align-items:center;gap:var(--gt-space-xs);">
                        <span style="color:var(--gt-white);font-weight:600;font-size:14px;">
                            <a href="<?php echo esc_url( admin_url( 'post.php?post=' . intval( $a['order_id'] ) . '&action=edit' ) ); ?>"
                               style="color:var(--gt-white);text-decoration:none;">
                                #<?php echo esc_html( (string) $a['order_id'] ); ?>
                            </a>
                        </span>
                        <span class="gt-badge <?php echo $a['status'] === 'completed' ? 'gt-badge-owned' : 'gt-badge-pro'; ?>" style="font-size:10px;">
                            <?php echo esc_html( $a['status'] ); ?>
                        </span>
                    </div>
                    <div class="gt-text-subtle" style="font-size:12px;margin-top:2px;">
                        <?php echo esc_html( $a['customer'] ); ?> · <?php echo esc_html( $a['time_ago'] ); ?>
                    </div>
                </div>
                <div style="text-align:right;">
                    <div style="color:#22c55e;font-weight:700;font-size:14px;"><?php echo wp_kses_post( wc_price( $a['total'] ) ); ?></div>
                    <?php if ( $a['discount'] > 0 ): ?>
                    <div style="color:#f59e0b;font-size:12px;">saved <?php echo wp_kses_post( wc_price( $a['discount'] ) ); ?></div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php else: ?>
        <div class="gt-text-center" style="padding:var(--gt-space-xl) 0;">
            <div style="font-size:40px;margin-bottom:var(--gt-space-sm);">🛒</div>
            <p class="gt-text-soft gt-text-sm" style="margin:0;">No BOGO orders yet.<br>Activate a rule or import a PRO Pack.</p>
        </div>
        <?php endif; ?>
    </div>

    <!-- Active Rules -->
    <div class="gt-card gt-animate-in">
        <div class="gt-card-header">
            <h3 class="gt-card-title">⚙️ Active Rules</h3>
            <a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=pro-rules' ) ); ?>" class="gt-btn gt-btn-secondary gt-btn-sm">Manage →</a>
        </div>
        <?php if ( ! empty( $rules ) ): ?>
        <div>
            <?php foreach ( $rules as $i => $rule ): ?>
            <div style="display:flex;justify-content:space-between;align-items:center;padding:var(--gt-space-sm) 0;<?php echo $i < count( $rules ) - 1 ? 'border-bottom:1px solid rgba(148,163,184,0.08);' : ''; ?>">
                <div>
                    <div style="color:var(--gt-white);font-size:14px;font-weight:600;"><?php echo esc_html( $rule['name'] ); ?></div>
                    <div class="gt-text-subtle" style="font-size:12px;margin-top:2px;"><?php echo esc_html( $rule['description'] ); ?></div>
                </div>
                <div style="text-align:right;">
                    <span class="gt-badge gt-badge-owned" style="font-size:10px;">Active</span>
                    <?php if ( $rule['uses'] > 0 ): ?>
                    <div class="gt-text-subtle" style="font-size:11px;margin-top:3px;"><?php echo esc_html( number_format( $rule['uses'] ) ); ?> uses</div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php else: ?>
        <div class="gt-text-center" style="padding:var(--gt-space-xl) 0;">
            <div style="font-size:40px;margin-bottom:var(--gt-space-sm);">📋</div>
            <p class="gt-text-soft gt-text-sm" style="margin:0 0 var(--gt-space-md);">No active rules yet.</p>
            <a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=pro-rules' ) ); ?>" class="gt-btn gt-btn-primary gt-btn-sm">Browse PRO Packs</a>
        </div>
        <?php endif; ?>
    </div>

</div>

<!-- ── Top Rules Performance ───────────────────────────────────────────── -->
<?php if ( $has_data && ! empty( $stats['top_rules'] ) ): ?>
<div class="gt-card gt-animate-in" style="margin-bottom:var(--gt-space-xl);">
    <div class="gt-card-header">
        <h3 class="gt-card-title">🏆 Top Performing Rules — <?php echo esc_html( $period_label ); ?></h3>
    </div>
    <div style="overflow-x:auto;">
        <table class="gt-table">
            <thead>
                <tr>
                    <th>Rule</th>
                    <th>Uses</th>
                    <th>Revenue</th>
                    <th>Discounts</th>
                    <th>Avg Order</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ( $stats['top_rules'] as $rule ): ?>
                <tr>
                    <td><strong><?php echo esc_html( $rule['rule_name'] ); ?></strong></td>
                    <td><?php echo esc_html( number_format( $rule['uses'] ) ); ?></td>
                    <td style="color:#22c55e;"><?php echo wp_kses_post( wc_price( $rule['revenue'] ) ); ?></td>
                    <td style="color:#f59e0b;"><?php echo wp_kses_post( wc_price( $rule['discounts'] ) ); ?></td>
                    <td><?php echo wp_kses_post( wc_price( $rule['avg_order'] ) ); ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- ── Empty State CTA ─────────────────────────────────────────────────── -->
<?php if ( ! $has_data ): ?>
<div class="gt-card gt-animate-in" style="text-align:center;padding:var(--gt-space-2xl);margin-bottom:var(--gt-space-xl);">
    <div style="font-size:56px;margin-bottom:var(--gt-space-md);">📊</div>
    <h3 style="color:var(--gt-white);margin:0 0 var(--gt-space-sm);">No Campaign Data Yet</h3>
    <p class="gt-text-soft" style="margin:0 0 var(--gt-space-xl);max-width:500px;margin-left:auto;margin-right:auto;">
        Once customers place orders with active BOGO rules, your performance data will appear here automatically. 
        Start by importing a PRO Pack or creating a rule.
    </p>
    <div class="gt-flex" style="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">Browse PRO Packs</a>
        <a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-free-rule' ) ); ?>" class="gt-btn gt-btn-secondary">Create Free Rule</a>
    </div>
</div>
<?php endif; ?>
