<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /templates/dashboard.php
// Description: Dashboard tab — business metrics, channel health, charts, top post — NUCLEAR+++
// Last Edited: 2026-04-22
// ==================================================
if (!defined('ABSPATH')) {
    exit;
}

// ── Local DB metrics ──────────────────────────────────────────────────
global $wpdb;
$now_utc      = gmdate('Y-m-d H:i:s');
$today        = gmdate('Y-m-d');
$mtd_start    = gmdate('Y-m-') . '01 00:00:00';
$last30_start = gmdate('Y-m-d', strtotime('-29 days')) . ' 00:00:00';

// MTD posts published
$posts_mtd = (int) $wpdb->get_var($wpdb->prepare(
    "SELECT COUNT(*) FROM {$wpdb->prefix}amai_scheduled_posts
     WHERE status = 'posted' AND scheduled_utc >= %s",
    $mtd_start
));

// Last 30 days posts published
$posts_30d = (int) $wpdb->get_var($wpdb->prepare(
    "SELECT COUNT(*) FROM {$wpdb->prefix}amai_scheduled_posts
     WHERE status = 'posted' AND scheduled_utc >= %s",
    $last30_start
));

// Posts by day for last 30 days (for chart)
$daily_rows = $wpdb->get_results($wpdb->prepare(
    "SELECT DATE(scheduled_utc) AS day, COUNT(*) AS cnt
     FROM {$wpdb->prefix}amai_scheduled_posts
     WHERE status = 'posted' AND scheduled_utc >= %s
     GROUP BY DATE(scheduled_utc)
     ORDER BY day ASC",
    $last30_start
), ARRAY_A);

$daily_map = [];
foreach ((array) $daily_rows as $row) {
    if (is_array($row) && isset($row['day'], $row['cnt'])) {
        $daily_map[(string) $row['day']] = (int) $row['cnt'];
    }
}

// Build 30-day array (all days, zero-fill gaps)
$chart_days   = [];
$chart_counts = [];
for ($i = 29; $i >= 0; $i--) {
    $d              = gmdate('Y-m-d', strtotime("-{$i} days"));
    $chart_days[]   = gmdate('M j', strtotime($d));
    $chart_counts[] = $daily_map[$d] ?? 0;
}

// Pending approval
$pending_approval = (int) $wpdb->get_var(
    "SELECT COUNT(*) FROM {$wpdb->prefix}amai_scheduled_posts WHERE status = 'draft'"
);

// Next scheduled post
$next_post = $wpdb->get_row($wpdb->prepare(
    "SELECT channel, scheduled_utc FROM {$wpdb->prefix}amai_scheduled_posts
     WHERE status = 'approved' AND scheduled_utc > %s
     ORDER BY scheduled_utc ASC LIMIT 1",
    $now_utc
), ARRAY_A);

$next_post_label   = 'None scheduled';
$next_post_channel = '';
if ($next_post !== null && is_array($next_post)) {
    $diff = strtotime((string) $next_post['scheduled_utc']) - time();
    if ($diff < 3600) {
        $next_post_label = 'Under 1 hour';
    } elseif ($diff < 86400) {
        $next_post_label = 'Today';
    } elseif ($diff < 172800) {
        $next_post_label = 'Tomorrow';
    } else {
        $next_post_label = gmdate('D, M j', strtotime((string) $next_post['scheduled_utc']));
    }
    $next_post_channel = ucfirst((string) ($next_post['channel'] ?? ''));
}

// Posting streak — consecutive days with at least one posted post up to today
$streak        = 0;
$streak_date   = gmdate('Y-m-d');
$streak_limit  = 90;
for ($i = 0; $i < $streak_limit; $i++) {
    $check = gmdate('Y-m-d', strtotime("-{$i} days"));
    $cnt   = (int) $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM {$wpdb->prefix}amai_scheduled_posts
         WHERE status = 'posted' AND DATE(scheduled_utc) = %s",
        $check
    ));
    if ($cnt > 0) {
        $streak++;
    } else {
        break;
    }
}

