<?php
/**
 * View: Main Analytics Dashboard with Advanced Filters (Premium UI)
 */

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

global $wpdb;

// Table names
$pexemail_table_contacts   = $wpdb->prefix . 'pexemail_contacts';
$pexemail_table_recipients = $wpdb->prefix . 'pexemail_recipients';
$pexemail_table_campaigns  = $wpdb->prefix . 'pexemail_campaigns';

// Fetch all campaigns for the dropdown filter
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$pexemail_all_campaigns = $wpdb->get_results( "SELECT id, subject FROM {$wpdb->prefix}pexemail_campaigns ORDER BY id DESC" );

// --- Filter Capture ---
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$pexemail_filter_campaign = isset( $_GET['filter_campaign'] ) ? intval( $_GET['filter_campaign'] ) : 0;
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$pexemail_filter_month    = isset( $_GET['filter_month'] ) ? sanitize_text_field( wp_unslash( $_GET['filter_month'] ) ) : '';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$pexemail_filter_start    = isset( $_GET['filter_start'] ) ? sanitize_text_field( wp_unslash( $_GET['filter_start'] ) ) : '';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$pexemail_filter_end      = isset( $_GET['filter_end'] ) ? sanitize_text_field( wp_unslash( $_GET['filter_end'] ) ) : '';

// --- Dynamic SQL WHERE Builder ---
$pexemail_where_c    = [ "1=1" ];
$pexemail_where_args = [];

if ( $pexemail_filter_campaign > 0 ) {
    $pexemail_where_c[]    = "c.id = %d";
    $pexemail_where_args[] = $pexemail_filter_campaign;
}
if ( ! empty( $pexemail_filter_month ) ) {
    $pexemail_where_c[]    = "c.created_at LIKE %s";
    $pexemail_where_args[] = $wpdb->esc_like( $pexemail_filter_month ) . '%';
}
if ( ! empty( $pexemail_filter_start ) ) {
    $pexemail_where_c[]    = "c.created_at >= %s";
    $pexemail_where_args[] = $pexemail_filter_start . ' 00:00:00';
}
if ( ! empty( $pexemail_filter_end ) ) {
    $pexemail_where_c[]    = "c.created_at <= %s";
    $pexemail_where_args[] = $pexemail_filter_end . ' 23:59:59';
}

$pexemail_where_sql = implode( ' AND ', $pexemail_where_c );

// --- 1. Calculate Dynamic Global Metrics ---

// 1A. Get Total Sent (from the recipients table)
if ( empty( $pexemail_where_args ) ) {
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
    $pexemail_total_sent = $wpdb->get_var( "SELECT COUNT(r.id) FROM {$wpdb->prefix}pexemail_recipients r JOIN {$wpdb->prefix}pexemail_campaigns c ON r.campaign_id = c.id WHERE r.status = 'sent' AND " . $pexemail_where_sql );
} else {
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
    $pexemail_total_sent = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(r.id) FROM {$wpdb->prefix}pexemail_recipients r JOIN {$wpdb->prefix}pexemail_campaigns c ON r.campaign_id = c.id WHERE r.status = 'sent' AND " . $pexemail_where_sql, $pexemail_where_args ) );
}
$pexemail_total_sent = $pexemail_total_sent ? $pexemail_total_sent : 0;


// FIX: Force Top Scorecards to use Ground Truth (Unique Recipients) instead of Gross Campagin cache
if ( empty( $pexemail_where_args ) ) {
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
    $pexemail_total_opened  = $wpdb->get_var( "SELECT COUNT(r.id) FROM {$wpdb->prefix}pexemail_recipients r JOIN {$wpdb->prefix}pexemail_campaigns c ON r.campaign_id = c.id WHERE r.opened = 1 AND " . $pexemail_where_sql );
    
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
    $pexemail_total_clicked = $wpdb->get_var( "SELECT COUNT(r.id) FROM {$wpdb->prefix}pexemail_recipients r JOIN {$wpdb->prefix}pexemail_campaigns c ON r.campaign_id = c.id WHERE r.clicked = 1 AND " . $pexemail_where_sql );
} else {
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
    $pexemail_total_opened  = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(r.id) FROM {$wpdb->prefix}pexemail_recipients r JOIN {$wpdb->prefix}pexemail_campaigns c ON r.campaign_id = c.id WHERE r.opened = 1 AND " . $pexemail_where_sql, $pexemail_where_args ) );
    
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
    $pexemail_total_clicked = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(r.id) FROM {$wpdb->prefix}pexemail_recipients r JOIN {$wpdb->prefix}pexemail_campaigns c ON r.campaign_id = c.id WHERE r.clicked = 1 AND " . $pexemail_where_sql, $pexemail_where_args ) );
}

