<?php
/**
 * View: All Campaigns, Add/Edit Campaign, and Live Sending Stats
 */

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

global $wpdb;

// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$pexemail_page   = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$pexemail_action = isset( $_GET['action'] ) ? sanitize_text_field( wp_unslash( $_GET['action'] ) ) : '';
$pexemail_tz     = new DateTimeZone( 'Asia/Dhaka' ); 

// Ultimate Failsafe: Guarantee total tracking columns exist in the campaigns table
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$pexemail_camp_cols = $wpdb->get_col( "DESC {$wpdb->prefix}pexemail_campaigns", 0 );
if ( is_array( $pexemail_camp_cols ) ) {
    if ( ! in_array( 'opens', $pexemail_camp_cols, true ) ) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query( "ALTER TABLE {$wpdb->prefix}pexemail_campaigns ADD COLUMN opens INT DEFAULT 0" );
    }
    if ( ! in_array( 'clicks', $pexemail_camp_cols, true ) ) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query( "ALTER TABLE {$wpdb->prefix}pexemail_campaigns ADD COLUMN clicks INT DEFAULT 0" );
    }
}
?>

<style>
    /* Global Reset & Typography */
    .pex-premium-wrap { max-width: 1400px; margin: 25px 0 0 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; color: #334155; }
    
    /* Hero Section */
    .pex-hero { background: linear-gradient(135deg, #0f5132 0%, #064e3b 100%); color: #fff; padding: 45px 50px; border-radius: 16px; margin-bottom: 30px; 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; }
    
    /* Buttons */
    .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; border: none; cursor: pointer; }
    .pex-btn-white:hover { background: #f8fafc; color: #047857; transform: translateY(-2px); box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15); }
    .pex-btn-primary { background: #0f172a; color: white; padding: 12px 24px; border-radius: 10px; font-weight: 600; font-size: 14px; text-decoration: none; display: inline-flex; align-items: center; justify-content: center; transition: all 0.2s; border: none; cursor: pointer; box-shadow: 0 2px 4px rgba(15, 23, 42, 0.1); gap: 8px; }
    .pex-btn-primary:hover { background: #1e293b; transform: translateY(-1px); box-shadow: 0 4px 12px rgba(15, 23, 42, 0.15); color: white; }
    .pex-btn-secondary { background: #ffffff; color: #475569; padding: 12px 24px; border-radius: 10px; font-weight: 700; font-size: 15px; text-decoration: none; display: inline-flex; align-items: center; transition: all 0.2s; border: 1px solid #cbd5e1; box-shadow: 0 2px 4px rgba(0,0,0,0.02); gap: 8px; cursor: pointer; }
    .pex-btn-secondary:hover { background: #f8fafc; color: #0f172a; border-color: #94a3b8; transform: translateY(-1px); }

    /* Action Buttons */
    .pex-action-play { background: #10b981; color: white; padding: 12px 24px; border-radius: 10px; border: none; font-weight: 700; font-size: 15px; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; transition: all 0.2s; box-shadow: 0 4px 10px rgba(16, 185, 129, 0.2); }
    .pex-action-play:hover { background: #059669; transform: translateY(-1px); box-shadow: 0 6px 15px rgba(16, 185, 129, 0.3); }
    .pex-action-play:disabled { background: #94a3b8; cursor: not-allowed; box-shadow: none; transform: none; }
    .pex-action-pause { background: #f59e0b; color: white; padding: 12px 24px; border-radius: 10px; border: none; font-weight: 700; font-size: 15px; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; transition: all 0.2s; box-shadow: 0 4px 10px rgba(245, 158, 11, 0.2); }
    .pex-action-pause:hover { background: #d97706; transform: translateY(-1px); box-shadow: 0 6px 15px rgba(245, 158, 11, 0.3); }
    .pex-action-stop { background: #ef4444; color: white; padding: 12px 24px; border-radius: 10px; border: none; font-weight: 700; font-size: 15px; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; transition: all 0.2s; box-shadow: 0 4px 10px rgba(239, 68, 68, 0.2); }
    .pex-action-stop:hover { background: #dc2626; transform: translateY(-1px); box-shadow: 0 6px 15px rgba(239, 68, 68, 0.3); }
    .pex-action-retry { background: #3b82f6; color: white; padding: 12px 24px; border-radius: 10px; border: none; font-weight: 700; font-size: 15px; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; transition: all 0.2s; box-shadow: 0 4px 10px rgba(59, 130, 246, 0.2); }
    .pex-action-retry:hover { background: #2563eb; transform: translateY(-1px); box-shadow: 0 6px 15px rgba(59, 130, 246, 0.3); }

    /* Notices */
    .pex-custom-notice { background: #f0fdf4; border: 1px solid #bbf7d0; border-left: 4px solid #10b981; padding: 16px 20px; border-radius: 10px; color: #065f46; font-weight: 600; margin-bottom: 25px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.02); font-size: 14.5px; display: flex; align-items: center; gap: 10px; }
    .pex-error-notice { background: #fef2f2; border: 1px solid #fecaca; border-left: 4px solid #ef4444; padding: 16px 20px; border-radius: 10px; color: #991b1b; font-weight: 600; margin-bottom: 25px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.02); font-size: 14.5px; display: flex; align-items: center; gap: 10px; }
    .pex-info-notice { background: #eff6ff; border: 1px solid #bfdbfe; border-left: 4px solid #3b82f6; padding: 16px 20px; border-radius: 10px; color: #1e40af; font-weight: 600; margin-bottom: 25px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.02); font-size: 14.5px; display: flex; align-items: center; gap: 10px; }

    /* Cards */
    .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; margin-bottom: 30px; }
    .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; }

    /* Form Styles */
    .pex-form-group { margin-bottom: 24px; }
    .pex-form-label { display: block; font-size: 13.5px; font-weight: 700; color: #1e293b; margin-bottom: 8px; }
    .pex-input { width: 100%; max-width: 600px; padding: 12px 16px; border: 1px solid #cbd5e1; border-radius: 10px; font-size: 14.5px; outline: none; transition: all 0.2s; background: #f8fafc; color: #0f172a; box-shadow: inset 0 1px 2px rgba(0,0,0,0.01); box-sizing: border-box; }
    .pex-input:focus { border-color: #10b981; background: #ffffff; box-shadow: 0 0 0 4px rgba(16, 185, 129, 0.15); }
    .pex-desc { font-size: 13px; color: #64748b; margin-top: 6px; line-height: 1.5; }
    .pex-desc code { background: #f1f5f9; padding: 2px 6px; border-radius: 4px; font-size: 12px; color: #e11d48; }

    /* Empty State */
    .pex-empty-state { display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 80px 20px; background: #ffffff; border-radius: 16px; border: 2px dashed #cbd5e1; margin-top: 10px; text-align: center; }
    .pex-empty-icon-wrap { 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; }
    .pex-empty-state h3 { font-size: 20px; color: #0f172a; margin: 0 0 10px 0; font-weight: 800; }
    .pex-empty-state p { color: #64748b; margin: 0 auto 25px auto; max-width: 450px; font-size: 15px; line-height: 1.6; }

    /* Table Styles */
    .pex-table { width: 100%; border-collapse: collapse; font-size: 14.5px; }
    .pex-table th { background: #f8fafc; padding: 16px 20px; text-align: left; font-weight: 700; color: #475569; border-bottom: 1px solid #e2e8f0; font-size: 13px; text-transform: uppercase; letter-spacing: 0.5px; }
    .pex-table td { padding: 16px 20px; border-bottom: 1px solid #f1f5f9; vertical-align: middle; color: #334155; }
    .pex-table tr:hover td { background: #f8fafc; }
    .pex-table tr:last-child td { border-bottom: none; }

    /* Badges */
    .pex-badge { display: inline-block; padding: 6px 12px; border-radius: 20px; font-weight: 700; font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; }
    
    /* Action Pills */
    .pex-action-pill { display: inline-flex; align-items: center; gap: 6px; padding: 6px 14px; border-radius: 6px; font-size: 13px; font-weight: 600; text-decoration: none; transition: all 0.2s; border: none; color: #fff; box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
    .pex-pill-view { background: #2563eb; }
    .pex-pill-view:hover { background: #1d4ed8; color: #fff; transform: translateY(-1px); }
    .pex-pill-edit { background: #475569; }
    .pex-pill-edit:hover { background: #334155; color: #fff; transform: translateY(-1px); }
    .pex-pill-dup { background: #7c3aed; }
    .pex-pill-dup:hover { background: #6d28d9; color: #fff; transform: translateY(-1px); }
    .pex-pill-del { background: #dc2626; }
    .pex-pill-del:hover { background: #b91c1c; color: #fff; transform: translateY(-1px); }

    /* Metrics Grid */
    .pex-metrics-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 24px; margin-bottom: 30px; }
    @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: 24px; border-radius: 16px; border: 1px solid #eef2f6; box-shadow: 0 4px 6px -1px rgba(15, 23, 42, 0.02); display: flex; flex-direction: column; }
    .pex-metric-top { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; }
    .pex-metric-label { font-size: 13.5px; font-weight: 700; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; }
    .pex-metric-icon-wrap { width: 44px; height: 44px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 20px; }
    .ic-gray { background: #f1f5f9; color: #475569; }
    .ic-green { background: #ecfdf5; color: #059669; }
    .ic-blue { background: #eff6ff; color: #2563eb; }
    .ic-purple { background: #f5f3ff; color: #7c3aed; }
    .pex-metric-value { font-size: 34px; font-weight: 800; color: #0f172a; margin-bottom: 4px; letter-spacing: -0.5px; }

    /* Progress Bar */
    .pex-progress-wrap { background: #f1f5f9; border-radius: 20px; height: 26px; overflow: hidden; margin: 25px 0; border: 1px solid #e2e8f0; box-shadow: inset 0 2px 4px rgba(0,0,0,0.05); }
    .pex-progress-bar { background: #10b981; height: 100%; transition: width 0.4s ease, background-color 0.4s ease; display: flex; align-items: center; justify-content: flex-end; padding-right: 10px; color: white; font-weight: 800; font-size: 12px; }
    .pex-progress-bar.is-sending { background-image: linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent); background-size: 1.5rem 1.5rem; animation: progress-stripes 1s linear infinite; }
    @keyframes progress-stripes { from { background-position: 1.5rem 0; } to { background-position: 0 0; } }

    /* Status Bar */
    .pex-status-bar { display: flex; align-items: center; justify-content: space-between; background: #f8fafc; padding: 15px 20px; border-radius: 12px; border: 1px solid #e2e8f0; margin-bottom: 25px; }
    .pex-status-left { font-size: 15px; font-weight: 600; color: #0f172a; }
</style>

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

    <?php 
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if ( isset( $_GET['saved'] ) ) : ?>
        <div class="pex-custom-notice">✅ <?php esc_html_e( 'Campaign saved successfully.', 'pexally-email-campaigns' ); ?></div>
    <?php endif; ?>
    <?php 
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if ( isset( $_GET['duplicated'] ) ) : ?>
        <div class="pex-custom-notice">✅ <?php esc_html_e( 'Campaign duplicated successfully. You can now edit the copy.', 'pexally-email-campaigns' ); ?></div>
    <?php endif; ?>
    <?php 
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if ( isset( $_GET['deleted'] ) ) : ?>
        <div class="pex-custom-notice">✅ <?php esc_html_e( 'Campaign deleted successfully.', 'pexally-email-campaigns' ); ?></div>
    <?php endif; ?>

    <!-- ==========================================
         VIEW 1: ADD / EDIT CAMPAIGN 
         ========================================== -->
    <?php if ( $pexemail_page === 'pexemail-campaigns-add' || $pexemail_action === 'edit' ) : 
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $pexemail_edit_id  = isset( $_GET['id'] ) ? intval( $_GET['id'] ) : 0;
        $pexemail_subject  = ''; 
        $pexemail_template = ''; 
        $pexemail_list_id  = 0;
        $pexemail_title    = __( 'Create New Campaign', 'pexally-email-campaigns' );

        $pexemail_tpl_html = [
            'minimal'      => "<p style='font-size:16px;color:#374151'>Hi {{first_name}},</p><p style='font-size:16px;color:#374151'>We are reaching out to let you know about...</p><p style='font-size:16px;color:#374151'>Best regards,<br>The Team</p>",
            'newsletter'   => "<div style='text-align:center;margin-bottom:20px'><div style='background:#cbd5e1;height:220px;border-radius:8px;line-height:220px;color:#475569;font-weight:bold;'>Hero Image Area</div></div><h2 style='color:#0f172a'>Weekly Digest</h2><p style='color:#475569'>Top updates you missed:</p><ul style='color:#475569'><li>Update One</li><li>Update Two</li></ul><div style='text-align:center;margin-top:30px'><a href='#' style='background:#10b981;color:#fff;padding:12px 24px;text-decoration:none;border-radius:6px;font-weight:bold;display:inline-block'>Read Full Story</a></div>",
            'promo'        => "<div style='text-align:center;background:#fef2f2;padding:40px 20px;border-radius:8px;border:2px dashed #fca5a5;margin-bottom:25px'><h1 style='color:#dc2626;margin:0 0 10px 0'>50% OFF TODAY</h1><p style='color:#991b1b;font-size:18px'>Code <strong style='background:#fff;padding:4px 8px'>SAVE50</strong> at checkout.</p></div><div style='text-align:center'><a href='#' style='background:#dc2626;color:#fff;padding:14px 30px;text-decoration:none;border-radius:6px;font-weight:bold;display:inline-block'>Shop Now</a></div>",
            'announcement' => "<div style='text-align:center'><div style='font-size:48px'>🎉</div><h2 style='color:#0f172a'>We have big news!</h2><p style='color:#475569'>We are thrilled to announce our latest feature.</p><a href='#' style='background:#0f172a;color:#fff;padding:14px 28px;text-decoration:none;border-radius:6px;font-weight:bold;display:inline-block'>See What's New</a></div>",
            'ecommerce'    => "<h2 style='text-align:center;color:#0f172a'>New Arrivals</h2><p style='text-align:center;color:#64748b'>Check out our latest collection.</p><table width='100%' cellpadding='10'><tr><td width='50%' align='center'><div style='background:#f1f5f9;height:180px;border-radius:8px;line-height:180px;color:#94a3b8;font-weight:bold;'>Product 1</div><h3 style='color:#1e293b'>Product 1</h3><p style='color:#10b981;font-weight:bold'>$49.99</p><a href='#' style='background:#10b981;color:#fff;padding:10px 20px;text-decoration:none;border-radius:6px;font-weight:bold'>Buy Now</a></td><td width='50%' align='center'><div style='background:#f1f5f9;height:180px;border-radius:8px;line-height:180px;color:#94a3b8;font-weight:bold;'>Product 2</div> <h3 style='color:#1e293b'>Product 2</h3><p style='color:#10b981;font-weight:bold'>$59.99</p><a href='#' style='background:#10b981;color:#fff;padding:10px 20px;text-decoration:none;border-radius:6px;font-weight:bold'>Buy Now</a></td></tr></table>",
            'webinar'      => "<h2 style='color:#0f172a'>You're Invited!</h2><p style='color:#475569'>Join us for an exclusive live masterclass.</p><div style='background:#f8fafc;border-left:4px solid #10b981;padding:20px;margin:25px 0'><p><strong>📅 Date:</strong> Next Thursday</p><p><strong>⏰ Time:</strong> 2:00 PM EST</p><p><strong>📍 Location:</strong> Zoom</p></div><div style='margin-top:25px'><a href='#' style='background:#10b981;color:#fff;padding:12px 24px;text-decoration:none;border-radius:6px;font-weight:bold;display:inline-block'>Reserve My Seat</a></div>",
            'welcome'      => "<h2 style='color:#0f172a'>Welcome, {{first_name}}! 👋</h2><p style='color:#475569'>We are excited to have you on board. Quick links:</p><ul><li><a href='#' style='color:#10b981'>Complete profile</a></li><li><a href='#' style='color:#10b981'>Getting started guide</a></li></ul><p style='color:#475569'>Questions? Just reply!</p>",
            'alert'        => "<div style='background:#fffbeb;border:1px solid #fde68a;padding:25px;border-radius:8px'><h2 style='color:#d97706;margin:0 0 15px 0'>⚠️ Account Update</h2><p style='color:#92400e;margin:0'>Our terms of service have been updated. Please review.</p></div><div style='text-align:center;margin-top:25px'><a href='#' style='background:#d97706;color:#fff;padding:12px 28px;text-decoration:none;border-radius:6px;font-weight:bold;display:inline-block'>Review Changes</a></div>",
            'feedback'     => "<h2 style='text-align:center;color:#0f172a'>How did we do?</h2><p style='text-align:center;color:#475569'>We value your feedback!</p><div style='text-align:center;font-size:36px;margin:25px 0'><a href='#' style='text-decoration:none'>⭐</a> <a href='#' style='text-decoration:none'>⭐</a> <a href='#' style='text-decoration:none'>⭐</a> <a href='#' style='text-decoration:none'>⭐</a> <a href='#' style='text-decoration:none'>⭐</a></div>",
            'update'       => "<h2 style='color:#0f172a'>Version 2.0 is Live! 🚀</h2><p style='color:#475569'>Here is what's new:</p><div style='padding:15px;border-left:3px solid #3b82f6;background:#eff6ff'><p style='color:#1e3a8a'><strong>✨ Feature:</strong> Dark mode.</p><p style='color:#1e3a8a'><strong>⚡ Performance:</strong> 2x faster.</p></div><a href='#' style='background:#3b82f6;color:#fff;padding:12px 24px;text-decoration:none;border-radius:6px;font-weight:bold;display:inline-block'>Changelog</a>",
            'holiday'      => "<div style='text-align:center'><h1 style='color:#b91c1c'>Happy Holidays! 🎄</h1><p style='color:#475569'>Wishing you a wonderful season!</p><div style='background:#fef3c7;padding:20px;border-radius:8px;display:inline-block;margin-bottom:25px'><p style='color:#92400e;font-weight:bold;margin:0'>Enjoy 20% off your next purchase.</p></div><br><a href='#' style='background:#b91c1c;color:#fff;padding:14px 28px;text-decoration:none;border-radius:6px;font-weight:bold;display:inline-block'>Claim Gift</a></div>",
            'digest'       => "<h2 style='color:#0f172a'>Top Articles</h2><table width='100%'><tr><td width='130'><div style='background:#f1f5f9;width:110px;height:90px;border-radius:6px;text-align:center;line-height:90px;color:#94a3b8;'>Image</div></td><td><h3 style='color:#1e293b'>5 Ways to Boost Sales</h3><a href='#' style='color:#10b981;font-weight:bold'>Read Article &rarr;</a></td></tr></table><hr style='border:1px solid #e2e8f0;margin:20px 0'><table width='100%'><tr><td width='130'><div style='background:#f1f5f9;width:110px;height:90px;border-radius:6px;text-align:center;line-height:90px;color:#94a3b8;'>Image</div></td><td><h3 style='color:#1e293b'>Understanding SEO</h3><a href='#' style='color:#10b981;font-weight:bold'>Read Article &rarr;</a></td></tr></table>",
            'reminder'     => "<div style='text-align:center'><h2 style='color:#0f172a'>Just a friendly reminder! ⏰</h2><p style='color:#475569'>Our special event is starting tomorrow.</p><a href='#' style='background:#0f172a;color:#fff;padding:12px 28px;text-decoration:none;border-radius:6px;font-weight:bold;display:inline-block'>View Details</a></div>",
            'survey'       => "<div style='text-align:center'><h2 style='color:#0f172a'>We need your help, {{first_name}}!</h2><p style='color:#475569'>It only takes 2 minutes.</p><br><a href='#' style='background:#8b5cf6;color:#fff;padding:14px 28px;text-decoration:none;border-radius:6px;font-weight:bold;display:inline-block'>Take Survey</a></div>",
            'onboarding'   => "<h2 style='color:#0f172a'>Step 2: Complete Setup</h2><p style='color:#475569'>Now it's time to fully set up your account.</p><div style='background:#f8fafc;padding:20px;border-radius:8px;border:1px solid #e2e8f0'><p>✅ <strong>Task 1:</strong> Upload profile picture.</p><p>✅ <strong>Task 2:</strong> Connect social accounts.</p></div><a href='#' style='color:#10b981;font-weight:bold'>Dashboard &rarr;</a>",
            'coupon'       => "<h2 style='text-align:center;color:#0f172a'>A Special Treat 🎁</h2><p style='text-align:center;color:#475569'>Here is a secret coupon code:</p><div style='text-align:center;font-size:28px;font-weight:800;letter-spacing:3px;padding:20px;background:#f8fafc;border:2px dashed #94a3b8;border-radius:8px;color:#0f172a'>VIP2026</div><p style='text-align:center;color:#94a3b8'>Valid for 48 hours.</p>",
            'cart'         => "<h2 style='color:#0f172a;text-align:center'>You left something behind! 🛒</h2><p style='color:#475569;text-align:center'>Hi {{first_name}}, items in your cart are selling out fast!</p><div style='text-align:center;margin:30px 0'><a href='#' style='background:#f59e0b;color:#fff;padding:14px 30px;text-decoration:none;border-radius:6px;font-weight:bold;display:inline-block'>Return to Checkout</a></div>",
            'thanks'       => "<div style='text-align:center'><div style='font-size:50px;margin-bottom:10px'>✅</div><h2 style='color:#16a34a'>Thank You!</h2><p style='color:#475569'>Your order has been processed successfully.</p><a href='#' style='color:#10b981;font-weight:bold;text-decoration:none'>View Order &rarr;</a></div>",
            'vip'          => "<div style='background:#0f172a;padding:50px 30px;border-radius:12px;text-align:center'><h1 style='color:#fde047;font-style:italic'>VIP Exclusive</h1><p style='color:#cbd5e1'>You've been selected to join our inner circle.</p><a href='#' style='background:#fde047;color:#92400e;padding:14px 32px;text-decoration:none;border-radius:50px;font-weight:bold;display:inline-block'>Accept Invitation</a></div>",
            'recap'        => "<h2 style='color:#0f172a'>Your Monthly Recap 📈</h2><p style='color:#475569'>Here is what you achieved this month:</p><div style='background:#f8fafc;padding:20px;border-radius:8px;border:1px solid #e2e8f0'><p><strong>Tasks Completed:</strong> 42</p><p><strong>Hours Saved:</strong> 12</p><p><strong>Goals Met:</strong> 100%</p></div><a href='#' style='color:#2563eb;font-weight:bold;text-decoration:none'>View Analytics &rarr;</a>"
        ];

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if ( isset( $_GET['tpl'] ) ) {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $pexemail_tpl_req = sanitize_text_field( wp_unslash( $_GET['tpl'] ) );
            if ( array_key_exists( $pexemail_tpl_req, $pexemail_tpl_html ) ) {
                $pexemail_template = $pexemail_tpl_html[ $pexemail_tpl_req ];
            }
        }

        if ( $pexemail_edit_id > 0 ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $pexemail_campaign = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}pexemail_campaigns WHERE id = %d", $pexemail_edit_id ) );
            if ( $pexemail_campaign ) {
                $pexemail_subject  = stripslashes( $pexemail_campaign->subject );
                $pexemail_template = stripslashes( $pexemail_campaign->template );
                $pexemail_list_id  = intval( $pexemail_campaign->list_id );
                $pexemail_title    = __( 'Edit Campaign #', 'pexally-email-campaigns' ) . $pexemail_edit_id;
            }
        }

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $pexemail_lists = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}pexemail_lists ORDER BY name ASC" );
    ?>
        <div class="pex-hero">
            <div class="pex-hero-text">
                <h1><?php echo esc_html( $pexemail_title ); ?></h1>
                <p><?php esc_html_e( 'Set your subject, build your email, and select your target list.', 'pexally-email-campaigns' ); ?></p>
            </div>
            <div>
                <a href="?page=pexemail-campaigns" 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="M10 19l-7-7m0 0l7-7m-7 7h18"></path></svg>
                    <?php esc_html_e( 'Back to Campaigns', 'pexally-email-campaigns' ); ?>
                </a>
            </div>
        </div>

        <div class="pex-card">
            <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
                <?php wp_nonce_field( 'pexemail_save_campaign_action', 'pexemail_campaign_nonce' ); ?>
                <input type="hidden" name="action" value="pexemail_save_campaign">
                <input type="hidden" name="campaign_id" value="<?php echo esc_attr( $pexemail_edit_id ); ?>">
                
                <div class="pex-card-body">
                    
                    <div class="pex-form-group">
                        <label class="pex-form-label"><?php esc_html_e( 'Campaign Subject', 'pexally-email-campaigns' ); ?></label>
                        <input type="text" name="campaign_subject" class="pex-input" value="<?php echo esc_attr( $pexemail_subject ); ?>" required placeholder="e.g. Huge Sale Today!">
                        <div class="pex-desc">Pro tip: Use <code>{{first_name}}</code> in the subject for higher open rates!</div>
                    </div>

                    <div class="pex-form-group">
                        <label class="pex-form-label"><?php esc_html_e( 'Contact List', 'pexally-email-campaigns' ); ?></label>
                        <?php if ( empty( $pexemail_lists ) ) : ?>
                            <div class="pex-error-notice" style="max-width: 600px;">
                                <span>⚠️</span>
                                <div>You haven't created any contact lists yet! <a href="?page=pexemail-contacts" style="color: #b91c1c; text-decoration: underline;">Go to Contacts Manager</a>.</div>
                            </div>
                        <?php else : ?>
                            <select name="list_id" class="pex-input" required>
                                <option value="">-- <?php esc_html_e( 'Select a List', 'pexally-email-campaigns' ); ?> --</option>
                                <?php foreach ( $pexemail_lists as $pexemail_list_item ) : ?>
                                    <option value="<?php echo esc_attr( $pexemail_list_item->id ); ?>" <?php selected( $pexemail_list_id, $pexemail_list_item->id ); ?>><?php echo esc_html( $pexemail_list_item->name ); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <div class="pex-desc"><?php esc_html_e( 'Choose the list of subscribers to send this campaign to.', 'pexally-email-campaigns' ); ?></div>
                        <?php endif; ?>
                    </div>
                        
                    <div class="pex-form-group">
                        <label class="pex-form-label"><?php esc_html_e( 'Load Pre-built Template (Optional)', 'pexally-email-campaigns' ); ?></label>
                        <select id="js_template_injector" class="pex-input">
                            <option value="">-- Select a Template to load into Editor --</option>
                            <option value="minimal">1. Standard Minimal</option>
                            <option value="newsletter">2. Weekly Newsletter</option>
                            <option value="promo">3. Flash Sale Promo</option>
                            <option value="announcement">4. Big Announcement</option>
                            <option value="ecommerce">5. E-Commerce Showcase</option>
                            <option value="webinar">6. Webinar / Event</option>
                            <option value="welcome">7. Welcome & Onboarding</option>
                            <option value="alert">8. Urgent Alert</option>
                            <option value="feedback">9. Customer Feedback / Survey</option>
                            <option value="update">10. Software Release Notes</option>
                            <option value="holiday">11. Holiday Greeting</option>
                            <option value="digest">12. Blog Post Digest</option>
                            <option value="reminder">13. Event Reminder</option>
                            <option value="survey">14. Need Your Help</option>
                            <option value="onboarding">15. Onboarding Step 2</option>
                            <option value="coupon">16. Secret Coupon</option>
                            <option value="cart">17. Abandoned Cart</option>
                            <option value="thanks">18. Thank You</option>
                            <option value="vip">19. VIP Invite</option>
                            <option value="recap">20. Monthly Recap</option>
                        </select>
                        <div class="pex-desc" style="color: #ea580c; font-weight: 500;">
                            <?php esc_html_e( 'Warning: Selecting a template will overwrite anything currently typed in the editor box below.', 'pexally-email-campaigns' ); ?>
                        </div>
                    </div>

                    <div class="pex-form-group">
                        <label class="pex-form-label"><?php esc_html_e( 'Email Design Editor', 'pexally-email-campaigns' ); ?></label>
                        <div class="pex-desc" style="margin-bottom:12px;">Available Dynamic Tags: <code>{{first_name}}</code>, <code>{{last_name}}</code>, <code>{{email}}</code></div>
                        
                        <div style="border: 1px solid #cbd5e1; border-radius: 10px; overflow: hidden; max-width: 900px;">
                            <?php wp_editor( htmlspecialchars_decode( $pexemail_template ), 'campaign_template', [ 'textarea_rows' => 22 ] ); ?>
                        </div>
                        
                        <div class="pex-desc" style="margin-top:12px;">
                            <span style="display:inline-block; margin-right:5px;">🛡️</span>
                            <?php esc_html_e( 'Your email will automatically be wrapped securely in your branded Header Logo and Footer from Settings.', 'pexally-email-campaigns' ); ?>
                        </div>
                    </div>

                    <hr style="border: 0; border-top: 1px solid #e2e8f0; margin: 30px 0;">
                    
                    <button type="submit" class="pex-btn-primary" style="padding: 14px 32px; font-size: 16px;">
                        <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="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4"></path></svg>
                        <?php esc_html_e( 'Save Campaign', 'pexally-email-campaigns' ); ?>
                    </button>
                </div>
            </form>
        </div>

        <script>
        jQuery(document).ready(function($) {
            const templateDict = <?php echo json_encode( $pexemail_tpl_html ); ?>;

            $('#js_template_injector').on('change', function() {
                let selectedTpl = $(this).val();
                if (!selectedTpl || !templateDict[selectedTpl]) return;
                
                let htmlContent = templateDict[selectedTpl];
                
                if (typeof tinyMCE !== 'undefined' && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden()) {
                    tinyMCE.activeEditor.setContent(htmlContent);
                } else {
                    $('#campaign_template').val(htmlContent);
                }
            });
        });
        </script>

    <!-- ==========================================
         VIEW 2: LIVE SENDING / STATS PAGE 
         ========================================== -->
    <?php 
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    elseif ( $pexemail_action === 'view' && isset( $_GET['id'] ) ) : 
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $pexemail_campaign_id = intval( $_GET['id'] );

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $pexemail_campaign = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}pexemail_campaigns WHERE id = %d", $pexemail_campaign_id ) );
        if ( ! $pexemail_campaign ) return;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $pexemail_total_recipients  = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}pexemail_recipients WHERE campaign_id = %d", $pexemail_campaign_id ) );
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $pexemail_sent_recipients   = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}pexemail_recipients WHERE campaign_id = %d AND status = 'sent'", $pexemail_campaign_id ) );
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $pexemail_failed_recipients = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}pexemail_recipients WHERE campaign_id = %d AND status = 'failed'", $pexemail_campaign_id ) );
        
        $pexemail_total_processed   = $pexemail_sent_recipients + $pexemail_failed_recipients;

        // FIX: Match the Dashboard Math. Only count unique recipients who opened/clicked.
        $pexemail_total_opens = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}pexemail_recipients WHERE campaign_id = %d AND opened = 1", $pexemail_campaign_id ) );
        $pexemail_total_clicks = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}pexemail_recipients WHERE campaign_id = %d AND clicked = 1", $pexemail_campaign_id ) );

        // Schedule Logic Variables
        $pexemail_is_scheduled = ( $pexemail_campaign->status === 'scheduled' );
        $pexemail_is_sending_cron = ( $pexemail_campaign->status === 'sending_cron' );
        $pexemail_schedule_display = '';
        
        $pexemail_scheduled_at = isset( $pexemail_campaign->scheduled_at ) ? intval( $pexemail_campaign->scheduled_at ) : 0;

        if ( $pexemail_is_scheduled && $pexemail_scheduled_at > 0 ) {
            $pexemail_schedule_display = wp_date( 'd M, Y - h:i A', $pexemail_scheduled_at ) . ' (Local Site Time)';
        }
    ?>
        <div class="pex-hero">
            <div class="pex-hero-text">
                <h1><?php echo esc_html( stripslashes( $pexemail_campaign->subject ) ); ?></h1>
                <p><?php esc_html_e( 'Live Campaign Monitor. Track progress, opens, and clicks.', 'pexally-email-campaigns' ); ?></p>
            </div>
            <div>
                <a href="?page=pexemail-campaigns" 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="M10 19l-7-7m0 0l7-7m-7 7h18"></path></svg>
                    <?php esc_html_e( 'Back to Campaigns', 'pexally-email-campaigns' ); ?>
                </a>
            </div>
        </div>

        <?php if ( $pexemail_is_scheduled ) : ?>
            <div class="pex-info-notice" id="notice-scheduled">
                <span style="font-size: 24px;">📅</span>
                <div>
                    <strong style="display:block; margin-bottom: 4px; font-size: 15px;">Campaign Scheduled Successfully</strong>
                    <span>This campaign is safely locked and will automatically send in the background at: <strong><?php echo esc_html( $pexemail_schedule_display ); ?></strong></span>
                </div>
            </div>
        <?php endif; ?>

        <?php if ( $pexemail_is_sending_cron ) : ?>
            <div class="pex-info-notice">
                <span style="font-size: 24px;">🚀</span>
                <div>
                    <strong style="display:block; margin-bottom: 4px; font-size: 15px;">Cron Engine is Active</strong>
                    <span>This campaign is currently being sent automatically in the background via Server Cron. Refresh to see updated metrics.</span>
                </div>
            </div>
        <?php endif; ?>

        <?php if ( $pexemail_failed_recipients > 0 ) : ?>
            <div class="pex-error-notice">
                <span style="font-size: 20px;">⚠️</span>
                <div><strong>Warning:</strong> <?php echo esc_html( $pexemail_failed_recipients ); ?> emails failed to send. Check your SMTP Settings.</div>
            </div>
        <?php endif; ?>

        <!-- Metrics Grid -->
        <div class="pex-metrics-grid">
            <div class="pex-metric-card">
                <div class="pex-metric-top">
                    <span class="pex-metric-label">Total Recipients</span>
                    <div class="pex-metric-icon-wrap ic-gray">
                        <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="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path></svg>
                    </div>
                </div>
                <span class="pex-metric-value" id="stat-total"><?php echo esc_html( $pexemail_total_recipients ); ?></span>
            </div>
            
            <div class="pex-metric-card">
                <div class="pex-metric-top">
                    <span class="pex-metric-label">Successfully Queued/Sent</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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                    </div>
                </div>
                <span class="pex-metric-value" id="stat-sent" style="color: #059669;"><?php echo esc_html( $pexemail_sent_recipients ); ?></span>
            </div>

            <div class="pex-metric-card">
                <div class="pex-metric-top">
                    <span class="pex-metric-label">Opened</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="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" style="color: #2563eb;"><?php echo esc_html( $pexemail_total_opens ); ?></span>
            </div>

            <div class="pex-metric-card">
                <div class="pex-metric-top">
                    <span class="pex-metric-label">Clicked Links</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" style="color: #7c3aed;"><?php echo esc_html( $pexemail_total_clicks ); ?></span>
            </div>
        </div>

        <!-- Live Sending Panel -->
        <div class="pex-card">
            <div class="pex-card-header">
                <h2>Live Sending Engine</h2>
            </div>
            <div class="pex-card-body">
                
                <div class="pex-status-bar">
                    <div class="pex-status-left" id="sending-status-text">
                        <?php 
                        if ( $pexemail_is_scheduled ) {
                            echo '<span style="color:#d97706;">Waiting for Schedule Cron Engine...</span>';
                        } elseif ( $pexemail_is_sending_cron ) {
                            echo '<span style="color:#2563eb;">Processing via Background Server Cron...</span>';
                        } elseif ( $pexemail_total_processed >= $pexemail_total_recipients && $pexemail_total_recipients > 0 ) {
                            if ( $pexemail_failed_recipients > 0 ) {
                                echo '<span style="color:#dc2626;">Finished, but ' . esc_html( $pexemail_failed_recipients ) . ' emails FAILED.</span>';
                            } else {
                                echo '<span style="color:#059669;">Campaign Queued Successfully!</span>';
                            }
                        } else {
                            echo 'Ready to process.';
                        }
                        ?>
                    </div>
                </div>

                <div class="pex-progress-wrap" id="progress-container" <?php if ( $pexemail_total_processed > 0 ) echo 'style="display:block;"'; else echo 'style="display:none;"'; ?>>
                    <?php $pexemail_percent = $pexemail_total_recipients > 0 ? ( $pexemail_total_processed / $pexemail_total_recipients ) * 100 : 0; ?>
                    <div class="pex-progress-bar" id="progress-bar" style="width: <?php echo esc_attr( $pexemail_percent ); ?>%;">
                        <?php echo esc_html( round( $pexemail_percent ) ); ?>%
                    </div>
                </div>

                <div style="margin-top: 30px; display:flex; align-items:center; flex-wrap:wrap; gap:12px;">
                    
                    <button id="start-sending-btn" class="pex-action-play" <?php if ( $pexemail_total_processed >= $pexemail_total_recipients || $pexemail_is_scheduled || $pexemail_is_sending_cron ) echo 'style="display:none;" disabled'; ?>>
                        <svg width="20" height="20" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z" clip-rule="evenodd"></path></svg>
                        Start Sending
                    </button>
                    
                    <button id="show-schedule-btn" class="pex-btn-secondary" <?php if ( $pexemail_total_processed > 0 || $pexemail_is_scheduled || $pexemail_is_sending_cron ) echo 'style="display:none;" disabled'; ?>>
                        <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="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
                        Schedule for Later
                    </button>

                    <button id="cancel-schedule-btn" class="pex-btn-secondary" style="border-color:#ef4444; color:#ef4444; <?php echo $pexemail_is_scheduled ? 'display:inline-flex;' : 'display:none;'; ?>">
                        Cancel Scheduled Send
                    </button>

                    <button id="pause-sending-btn" class="pex-action-pause" style="display:none;">
                        <svg width="20" height="20" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zM7 8a1 1 0 012 0v4a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v4a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd"></path></svg>
                        Pause
                    </button>
                    
                    <button id="stop-sending-btn" class="pex-action-stop" style="display:none;">
                        <svg width="20" height="20" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8 7a1 1 0 00-1 1v4a1 1 0 001 1h4a1 1 0 001-1V8a1 1 0 00-1-1H8z" clip-rule="evenodd"></path></svg>
                        Stop
                    </button>

                    <button id="retry-failed-btn" class="pex-action-retry" style="<?php echo ( $pexemail_failed_recipients > 0 && $pexemail_total_processed >= $pexemail_total_recipients ) ? 'display:inline-flex;' : 'display:none;'; ?>">
                        <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="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path></svg>
                        Retry Failed Emails
                    </button>
                    
                </div>

                <!-- Schedule Panel Modal (Hidden by default) -->
                <div id="schedule-panel-ui" style="display:none; background:#f8fafc; padding:25px; border-radius:12px; margin-top:20px; border:1px solid #e2e8f0; box-shadow:inset 0 2px 4px rgba(0,0,0,0.02);">
                    <h3 style="margin:0 0 20px; font-size:16px; color:#0f172a;">Pick a Date, Time, and World Timezone</h3>
                    
                    <div style="display:flex; gap:20px; margin-bottom:20px; flex-wrap:wrap;">
                        <div>
                            <label class="pex-form-label">Send Date</label>
                            <input type="date" id="sched-date" class="pex-input" style="width:160px; padding:10px 14px;">
                        </div>
                        <div>
                            <label class="pex-form-label">Send Time</label>
                            <input type="time" id="sched-time" class="pex-input" style="width:140px; padding:10px 14px;">
                        </div>
                        <div style="flex-grow: 1; max-width: 350px;">
                            <label class="pex-form-label">Global Timezone</label>
                            <select id="sched-timezone" class="pex-input" style="padding:10px 14px;">
                                <?php 
                                if ( function_exists('wp_timezone_choice') ) {
                                    echo wp_timezone_choice( wp_timezone_string() ); 
                                } else {
                                    echo '<option value="UTC">UTC</option>';
                                }
                                ?>
                            </select>
                        </div>
                    </div>

                    <div style="display:flex; gap:12px;">
                        <button id="confirm-schedule-btn" class="pex-btn-primary" style="padding:10px 24px;">Confirm Schedule</button>
                        <button id="hide-schedule-btn" class="pex-btn-secondary" style="background:#ffffff; border-color:#cbd5e1; color:#64748b; padding:10px 24px;">Cancel</button>
                    </div>
                </div>

            </div>
        </div>

        <script>
        jQuery(document).ready(function($) {
            let totalRecipients = parseInt($('#stat-total').text()) || 0;
            let sentRecipients = parseInt($('#stat-sent').text()) || 0;
            let totalProcessed = <?php echo intval( $pexemail_total_processed ); ?>;
            let batchSize = 50; // Sync with PHP SaaS batch size
            
            window.pexIsPaused = false;
            window.pexIsStopped = false;
            window.pexTimeout = null;

            $('#toggle-failed-list').on('click', function(e) {
                e.preventDefault();
                $('#failed-emails-container').slideToggle();
            });

            // Calculate ETA based on SaaS API batching speed (~2 seconds per batch roundtrip)
            function getEtaText(remainingCount) {
                if (remainingCount <= 0) return "";
                let batchesLeft = Math.ceil(remainingCount / batchSize);
                let secondsLeft = batchesLeft * 2; 
                
                let h = Math.floor(secondsLeft / 3600);
                let m = Math.floor((secondsLeft % 3600) / 60);
                let s = secondsLeft % 60;
                
                let timeArr = [];
                if (h > 0) timeArr.push(h + " hr");
                if (m > 0) timeArr.push(m + " min");
                if (s > 0 && h === 0) timeArr.push(s + " sec"); 
                
                if (timeArr.length === 0) return "";
                return " | ETA: " + timeArr.join(" ");
            }

            // SCHEDULING UI LOGIC
            $('#show-schedule-btn').on('click', function(e) {
                e.preventDefault();
                $('#schedule-panel-ui').slideDown();
                $(this).hide();
            });

            $('#hide-schedule-btn').on('click', function(e) {
                e.preventDefault();
                $('#schedule-panel-ui').slideUp();
                $('#show-schedule-btn').show();
            });

            $('#confirm-schedule-btn').on('click', function(e) {
                e.preventDefault();
                let sDate = $('#sched-date').val();
                let sTime = $('#sched-time').val();
                let sTz   = $('#sched-timezone').val();

                if (!sDate || !sTime || !sTz) {
                    alert("Please fill out the Date, Time, and Timezone.");
                    return;
                }

                $(this).text("Saving...").prop('disabled', true);

                $.post(pexEmailGlobal.ajax_url, {
                    action: 'pexemail_schedule_campaign',
                    campaign_id: <?php echo intval( $pexemail_campaign->id ); ?>,
                    date: sDate,
                    time: sTime,
                    timezone: sTz,
                    _ajax_nonce: pexEmailGlobal.nonce_admin 
                }, function(res) {
                    if(res.success) {
                        location.reload(); 
                    } else {
                        alert(res.data);
                        $('#confirm-schedule-btn').text("Confirm Schedule").prop('disabled', false);
                    }
                });
            });

            $('#cancel-schedule-btn').on('click', function(e) {
                e.preventDefault();
                if(!confirm("Are you sure you want to cancel the scheduled deployment?")) return;
                
                $(this).text("Cancelling...").prop('disabled', true);
                $.post(pexEmailGlobal.ajax_url, {
                    action: 'pexemail_cancel_schedule',
                    campaign_id: <?php echo intval( $pexemail_campaign->id ); ?>,
                    _ajax_nonce: pexEmailGlobal.nonce_admin 
                }, function(res) {
                    location.reload(); 
                });
            });

            // BROWSER SENDING LOGIC
            $('#start-sending-btn').on('click', function(e) {
                e.preventDefault();
                if(totalProcessed >= totalRecipients) return;
                
                window.pexIsPaused = false;
                window.pexIsStopped = false;
                $(this).hide();
                $('#show-schedule-btn').hide();
                $('#pause-sending-btn').show();
                $('#stop-sending-btn').show();
                $('#progress-container').show();
                
                $('#sending-status-text').html('Pushing to Delivery Engine...').css('color', '#0f172a');
                $('#progress-bar').css('background-color', '#10b981').addClass('is-sending');
                sendBatch();
            });

            $('#pause-sending-btn').on('click', function(e) {
                e.preventDefault();
                window.pexIsPaused = true;
                clearTimeout(window.pexTimeout);
                $(this).hide();
                $('#stop-sending-btn').hide();
                $('#start-sending-btn').html('<svg width="20" height="20" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z" clip-rule="evenodd"></path></svg> Resume Sending').show();
                $('#sending-status-text').html('<span style="color:#d97706;">Paused by user.</span>');
                $('#progress-bar').removeClass('is-sending');
            });

            $('#stop-sending-btn').on('click', function(e) {
                e.preventDefault();
                window.pexIsStopped = true;
                clearTimeout(window.pexTimeout);
                $(this).hide();
                $('#pause-sending-btn').hide();
                $('#start-sending-btn').html('<svg width="20" height="20" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8 7a1 1 0 00-1 1v4a1 1 0 001 1h4a1 1 0 001-1V8a1 1 0 00-1-1H8z" clip-rule="evenodd"></path></svg> Start Sending').show();
                $('#sending-status-text').html('<span style="color:#dc2626;">Stopped by user.</span>');
                $('#progress-bar').removeClass('is-sending');
            });

            $('#retry-failed-btn').on('click', function(e) {
                e.preventDefault();
                if (!confirm("This will reset all failed emails to 'pending' and attempt to send them again. Continue?")) return;
                $(this).html('Resetting...').attr('disabled', true);
                
                $.post(pexEmailGlobal.ajax_url, {
                    action: 'pexemail_retry_failed_campaign', 
                    campaign_id: <?php echo intval( $pexemail_campaign->id ); ?>,
                    _ajax_nonce: pexEmailGlobal.nonce_admin 
                }, function(res) {
                    if (res.success) location.reload(); 
                });
            });

            function sendBatch() {
                if (window.pexIsPaused || window.pexIsStopped) return;

                $.ajax({
                    url: pexEmailGlobal.ajax_url,
                    type: 'POST',
                    data: { action: 'pexemail_send_campaign_batch', campaign_id: <?php echo intval( $pexemail_campaign->id ); ?>, _ajax_nonce: pexEmailGlobal.nonce_admin },
                    success: function(response) {
                        if (window.pexIsPaused || window.pexIsStopped) return;

                        if (response.success) {
                            if (response.data.status === 'processing') {
                                sentRecipients += response.data.sent_this_batch;
                                totalProcessed += response.data.processed_this_batch;
                                
                                let remaining = totalRecipients - totalProcessed;
                                let percent = ((totalProcessed / totalRecipients) * 100).toFixed(0);
                                let etaText = getEtaText(remaining);
                                
                                $('#stat-sent').text(sentRecipients);
                                $('#progress-bar').css('width', percent + '%').text(percent + '%');
                                $('#sending-status-text').text('Queued ' + totalProcessed + ' of ' + totalRecipients + ' to Delivery Engine...' + etaText);
                                
                                // Batch process every 1s since we are just sending to an API now
                                window.pexTimeout = setTimeout(sendBatch, 1000); 
                            } else if (response.data.status === 'completed') {
                                $('#progress-bar').css('width', '100%').text('100%').removeClass('is-sending');
                                $('#pause-sending-btn').hide();
                                $('#stop-sending-btn').hide();
                                
                                if (sentRecipients < totalRecipients) {
                                    let failed = totalRecipients - sentRecipients;
                                    $('#sending-status-text').html('<span style="color:#dc2626;">Finished, but ' + failed + ' emails FAILED. Check API connection.</span>');
                                    $('#progress-bar').css('background-color', '#dc2626');
                                    $('#retry-failed-btn').show();
                                } else {
                                    $('#sending-status-text').html('<span style="color:#059669;">Campaign Queued Successfully!</span>');
                                    $('#start-sending-btn').hide();
                                }
                            }
                        } else {
                            // This catches the Pexally Central API limit/error messages!
                            $('#progress-bar').css('background-color', '#f59e0b').removeClass('is-sending');
                            $('#sending-status-text').html('<span style="color:#b91c1c;"><strong>Stopped:</strong> ' + response.data + '</span>');
                            $('#pause-sending-btn').hide();
                            $('#stop-sending-btn').hide();
                            $('#start-sending-btn').html('<svg width="20" height="20" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z" clip-rule="evenodd"></path></svg> Resume Sending').show();
                            window.pexIsPaused = true;
                        }
                    },
                    error: function() {
                        if (window.pexIsPaused || window.pexIsStopped) return;
                        $('#sending-status-text').html('<span style="color:#dc2626;">Network error. Retrying in 5s...</span>');
                        window.pexTimeout = setTimeout(sendBatch, 5000);
                    }
                });
            }
        });
        </script>

    <!-- ==========================================
         VIEW 3: MAIN CAMPAIGNS LIST TABLE 
         ========================================== -->
    <?php else : 
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $pexemail_campaigns = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}pexemail_campaigns ORDER BY id DESC" );
    ?>
        <div class="pex-hero">
            <div class="pex-hero-text">
                <h1><?php esc_html_e( 'All Campaigns', 'pexally-email-campaigns' ); ?></h1>
                <p><?php esc_html_e( 'Manage your drafts, view sending progress, or duplicate past campaigns.', 'pexally-email-campaigns' ); ?></p>
            </div>
            <div>
                <a href="?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( 'Add New Campaign', 'pexally-email-campaigns' ); ?>
                </a>
            </div>
        </div>

        <?php if ( empty( $pexemail_campaigns ) ) : ?>
            
            <div class="pex-empty-state">
                <div class="pex-empty-icon-wrap">
                    <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="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path></svg>
                </div>
                <h3><?php esc_html_e( 'No Campaigns Yet', 'pexally-email-campaigns' ); ?></h3>
                <p><?php esc_html_e( 'You haven\'t created any email campaigns. Start engaging your audience by creating your first beautifully designed campaign today!', 'pexally-email-campaigns' ); ?></p>
                <a href="?page=pexemail-campaigns-add" class="pex-btn-primary" style="padding:14px 28px; font-size:16px;">
                    + <?php esc_html_e( 'Create Your First Campaign', 'pexally-email-campaigns' ); ?>
                </a>
            </div>

        <?php else : ?>

            <div class="pex-card">
                <div class="pex-card-body" style="padding:0;">
                    <table class="pex-table">
                        <thead>
                            <tr>
                                <th><?php esc_html_e( 'ID', 'pexally-email-campaigns' ); ?></th>
                                <th><?php esc_html_e( 'Subject', 'pexally-email-campaigns' ); ?></th>
                                <th><?php esc_html_e( 'Status', 'pexally-email-campaigns' ); ?></th>
                                <th><?php esc_html_e( 'Date Created', 'pexally-email-campaigns' ); ?></th>
                                <th style="text-align:right; width: 350px;"><?php esc_html_e( 'Actions', 'pexally-email-campaigns' ); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ( $pexemail_campaigns as $pexemail_c ) : 
                                $pexemail_delete_url = wp_nonce_url( admin_url( 'admin-post.php?action=pexemail_delete_campaign&id=' . $pexemail_c->id ), 'pexemail_delete_campaign_action', 'pexemail_delete_nonce' );
                                $pexemail_duplicate_url = wp_nonce_url( admin_url( 'admin-post.php?action=pexemail_duplicate_campaign&id=' . $pexemail_c->id ), 'pexemail_duplicate_campaign_action', 'pexemail_duplicate_nonce' );
                                
                                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                                $pexemail_total_recs = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}pexemail_recipients WHERE campaign_id = %d", $pexemail_c->id ) );
                                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                                $pexemail_processed_recs = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}pexemail_recipients WHERE campaign_id = %d AND status != 'pending'", $pexemail_c->id ) );
                                
                                $pexemail_badge_text = 'Draft';
                                $pexemail_badge_color = '#64748b';
                                $pexemail_badge_bg = '#f1f5f9';

                                if ( $pexemail_c->status === 'scheduled' ) {
                                    $pexemail_badge_text = 'Scheduled';
                                    $pexemail_badge_color = '#d97706';
                                    $pexemail_badge_bg = '#fef3c7';
                                } elseif ( $pexemail_c->status === 'sending_cron' ) {
                                    $pexemail_badge_text = 'Cron Active';
                                    $pexemail_badge_color = '#2563eb';
                                    $pexemail_badge_bg = '#eff6ff';
                                } elseif ( $pexemail_total_recs > 0 && $pexemail_processed_recs >= $pexemail_total_recs ) {
                                    $pexemail_badge_text = 'Completed';
                                    $pexemail_badge_color = '#059669';
                                    $pexemail_badge_bg = '#ecfdf5';
                                } elseif ( $pexemail_processed_recs > 0 && $pexemail_processed_recs < $pexemail_total_recs ) {
                                    $pexemail_percent = round( ( $pexemail_processed_recs / $pexemail_total_recs ) * 100 );
                                    $pexemail_badge_text = 'Sending (' . $pexemail_percent . '%)';
                                    $pexemail_badge_color = '#2563eb';
                                    $pexemail_badge_bg = '#eff6ff';
                                }
                            ?>
                                <tr>
                                    <td><strong>#<?php echo esc_html( $pexemail_c->id ); ?></strong></td>
                                    <td style="font-weight:600; color:#0f172a; max-width:280px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;" title="<?php echo esc_attr( stripslashes( $pexemail_c->subject ) ); ?>">
                                        <?php echo esc_html( stripslashes( $pexemail_c->subject ) ); ?>
                                    </td>
                                    <td>
                                        <span class="pex-badge" style="color:<?php echo esc_attr( $pexemail_badge_color ); ?>; background:<?php echo esc_attr( $pexemail_badge_bg ); ?>;">
                                            <?php echo esc_html( $pexemail_badge_text ); ?>
                                        </span>
                                    </td>
                                    <!-- FIX: Added Time to Date Created -->
                                    <td style="font-size: 13.5px;"><?php echo esc_html( wp_date( 'd M, Y - h:i A', strtotime( $pexemail_c->created_at ), $pexemail_tz ) ); ?></td>
                                    <td style="text-align:right;">
                                        <a href="?page=pexemail-campaigns&action=view&id=<?php echo esc_attr( $pexemail_c->id ); ?>" class="pex-action-pill pex-pill-view">View</a>
                                        <a href="?page=pexemail-campaigns-add&id=<?php echo esc_attr( $pexemail_c->id ); ?>" class="pex-action-pill pex-pill-edit">Edit</a>
                                        <a href="<?php echo esc_url( $pexemail_duplicate_url ); ?>" class="pex-action-pill pex-pill-dup">Duplicate</a>
                                        <a href="<?php echo esc_url( $pexemail_delete_url ); ?>" class="pex-action-pill pex-pill-del" onclick="return confirm('Are you sure you want to delete this campaign?');">Delete</a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endif; ?>

    <?php endif; ?>

</div>