// Top performing post this month (by engagement score: likes + comments*3 + reach*0.01)
$top_post = $wpdb->get_row($wpdb->prepare(
    "SELECT id, channel, post_type, post_content AS content, scheduled_utc,
            stat_likes, stat_comments, stat_reach,
            (COALESCE(stat_likes,0) + COALESCE(stat_comments,0)*3 + COALESCE(stat_reach,0)*0.01) AS score
     FROM {$wpdb->prefix}amai_scheduled_posts
     WHERE status = 'posted' AND scheduled_utc >= %s
       AND (stat_likes IS NOT NULL OR stat_comments IS NOT NULL OR stat_reach IS NOT NULL)
     ORDER BY score DESC
     LIMIT 1",
    $mtd_start
), ARRAY_A);

// Posts by channel for engagement chart (last 30 days)
$channel_engagement = $wpdb->get_results($wpdb->prepare(
    "SELECT channel,
            SUM(COALESCE(stat_likes,0) + COALESCE(stat_comments,0)*3 + COALESCE(stat_reach,0)*0.01) AS score,
            COUNT(*) AS post_count
     FROM {$wpdb->prefix}amai_scheduled_posts
     WHERE status = 'posted' AND scheduled_utc >= %s
     GROUP BY channel
     ORDER BY score DESC",
    $last30_start
), ARRAY_A);

// ── Channel health ────────────────────────────────────────────────────
$channels = [];

// Facebook
$fb_conn = \AutoMarketerAI\FacebookAuth::getConnection();
if ($fb_conn !== null) {
    $expires    = isset($fb_conn['token_expires_at']) ? strtotime((string) $fb_conn['token_expires_at']) : null;
    $days_left  = $expires ? (int) ceil(($expires - time()) / 86400) : null;
    $health     = ($days_left === null || $days_left > 7) ? 'good' : ($days_left > 0 ? 'warning' : 'expired');
    $channels[] = [
        'name'      => 'Facebook',
        'page_name' => esc_html((string) ($fb_conn['page_name'] ?? '')),
        'health'    => $health,
        'days_left' => $days_left,
        'url'       => admin_url('admin.php?page=automarketer-ai-social&channel=facebook'),
    ];
}

// Instagram
$ig_id = \AutoMarketerAI\FacebookAuth::getInstagramAccountId();
if ($ig_id !== null) {
    // Instagram token is tied to Facebook token — same expiry
    $ig_health  = isset($channels[0]) ? $channels[0]['health'] : 'good';
    $ig_days    = isset($channels[0]) ? $channels[0]['days_left'] : null;
    $channels[] = [
        'name'      => 'Instagram',
        'page_name' => '',
        'health'    => $ig_health,
        'days_left' => $ig_days,
        'url'       => admin_url('admin.php?page=automarketer-ai-social&channel=instagram'),
    ];
}

// X
$x_conn = \AutoMarketerAI\XAuth::getConnection();
if ($x_conn !== null) {
    $x_status  = $x_conn['status'] ?? 'error';
    $health    = $x_status === 'active' ? 'good' : ($x_status === 'revoked' ? 'expired' : 'warning');
    $channels[] = [
        'name'      => 'X',
        'page_name' => '',
        'health'    => $health,
        'days_left' => null,
        'url'       => admin_url('admin.php?page=automarketer-ai-social&channel=x'),
    ];
}

// TikTok
$tk_conn = get_option('amai_tiktok_connection', null);
if (!empty($tk_conn) && is_array($tk_conn)) {
    $expires    = isset($tk_conn['token_expires_at']) ? strtotime((string) $tk_conn['token_expires_at']) : null;
    $days_left  = $expires ? (int) ceil(($expires - time()) / 86400) : null;
    $health     = ($days_left === null || $days_left > 1) ? 'good' : ($days_left > 0 ? 'warning' : 'expired');
    $channels[] = [
        'name'      => 'TikTok',
        'page_name' => '',
        'health'    => $health,
        'days_left' => $days_left,
        'url'       => admin_url('admin.php?page=automarketer-ai-social&channel=tiktok'),
    ];
}