$pexemail_total_opened  = $pexemail_total_opened ? $pexemail_total_opened : 0;
$pexemail_total_clicked = $pexemail_total_clicked ? $pexemail_total_clicked : 0;

$pexemail_open_rate  = ( $pexemail_total_sent > 0 ) ? round( ( $pexemail_total_opened / $pexemail_total_sent ) * 100, 1 ) : 0;
$pexemail_click_rate = ( $pexemail_total_opened > 0 ) ? round( ( $pexemail_total_clicked / $pexemail_total_opened ) * 100, 1 ) : 0;

// Dynamic Contacts Metric (Global vs Filtered)
if ( $pexemail_filter_campaign > 0 || ! empty( $pexemail_filter_month ) || ! empty( $pexemail_filter_start ) || ! empty( $pexemail_filter_end ) ) {
    if ( empty( $pexemail_where_args ) ) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $pexemail_total_contacts = $wpdb->get_var( "SELECT COUNT(r.id) FROM {$wpdb->prefix}pexemail_recipients r JOIN {$wpdb->prefix}pexemail_campaigns c ON r.campaign_id = c.id WHERE " . $pexemail_where_sql );
    } else {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
        $pexemail_total_contacts = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(r.id) FROM {$wpdb->prefix}pexemail_recipients r JOIN {$wpdb->prefix}pexemail_campaigns c ON r.campaign_id = c.id WHERE " . $pexemail_where_sql, $pexemail_where_args ) );
    }
    $pexemail_contact_label  = esc_html__( 'Targeted Recipients', 'pexally-email-campaigns' );
} else {
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $pexemail_total_contacts = $wpdb->get_var( "SELECT COUNT(id) FROM {$wpdb->prefix}pexemail_contacts WHERE status = 'subscribed'" );
    $pexemail_contact_label  = esc_html__( 'Active Subscribers', 'pexally-email-campaigns' );
}

// --- 2. Fetch Data for the Interactive Chart ---
$pexemail_chart_labels  = [];
$pexemail_chart_sent    = [];
$pexemail_chart_opened  = [];
$pexemail_chart_clicked = [];

if ( empty( $pexemail_where_args ) ) {
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
    $pexemail_recent_campaigns = $wpdb->get_results( "SELECT id, subject FROM {$wpdb->prefix}pexemail_campaigns c WHERE c.status = 'completed' AND " . $pexemail_where_sql . " ORDER BY c.id DESC LIMIT 5" );
} else {
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
    $pexemail_recent_campaigns = $wpdb->get_results( $wpdb->prepare( "SELECT id, subject FROM {$wpdb->prefix}pexemail_campaigns c WHERE c.status = 'completed' AND " . $pexemail_where_sql . " ORDER BY c.id DESC LIMIT 5", $pexemail_where_args ) );
}

if ( $pexemail_recent_campaigns ) {
    $pexemail_recent_campaigns = array_reverse( $pexemail_recent_campaigns ); // Oldest left, newest right
    foreach ( $pexemail_recent_campaigns as $pexemail_camp ) {
        $pexemail_short_subject = mb_strlen( stripslashes($pexemail_camp->subject) ) > 20 ? mb_substr( stripslashes($pexemail_camp->subject), 0, 20 ) . '...' : stripslashes($pexemail_camp->subject);
        $pexemail_chart_labels[] = $pexemail_short_subject;
        
        // FIX: Also force the chart to use ground truth unique recipients tracking
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $pexemail_c_sent    = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(id) FROM {$wpdb->prefix}pexemail_recipients WHERE campaign_id = %d AND status = 'sent'", $pexemail_camp->id ) );
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $pexemail_c_opened  = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(id) FROM {$wpdb->prefix}pexemail_recipients WHERE campaign_id = %d AND opened = 1", $pexemail_camp->id ) );
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $pexemail_c_clicked = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(id) FROM {$wpdb->prefix}pexemail_recipients WHERE campaign_id = %d AND clicked = 1", $pexemail_camp->id ) );
        
        $pexemail_chart_sent[]    = $pexemail_c_sent ? $pexemail_c_sent : 0;
        $pexemail_chart_opened[]  = $pexemail_c_opened ? $pexemail_c_opened : 0;
        $pexemail_chart_clicked[] = $pexemail_c_clicked ? $pexemail_c_clicked : 0;
    }
}
?>