// LinkedIn
$li_conn = get_option('amai_linkedin_connection', null);
if (!empty($li_conn) && is_array($li_conn)) {
    $expires    = isset($li_conn['token_expires_at']) ? strtotime((string) $li_conn['token_expires_at']) : null;
    $days_left  = $expires ? (int) ceil(($expires - time()) / 86400) : null;
    $health     = ($days_left === null || $days_left > 7) ? 'good' : ($days_left > 0 ? 'warning' : 'expired');
    $channels[] = [
        'name'      => 'LinkedIn',
        'page_name' => '',
        'health'    => $health,
        'days_left' => $days_left,
        'url'       => admin_url('admin.php?page=automarketer-ai-social&channel=linkedin'),
    ];
}

// Google Business
$google_conn = $wpdb->get_row(
    "SELECT status, token_expires_at, business_name FROM {$wpdb->prefix}amai_google_connection LIMIT 1",
    ARRAY_A
);
if ($google_conn !== null && ($google_conn['status'] ?? '') === 'connected') {
    $expires    = isset($google_conn['token_expires_at']) ? strtotime((string) $google_conn['token_expires_at']) : null;
    $days_left  = $expires ? (int) ceil(($expires - time()) / 86400) : null;
    $health     = ($days_left === null || $days_left > 1) ? 'good' : ($days_left > 0 ? 'warning' : 'expired');
    $channels[] = [
        'name'      => 'Google',
        'page_name' => esc_html((string) ($google_conn['business_name'] ?? '')),
        'health'    => $health,
        'days_left' => $days_left,
        'url'       => admin_url('admin.php?page=automarketer-ai-social&channel=google'),
    ];
}

$connected_count = count($channels);

// ── Plan data from wp_options (shown immediately; Stripe data loaded async) ──
$plan_slug   = get_option('automarketer_ai_plan_id', 'free');
$sub_id      = get_option('automarketer_ai_stripe_sub_id', '');
$cust_id     = get_option('automarketer_ai_stripe_customer_id', '');
$plan_labels = [
    'free'         => 'Free Plan',
    'starter'      => 'Starter',
    'starter_pro'  => 'Starter Pro',
    'unlimited_ai' => 'Unlimited AI',
    'agency'       => 'Agency',
];
$plan_label  = $plan_labels[$plan_slug] ?? ucfirst($plan_slug);
$has_stripe  = ($sub_id !== '' || $cust_id !== '');

// ── AI provider label ─────────────────────────────────────────────────
$active_modules    = (array) get_option('amai_active_modules', []);
$active_ai_label   = 'None';
$ai_provider_names = [
    'ai-claude'   => 'Claude',
    'ai-openai'   => 'OpenAI',
    'ai-gemini'   => 'Gemini',
    'ai-grok'     => 'Grok',
    'ai-mistral'  => 'Mistral',
];
foreach ($active_modules as $mod) {
    if (is_string($mod) && isset($ai_provider_names[$mod])) {
        $active_ai_label = $ai_provider_names[$mod];
        break;
    }
}
?>
<!-- ── Page header ───────────────────────────────────────────────── -->
<div id="amai-dash-header">
    <div class="amai-dash-title">Dashboard</div>
    <p class="amai-dash-sub">How your business is doing this month</p>
    <?php include AMAI_PLUGIN_DIR . 'templates/partials/tabs.php'; ?>
</div>