<style>
    /* Global Reset & Typography */
    .pex-premium-wrap { 
        max-width: 1400px; /* Allows the dashboard to stretch nicely without breaking */
        margin: 25px 0 0 0; /* Strictly Left-Aligned in WP Admin */
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; 
        color: #334155; 
    }
    
    /* Hero Section (Brand Green - Enhanced) */
    .pex-hero { 
        background: linear-gradient(135deg, #0f5132 0%, #064e3b 100%); /* Deep, vibrant brand green */
        color: #fff; 
        padding: 45px 50px; 
        border-radius: 16px; 
        margin-bottom: 35px; 
        box-shadow: 0 15px 35px -5px rgba(6, 78, 59, 0.3), inset 0 1px 0 rgba(255,255,255,0.1); 
        display: flex; 
        align-items: center; 
        justify-content: space-between;
        position: relative;
        overflow: hidden;
    }
    .pex-hero::after {
        content: '';
        position: absolute;
        top: 0; right: 0; bottom: 0; left: 0;
        background: url('data:image/svg+xml;utf8,<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="40" fill="rgba(255,255,255,0.03)"/></svg>') repeat;
        opacity: 0.8;
        pointer-events: none;
    }
    .pex-hero-text { position: relative; z-index: 2; }
    .pex-hero h1 { color: #fff; margin: 0 0 10px 0; font-size: 30px; font-weight: 800; letter-spacing: -0.5px; text-shadow: 0 2px 4px rgba(0,0,0,0.1); }
    .pex-hero p { margin: 0; font-size: 16px; color: #d1fae5; line-height: 1.6; max-width: 600px; font-weight: 400; }
    
    .pex-btn-white { 
        position: relative; 
        z-index: 2;
        background: #ffffff; 
        color: #064e3b; 
        padding: 14px 28px; 
        border-radius: 30px; 
        font-weight: 700; 
        font-size: 15px;
        text-decoration: none; 
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1); 
        transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1); 
        display: inline-flex; 
        align-items: center;
        gap: 8px;
    }
    .pex-btn-white:hover { 
        background: #f8fafc; 
        color: #047857; 
        transform: translateY(-2px); 
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15); 
    }

    /* Advanced Filter Bar */
    .pex-filter-card { 
        background: #ffffff; 
        padding: 24px 28px; 
        border-radius: 16px; 
        border: 1px solid #eef2f6; 
        margin-bottom: 35px; 
        display: flex; 
        flex-wrap: wrap; 
        gap: 20px; 
        align-items: flex-end; 
        box-shadow: 0 4px 6px -1px rgba(15, 23, 42, 0.02), 0 2px 4px -1px rgba(15, 23, 42, 0.02); 
    }
    .pex-filter-group { display: flex; flex-direction: column; gap: 8px; flex: 1; min-width: 170px; }
    .pex-filter-group label { font-size: 12px; font-weight: 700; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; }
    .pex-filter-input { 
        padding: 12px 16px; 
        border: 1px solid #cbd5e1; 
        border-radius: 10px; 
        font-size: 14px; 
        outline: none; 
        transition: all 0.2s; 
        background: #f8fafc; 
        color: #334155;
        box-shadow: inset 0 1px 2px rgba(0,0,0,0.01);
    }
    .pex-filter-input:focus { 
        border-color: #10b981; 
        background: #ffffff;
        box-shadow: 0 0 0 4px rgba(16, 185, 129, 0.15); 
    }
    .pex-filter-actions { display: flex; gap: 12px; flex-wrap: wrap; }
    .pex-btn-apply { 
        background: #0f172a; color: white; border: none; padding: 0 28px; border-radius: 10px; 
        cursor: pointer; font-weight: 600; font-size: 14px; transition: all 0.2s; height: 44px; 
        box-shadow: 0 2px 4px rgba(15, 23, 42, 0.1);
    }
    .pex-btn-apply:hover { background: #1e293b; transform: translateY(-1px); box-shadow: 0 4px 12px rgba(15, 23, 42, 0.15); }
    .pex-btn-reset { 
        background: #f1f5f9; color: #475569; border: 1px solid #cbd5e1; padding: 0 24px; border-radius: 10px; 
        font-weight: 600; font-size: 14px; transition: all 0.2s; text-decoration: none; height: 44px; 
        display: inline-flex; align-items: center; justify-content: center; box-sizing: border-box; 
    }
    .pex-btn-reset:hover { background: #e2e8f0; color: #0f172a; }

    /* Metrics Grid */
    .pex-metrics-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 24px; margin-bottom: 35px; }
    @media (max-width: 1100px) { .pex-metrics-grid { grid-template-columns: repeat(2, 1fr); } }
    @media (max-width: 600px) { .pex-metrics-grid { grid-template-columns: 1fr; } }
    
    .pex-metric-card { 
        background: #ffffff; 
        padding: 26px; 
        border-radius: 16px; 
        border: 1px solid #eef2f6; 
        box-shadow: 0 4px 6px -1px rgba(15, 23, 42, 0.02), 0 2px 4px -1px rgba(15, 23, 42, 0.02); 
        display: flex;
        flex-direction: column;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }
    .pex-metric-card:hover { 
        transform: translateY(-4px); 
        box-shadow: 0 10px 20px -5px rgba(15, 23, 42, 0.05), 0 8px 10px -5px rgba(15, 23, 42, 0.02);
        border-color: #e2e8f0;
    }
    
    .pex-metric-top { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; }
    .pex-metric-label { font-size: 14px; font-weight: 700; color: #64748b; }
    
    .pex-metric-icon-wrap {
        width: 44px; height: 44px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 20px;
    }
    .ic-blue { background: #eff6ff; color: #2563eb; }
    .ic-green { background: #ecfdf5; color: #059669; }
    .ic-yellow { background: #fffbeb; color: #d97706; }
    .ic-purple { background: #f5f3ff; color: #7c3aed; }

    .pex-metric-value { font-size: 34px; font-weight: 800; color: #0f172a; margin-bottom: 6px; letter-spacing: -0.5px; }
    .pex-metric-sub { font-size: 13px; color: #94a3b8; font-weight: 500; }

    /* Dashboard Layout */
    .pex-dashboard-layout { display: grid; grid-template-columns: 2fr 1fr; gap: 30px; }
    @media (max-width: 1024px) { .pex-dashboard-layout { grid-template-columns: 1fr; } }
    
    .pex-card { 
        background: #ffffff; 
        border-radius: 16px; 
        border: 1px solid #eef2f6; 
        box-shadow: 0 4px 6px -1px rgba(15, 23, 42, 0.02), 0 2px 4px -1px rgba(15, 23, 42, 0.02); 
        overflow: hidden; 
    }
    .pex-card-header { padding: 24px 30px; border-bottom: 1px solid #f1f5f9; background: #ffffff; }
    .pex-card-header h2 { margin: 0; font-size: 18px; font-weight: 800; color: #0f172a; letter-spacing: -0.3px; }
    .pex-card-body { padding: 30px; }
    
    /* Quick Links */
    .pex-quick-links-wrap { display: flex; flex-direction: column; gap: 14px; }
    .pex-quick-link { 
        display: flex; align-items: center; justify-content: space-between; padding: 18px 20px; border-radius: 12px; 
        text-decoration: none; border: 1px solid #e2e8f0; 
        transition: all 0.2s ease; background: #ffffff; box-shadow: 0 1px 3px rgba(0,0,0,0.01);
    }
    .pex-quick-link:hover { 
        background: #f8fafc; border-color: #cbd5e1; transform: translateY(-1px); 
        box-shadow: 0 6px 12px rgba(15, 23, 42, 0.04);
    }
    .pex-quick-link-left { display: flex; align-items: center; gap: 16px; color: #1e293b; font-weight: 600; font-size: 15px; }
    .pex-quick-icon { 
        font-size: 20px; background: #f1f5f9; width: 44px; height: 44px; 
        display: flex; align-items: center; justify-content: center; border-radius: 10px; color: #475569;
    }
    .pex-quick-arrow {
        color: #94a3b8;
        transition: transform 0.2s ease, color 0.2s ease;
    }
    .pex-quick-link:hover .pex-quick-arrow {
        transform: translateX(4px);
        color: #10b981;
    }
</style>

<div class="wrap pex-premium-wrap">

    <!-- Hero Section -->
    <div class="pex-hero">
        <div class="pex-hero-text">
            <h1><?php esc_html_e( 'Welcome to Pexally Campaigns', 'pexally-email-campaigns' ); ?></h1>
            <p><?php esc_html_e( 'Your central hub for monitoring email performance, audience growth, and engagement.', 'pexally-email-campaigns' ); ?></p>
        </div>
        <div>
            <a href="<?php echo esc_url( admin_url( 'admin.php?page=pexemail-campaigns-add' ) ); ?>" class="pex-btn-white">
                <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4"></path></svg>
                <?php esc_html_e( 'Create Campaign', 'pexally-email-campaigns' ); ?>
            </a>
        </div>
    </div>

    <!-- Advanced Filter Bar -->
    <form method="GET" class="pex-filter-card">
        <input type="hidden" name="page" value="pexemail-dashboard">
        
        <div class="pex-filter-group" style="flex-grow: 2;">
            <label><?php esc_html_e( 'Filter by Campaign', 'pexally-email-campaigns' ); ?></label>
            <select name="filter_campaign" class="pex-filter-input">
                <option value="0"><?php esc_html_e( 'All Campaigns (Lifetime)', 'pexally-email-campaigns' ); ?></option>
                <?php foreach ( $pexemail_all_campaigns as $pexemail_camp_opt ) : ?>
                    <option value="<?php echo esc_attr( $pexemail_camp_opt->id ); ?>" <?php selected( $pexemail_filter_campaign, $pexemail_camp_opt->id ); ?>>
                        #<?php echo esc_html( $pexemail_camp_opt->id ); ?> - <?php echo esc_html( stripslashes( $pexemail_camp_opt->subject ) ); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="pex-filter-group">
            <label><?php esc_html_e( 'Filter by Month', 'pexally-email-campaigns' ); ?></label>
            <input type="month" name="filter_month" class="pex-filter-input" value="<?php echo esc_attr( $pexemail_filter_month ); ?>">
        </div>

        <div class="pex-filter-group">
            <label><?php esc_html_e( 'Start Date', 'pexally-email-campaigns' ); ?></label>
            <input type="date" name="filter_start" class="pex-filter-input" value="<?php echo esc_attr( $pexemail_filter_start ); ?>">
        </div>

        <div class="pex-filter-group">
            <label><?php esc_html_e( 'End Date', 'pexally-email-campaigns' ); ?></label>
            <input type="date" name="filter_end" class="pex-filter-input" value="<?php echo esc_attr( $pexemail_filter_end ); ?>">
        </div>

        <div class="pex-filter-actions">
            <button type="submit" class="pex-btn-apply"><?php esc_html_e( 'Apply Filters', 'pexally-email-campaigns' ); ?></button>
            <?php if ( $pexemail_filter_campaign > 0 || ! empty( $pexemail_filter_month ) || ! empty( $pexemail_filter_start ) || ! empty( $pexemail_filter_end ) ) : ?>
                <a href="<?php echo esc_url( admin_url( 'admin.php?page=pexemail-dashboard' ) ); ?>" class="pex-btn-reset"><?php esc_html_e( 'Clear', 'pexally-email-campaigns' ); ?></a>
            <?php endif; ?>
        </div>
    </form>

    <!-- Top Metrics -->
    <div class="pex-metrics-grid">
        <div class="pex-metric-card">
            <div class="pex-metric-top">
                <span class="pex-metric-label"><?php echo esc_html( $pexemail_contact_label ); ?></span>
                <div class="pex-metric-icon-wrap ic-blue">
                    <svg width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z"></path></svg>
                </div>
            </div>
            <span class="pex-metric-value val-contacts"><?php echo esc_html( number_format_i18n( $pexemail_total_contacts ) ); ?></span>
            <span class="pex-metric-sub">
                <?php echo ( $pexemail_filter_campaign > 0 || !empty($pexemail_filter_month) || !empty($pexemail_filter_start) ) ? esc_html__( 'In Selected Scope', 'pexally-email-campaigns' ) : esc_html__( 'Across all lists', 'pexally-email-campaigns' ); ?>
            </span>
        </div>
        
        <div class="pex-metric-card">
            <div class="pex-metric-top">
                <span class="pex-metric-label"><?php esc_html_e( 'Emails Sent', 'pexally-email-campaigns' ); ?></span>
                <div class="pex-metric-icon-wrap ic-green">
                    <svg width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path></svg>
                </div>
            </div>
            <span class="pex-metric-value val-sent"><?php echo esc_html( number_format_i18n( $pexemail_total_sent ) ); ?></span>
            <span class="pex-metric-sub"><?php esc_html_e( 'Successfully Delivered', 'pexally-email-campaigns' ); ?></span>
        </div>
        
        <div class="pex-metric-card">
            <div class="pex-metric-top">
                <span class="pex-metric-label"><?php esc_html_e( 'Avg. Open Rate', 'pexally-email-campaigns' ); ?></span>
                <div class="pex-metric-icon-wrap ic-yellow">
                    <svg width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path><path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path></svg>
                </div>
            </div>
            <span class="pex-metric-value val-open"><?php echo esc_html( $pexemail_open_rate ); ?>%</span>
            <span class="pex-metric-sub"><?php echo esc_html( number_format_i18n( $pexemail_total_opened ) ); ?> <?php esc_html_e( 'Total Opens', 'pexally-email-campaigns' ); ?></span>
        </div>
        
        <div class="pex-metric-card">
            <div class="pex-metric-top">
                <span class="pex-metric-label"><?php esc_html_e( 'Click-to-Open Rate', 'pexally-email-campaigns' ); ?></span>
                <div class="pex-metric-icon-wrap ic-purple">
                    <svg width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M15 15l-2 5L9 9l11 4-5 2zm0 0l5 5M7.188 2.239l.777 2.897M5.136 7.965l-2.898-.777M13.95 4.05l-2.122 2.122m-5.657 5.656l-2.12 2.122"></path></svg>
                </div>
            </div>
            <span class="pex-metric-value val-click"><?php echo esc_html( $pexemail_click_rate ); ?>%</span>
            <span class="pex-metric-sub"><?php echo esc_html( number_format_i18n( $pexemail_total_clicked ) ); ?> <?php esc_html_e( 'Total Clicks', 'pexally-email-campaigns' ); ?></span>
        </div>
    </div>

    <!-- Main Content Area -->
    <div class="pex-dashboard-layout">
        
        <!-- Interactive Chart -->
        <div class="pex-card">
            <div class="pex-card-header">
                <h2><?php echo ( $pexemail_filter_campaign > 0 ) ? esc_html__( 'Campaign Engagement', 'pexally-email-campaigns' ) : esc_html__( 'Recent Campaigns Engagement', 'pexally-email-campaigns' ); ?></h2>
            </div>
            <div class="pex-card-body">
                <?php if ( empty( $pexemail_chart_labels ) ) : ?>
                    <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 70px 20px; color: #64748b; text-align: center;">
                        <div style="background: #f8fafc; border-radius: 50%; width: 80px; height: 80px; display: flex; align-items: center; justify-content: center; margin-bottom: 20px; box-shadow: inset 0 2px 4px rgba(0,0,0,0.02); border: 1px solid #f1f5f9;">
                            <svg width="36" height="36" fill="none" stroke="#94a3b8" stroke-width="1.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path></svg>
                        </div>
                        <h3 style="margin: 0 0 8px; font-size: 17px; color: #0f172a; font-weight: 700;"><?php esc_html_e( 'No Campaign Data', 'pexally-email-campaigns' ); ?></h3>
                        <p style="margin:0; font-size: 14.5px; max-width: 320px; line-height: 1.5; color: #64748b;"><?php esc_html_e( 'There are no completed campaigns in the selected filter scope. Try adjusting your dates or campaign filter.', 'pexally-email-campaigns' ); ?></p>
                    </div>
                <?php else : ?>
                    <canvas id="pexEngagementChart" style="width: 100%; height: 320px;"></canvas>
                <?php endif; ?>
            </div>
        </div>

        <!-- Quick Links -->
        <div class="pex-card">
            <div class="pex-card-header">
                <h2><?php esc_html_e( 'Quick Actions', 'pexally-email-campaigns' ); ?></h2>
            </div>
            <div class="pex-card-body pex-quick-links-wrap">
                <a href="<?php echo esc_url( admin_url( 'admin.php?page=pexemail-contacts' ) ); ?>" class="pex-quick-link">
                    <div class="pex-quick-link-left">
                        <div class="pex-quick-icon">👥</div>
                        <div><?php esc_html_e( 'Manage Contacts & Lists', 'pexally-email-campaigns' ); ?></div>
                    </div>
                    <div class="pex-quick-arrow">
                        <svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7"></path></svg>
                    </div>
                </a>
                
                <a href="<?php echo esc_url( admin_url( 'admin.php?page=pexemail-campaigns-add' ) ); ?>" class="pex-quick-link">
                    <div class="pex-quick-link-left">
                        <div class="pex-quick-icon">🎨</div>
                        <div><?php esc_html_e( 'Create New Campaign', 'pexally-email-campaigns' ); ?></div>
                    </div>
                    <div class="pex-quick-arrow">
                        <svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7"></path></svg>
                    </div>
                </a>

                <a href="<?php echo esc_url( admin_url( 'admin.php?page=pexemail-settings' ) ); ?>" class="pex-quick-link">
                    <div class="pex-quick-link-left">
                        <div class="pex-quick-icon">⚙️</div>
                        <div><?php esc_html_e( 'SMTP & Branding Settings', 'pexally-email-campaigns' ); ?></div>
                    </div>
                    <div class="pex-quick-arrow">
                        <svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7"></path></svg>
                    </div>
                </a>

                <a href="<?php echo esc_url( admin_url( 'admin.php?page=pexemail-license' ) ); ?>" class="pex-quick-link">
                    <div class="pex-quick-link-left">
                        <div class="pex-quick-icon">🛡️</div>
                        <div><?php esc_html_e( 'Upgrade to Pro License', 'pexally-email-campaigns' ); ?></div>
                    </div>
                    <div class="pex-quick-arrow">
                        <svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7"></path></svg>
                    </div>
                </a>
            </div>
        </div>

    </div>

</div>

<!-- Render Chart.js -->
<?php if ( ! empty( $pexemail_chart_labels ) ) : ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    
    // Ensure Chart is defined. If it's not, we gracefully skip rendering so no JS errors break the page.
    if ( typeof Chart === 'undefined' ) {
        console.warn('Pexally Email: Chart.js is not loaded. Please ensure you enqueue it locally.');
        return;
    }

    const ctx = document.getElementById('pexEngagementChart').getContext('2d');
    
    const labels = <?php echo json_encode( $pexemail_chart_labels ); ?>;
    const dataSent = <?php echo json_encode( $pexemail_chart_sent ); ?>;
    const dataOpened = <?php echo json_encode( $pexemail_chart_opened ); ?>;
    const dataClicked = <?php echo json_encode( $pexemail_chart_clicked ); ?>;

    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [
                {
                    label: 'Delivered',
                    data: dataSent,
                    backgroundColor: '#10b981', // Clean Emerald
                    borderRadius: 4,
                    barPercentage: 0.5,
                    categoryPercentage: 0.7
                },
                {
                    label: 'Opened',
                    data: dataOpened,
                    backgroundColor: '#3b82f6', // Clean Blue
                    borderRadius: 4,
                    barPercentage: 0.5,
                    categoryPercentage: 0.7
                },
                {
                    label: 'Clicked',
                    data: dataClicked,
                    backgroundColor: '#8b5cf6', // Clean Purple
                    borderRadius: 4,
                    barPercentage: 0.5,
                    categoryPercentage: 0.7
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                    labels: { usePointStyle: true, boxWidth: 8, font: { family: '-apple-system, BlinkMacSystemFont, sans-serif', size: 12 }, padding: 20 }
                },
                tooltip: {
                    backgroundColor: '#0f172a',
                    titleFont: { size: 14, family: '-apple-system, BlinkMacSystemFont, sans-serif' },
                    bodyFont: { size: 13, family: '-apple-system, BlinkMacSystemFont, sans-serif' },
                    padding: 12,
                    cornerRadius: 8,
                    displayColors: true
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: { color: '#f1f5f9', drawBorder: false },
                    border: { display: false },
                    ticks: { font: { family: '-apple-system, BlinkMacSystemFont, sans-serif', size: 12 }, color: '#64748b', padding: 10 }
                },
                x: {
                    grid: { display: false, drawBorder: false },
                    border: { display: false },
                    ticks: { font: { family: '-apple-system, BlinkMacSystemFont, sans-serif', size: 12 }, color: '#475569', padding: 10 }
                }
            }
        }
    });
});
</script>
<?php endif; ?>