<div id="amai-dashboard">

    <!-- ── Profile completion nudge ─────────────────────────── -->
    <?php
    $nudge_engine = \AutoMarketerAI\NudgeEngine::init();
    $nudge_key    = $nudge_engine->getActiveNudge();
    if ($nudge_key !== null) {
        include AMAI_PLUGIN_DIR . 'templates/partials/nudge-card.php';
    }
    ?>

    <!-- ── Comment inbox notice ──────────────────────────── -->
    <?php
    $amai_comment_plan = (string) get_option('automarketer_ai_plan_id', 'free');
    if ($amai_comment_plan !== 'free') {
        global $wpdb;
        $amai_comment_table  = $wpdb->prefix . 'amai_social_comments';
        $amai_unread_total   = (int) $wpdb->get_var("SELECT COUNT(*) FROM `{$amai_comment_table}` WHERE status IN ('new','pending_review')");
        if ($amai_unread_total > 0) {
    ?>
    <div class="amai-dash-comment-notice">
        <div class="amai-dash-comment-notice-left">
            <div class="amai-dash-comment-notice-icon">
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M2 4a2 2 0 012-2h12a2 2 0 012 2v8a2 2 0 01-2 2H6l-4 4V4z" fill="#D97757" opacity=".15"/><path d="M2 4a2 2 0 012-2h12a2 2 0 012 2v8a2 2 0 01-2 2H6l-4 4V4z" stroke="#D97757" stroke-width="1.6" stroke-linejoin="round"/></svg>
            </div>
            <div>
                <div class="amai-dash-comment-notice-title">
                    <?php echo esc_html((string) $amai_unread_total); ?> unread comment<?php echo $amai_unread_total !== 1 ? 's' : ''; ?> waiting
                </div>
                <div class="amai-dash-comment-notice-sub">Reply from your comment inbox to keep the conversation going.</div>
            </div>
        </div>
        <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-comments')); ?>" class="amai-dash-comment-notice-btn">
            Open Inbox
        </a>
    </div>
    <?php
        }
    }
    ?>
    <!-- ── Revenue + plan hero ───────────────────────────────────── -->
    <div class="amai-dash-hero">
        <div class="amai-dash-hero-left">
            <div class="amai-dash-mrr-label">Monthly Revenue</div>
            <div class="amai-dash-mrr" id="amai-mrr-value">
                <?php if ($has_stripe): ?>
                    <span class="amai-mrr-loading">Loading...</span>
                <?php else: ?>
                    <span class="amai-mrr-free">Free Plan</span>
                <?php endif; ?>
            </div>
            <div class="amai-dash-mrr-meta" id="amai-mrr-meta">
                <?php if ($has_stripe): ?>
                    <span class="amai-mrr-loading-meta">Fetching billing data...</span>
                <?php else: ?>
                    No active subscription
                <?php endif; ?>
            </div>
        </div>
        <div class="amai-dash-hero-right">
            <div class="amai-dash-plan-badge">
                <span class="amai-plan-dot"></span>
                <?php echo esc_html($plan_label); ?>
            </div>
            <?php if ($has_stripe): ?>
                <div class="amai-dash-next-bill" id="amai-next-bill">Next billing date: <span>--</span></div>
            <?php endif; ?>
            <div class="amai-dash-member-since" id="amai-member-since"></div>
        </div>
    </div>

    <!-- ── Stat cards ────────────────────────────────────────────── -->
    <div class="amai-dash-cards">

        <div class="amai-dash-card">
            <div class="amai-dash-card-icon amai-dash-card-icon--posts">
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><path d="M3 5h14M3 10h14M3 15h8" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>
            </div>
            <div class="amai-dash-card-body">
                <div class="amai-dash-card-num"><?php echo esc_html((string) $posts_mtd); ?></div>
                <div class="amai-dash-card-label">Posts published this month</div>
                <div class="amai-dash-card-sub"><?php echo esc_html((string) $posts_30d); ?> in the past 30 days</div>
            </div>
        </div>

        <div class="amai-dash-card">
            <div class="amai-dash-card-icon amai-dash-card-icon--channels">
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><circle cx="10" cy="10" r="7" stroke="currentColor" stroke-width="1.6"/><path d="M10 3c-2 2-3 4-3 7s1 5 3 7M10 3c2 2 3 4 3 7s-1 5-3 7M3 10h14" stroke="currentColor" stroke-width="1.3"/></svg>
            </div>
            <div class="amai-dash-card-body">
                <div class="amai-dash-card-num"><?php echo esc_html((string) $connected_count); ?></div>
                <div class="amai-dash-card-label">Active channel<?php echo $connected_count === 1 ? '' : 's'; ?></div>
                <div class="amai-dash-card-sub">Powered by <?php echo esc_html($active_ai_label); ?></div>
            </div>
        </div>

        <div class="amai-dash-card">
            <div class="amai-dash-card-icon amai-dash-card-icon--pending">
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><circle cx="10" cy="10" r="7" stroke="currentColor" stroke-width="1.6"/><path d="M10 6v4l3 2" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>
            </div>
            <div class="amai-dash-card-body">
                <div class="amai-dash-card-num"><?php echo esc_html((string) $pending_approval); ?></div>
                <div class="amai-dash-card-label">Ready to review</div>
                <?php if ($pending_approval > 0): ?>
                    <a class="amai-dash-card-sub amai-dash-card-sub--link" href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-social&channel=facebook')); ?>">Review posts →</a>
                <?php else: ?>
                    <div class="amai-dash-card-sub">All clear</div>
                <?php endif; ?>
            </div>
        </div>

        <div class="amai-dash-card">
            <div class="amai-dash-card-icon amai-dash-card-icon--streak">
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><path d="M10 2c0 4-4 5-4 9a4 4 0 008 0c0-4-4-5-4-9z" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/><path d="M10 13a1.5 1.5 0 100-3 1.5 1.5 0 000 3z" fill="currentColor"/></svg>
            </div>
            <div class="amai-dash-card-body">
                <div class="amai-dash-card-num"><?php echo esc_html((string) $streak); ?></div>
                <div class="amai-dash-card-label">Day streak</div>
                <div class="amai-dash-card-sub"><?php echo $streak >= 7 ? 'Killing it.' : ($streak > 0 ? 'Keep it going.' : 'No posts today yet.'); ?></div>
            </div>
        </div>

        <div class="amai-dash-card">
            <div class="amai-dash-card-icon amai-dash-card-icon--next">
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><rect x="3" y="4" width="14" height="13" rx="2" stroke="currentColor" stroke-width="1.6"/><path d="M3 8h14M7 2v3M13 2v3" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>
            </div>
            <div class="amai-dash-card-body">
                <div class="amai-dash-card-num amai-dash-card-num--sm"><?php echo esc_html($next_post_label); ?></div>
                <div class="amai-dash-card-label">Up next</div>
                <div class="amai-dash-card-sub"><?php echo $next_post_channel !== '' ? esc_html($next_post_channel) : 'Nothing queued yet'; ?></div>
            </div>
        </div>

    </div>

    <!-- ── Channel health ────────────────────────────────────────── -->
    <?php if (!empty($channels)): ?>
    <div class="amai-dash-section">
        <div class="amai-dash-section-title">Channel Health</div>
        <div class="amai-dash-health-strip">
            <?php foreach ($channels as $ch):
                $health_class = 'amai-health--' . $ch['health'];
                $health_label = match($ch['health']) {
                    'warning' => 'Expires in ' . $ch['days_left'] . 'd',
                    'expired' => 'Token expired',
                    default   => 'Connected',
                };
            ?>
            <a class="amai-dash-health-pill <?php echo esc_attr($health_class); ?>" href="<?php echo esc_url($ch['url']); ?>">
                <span class="amai-health-dot"></span>
                <span class="amai-health-name"><?php echo esc_html($ch['name']); ?></span>
                <?php if ($ch['page_name'] !== ''): ?>
                    <span class="amai-health-page"><?php echo esc_html($ch['page_name']); ?></span>
                <?php endif; ?>
                <span class="amai-health-status"><?php echo esc_html($health_label); ?></span>
            </a>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- ── Charts ────────────────────────────────────────────────── -->
    <div class="amai-dash-charts">

        <div class="amai-dash-chart-box">
            <div class="amai-dash-chart-title">Posts Going Out <span class="amai-dash-chart-period">Last 30 days</span></div>
            <div class="amai-dash-chart-wrap" id="amai-chart-posts" aria-label="Posts published over last 30 days">
                <?php if ($posts_30d === 0): ?>
                    <div class="amai-dash-chart-empty">No posts published yet this period.</div>
                <?php endif; ?>
            </div>
        </div>

        <div class="amai-dash-chart-box">
            <div class="amai-dash-chart-title">Which channels are working <span class="amai-dash-chart-period">Last 30 days</span></div>
            <div class="amai-dash-chart-wrap" id="amai-chart-channels" aria-label="Engagement by channel">
                <?php if (empty($channel_engagement)): ?>
                    <div class="amai-dash-chart-empty">Engagement data will appear once posts have stats.</div>
                <?php endif; ?>
            </div>
        </div>

    </div>

    <!-- ── Top performing post ───────────────────────────────────── -->
    <?php if ($top_post !== null && is_array($top_post)): ?>
    <div class="amai-dash-section">
        <div class="amai-dash-section-title">Your best post this month</div>
        <div class="amai-dash-top-post">
            <div class="amai-dash-top-post-meta">
                <span class="amai-dash-top-channel"><?php echo esc_html(ucfirst((string) ($top_post['channel'] ?? ''))); ?></span>
                <span class="amai-dash-top-type"><?php echo esc_html(str_replace('_', ' ', (string) ($top_post['post_type'] ?? ''))); ?></span>
                <span class="amai-dash-top-date"><?php echo esc_html(gmdate('M j', strtotime((string) ($top_post['scheduled_utc'] ?? 'now')))); ?></span>
            </div>
            <div class="amai-dash-top-post-content">
                <?php
                $content = (string) ($top_post['content'] ?? '');
                echo esc_html(mb_strlen($content) > 280 ? mb_substr($content, 0, 277) . '...' : $content);
                ?>
            </div>
            <div class="amai-dash-top-post-stats">
                <?php if (isset($top_post['stat_likes']) && $top_post['stat_likes'] !== null): ?>
                    <span class="amai-top-stat"><strong><?php echo esc_html((string) $top_post['stat_likes']); ?></strong> likes</span>
                <?php endif; ?>
                <?php if (isset($top_post['stat_comments']) && $top_post['stat_comments'] !== null): ?>
                    <span class="amai-top-stat"><strong><?php echo esc_html((string) $top_post['stat_comments']); ?></strong> comments</span>
                <?php endif; ?>
                <?php if (isset($top_post['stat_reach']) && $top_post['stat_reach'] !== null): ?>
                    <span class="amai-top-stat"><strong><?php echo esc_html(number_format((int) $top_post['stat_reach'])); ?></strong> reach</span>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- ── AI cost placeholder ───────────────────────────────────── -->
    <div class="amai-dash-section amai-dash-section--coming">
        <div class="amai-dash-section-title">AI Spend <span class="amai-dash-badge-coming">Coming Soon</span></div>
        <div class="amai-dash-coming-text">We'll show you what your AI is costing you once tracking is set up.</div>
    </div>

</div><!-- /#amai-dashboard -->

<?php
// Pass chart data to JS
$chart_data = [
    'days'              => $chart_days,
    'counts'            => $chart_counts,
    'channelEngagement' => array_values((array) $channel_engagement),
    'hasStripe'         => $has_stripe,
    'mrrOverride'       => get_option('amai_mrr_override', null),
    'subId'             => $sub_id,
    'custId'            => $cust_id,
    'ajaxUrl'           => admin_url('admin-ajax.php'),
    'nonce'             => wp_create_nonce('amai_dashboard_subscription'),
];
?>
<script>
window.amaiDashData = <?php echo wp_json_encode($chart_data); ?>;
</script>