<?php

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

wp_enqueue_style( 'x4email-admin-modern', plugins_url( 'assets/css/admin-modern.css', dirname( __DIR__ ) ), array(), X4EMAIL_LITE_VER );
wp_enqueue_script( 'chart-js', plugins_url( 'assets/js/chart.min.js', dirname( __DIR__ ) ), array(), X4EMAIL_LITE_VER, true );

global $wpdb;
$table_name = esc_sql( $wpdb->prefix . 'x4email_logs_lite' );

// Get total, success, failed counts.
$sanitized_table = esc_sql( $table_name );
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Table name is hardcoded and escaped, custom table query for dashboard stats, real-time data needed.
$total_emails = (int) $wpdb->get_var( "SELECT COUNT(*) FROM `$sanitized_table`" );
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Table name is hardcoded and escaped, custom table query for dashboard stats, real-time data needed.
$success_emails = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM `$sanitized_table` WHERE status = %s", 'Successful' ) );
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Table name is hardcoded and escaped, custom table query for dashboard stats, real-time data needed.
$failed_emails = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM `$sanitized_table` WHERE status = %s", 'Failed to send' ) );

$success_rate = $total_emails > 0 ? round( ( $success_emails / $total_emails ) * 100 ) : 0;

// Get last 7 days stats for bar/line chart.
$days            = array();
$sent_per_day    = array();
$success_per_day = array();
$failed_per_day  = array();

for ( $i = 6; $i >= 0; $i-- ) {
	$date   = date_i18n( 'Y-m-d', strtotime( "-$i days" ) );
	$days[] = $date;

    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Table name is hardcoded and escaped, custom table query for dashboard charts, real-time data needed.
	$sent_per_day[] = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM `$sanitized_table` WHERE DATE(sent_at) = %s", $date ) );

    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Table name is hardcoded and escaped, custom table query for dashboard charts, real-time data needed.
	$success_per_day[] = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM `$sanitized_table` WHERE DATE(sent_at) = %s AND status = %s", $date, 'Successful' ) );

    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Table name is hardcoded and escaped, custom table query for dashboard charts, real-time data needed.
	$failed_per_day[] = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM `$sanitized_table` WHERE DATE(sent_at) = %s AND status = %s", $date, 'Failed to send' ) );
}

?>
<div class="x4email-admin" style="min-height:100vh; background: var(--color-bg); padding: 2.5rem 0;">
	<div style="max-width: 1100px; margin: 0 auto;">
	<div class="x4email-title" style="display:flex;align-items:center;justify-content:space-between;gap:0.75em;flex-direction:row;">
		<div style="display:flex;flex-direction:column;align-items:flex-start;">
		<h1 style="color:#fff;"><?php echo esc_html__( 'X4EMAIL Dashboard', 'x4email-lite' ); ?></h1>
		<span style="font-size:1.1rem;color:#fff;opacity:0.9;margin-top:0.25em;letter-spacing:0.01em;">
			<?php echo esc_html__( 'Welcome to your email management hub. Configure SMTP, view logs, manage hooks, and more.', 'x4email-lite' ); ?>
		</span>
		</div>
		<span style="font-size:3.5em;opacity:0.95;line-height:1;display:flex;align-items:center;justify-content:center;">
		<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="white" stroke-width="2" width="48" height="48"><path stroke-linecap="round" stroke-linejoin="round" d="M3 8l7.89 5.26a3 3 0 003.22 0L22 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/></svg>
		</span>
	</div>

	<!-- Metrics Section -->
	<div class="x4email-flex x4email-gap-lg" style="flex-wrap:wrap; margin-bottom:2.5rem;">
		<div class="x4email-card x4email-box-shadow" style="flex:1 1 180px; min-width:160px; text-align:center;">
		<div style="font-size:2.2em; color:#1976d2; font-weight:700;"><?php echo number_format( $total_emails ); ?></div>
		<div style="font-size:1em; color:#444; margin-top:0.5em;">
			<?php echo esc_html__( 'Total Emails Sent', 'x4email-lite' ); ?>
		</div>
		</div>
		<div class="x4email-card x4email-box-shadow" style="flex:1 1 180px; min-width:160px; text-align:center;">
		<div style="font-size:2.2em; color:#22c55e; font-weight:700;"><?php echo esc_html( $success_rate ); ?>%</div>
		<div style="font-size:1em; color:#444; margin-top:0.5em;">
			<?php echo esc_html__( 'Success Rate', 'x4email-lite' ); ?>
		</div>
		</div>
		<div class="x4email-card x4email-box-shadow" style="flex:1 1 180px; min-width:160px; text-align:center;">
		<div style="font-size:2.2em; color:#ef4444; font-weight:700;"><?php echo number_format( $failed_emails ); ?></div>
		<div style="font-size:1em; color:#444; margin-top:0.5em;">
			<?php echo esc_html__( 'Failed Emails', 'x4email-lite' ); ?>
		</div>
		</div>
	</div>
	<!-- Charts Section -->
	<div style="margin-bottom:2.5rem; position:relative;">
		<div id="x4email-charts-blur" style="position:absolute;top:0;left:0;width:100%;height:100%;z-index:2;display:flex;align-items:center;justify-content:center;pointer-events:auto;flex-direction:column;">
		<div style="background:rgba(255,255,255,0.95);padding:2em 3em 1.5em 3em;border-radius:12px;box-shadow:0 2px 12px 0 rgba(25,118,210,0.10);font-size:1.3em;color:#1976d2;font-weight:700;text-align:center;display: flex;flex-direction: column;">
			<?php echo esc_html__( 'Upgrade to Pro to see the charts', 'x4email-lite' ); ?>    
		<a href="<?php echo defined( 'X4EMAIL_PRO_URL' ) ? esc_url( X4EMAIL_PRO_URL ) : 'https://x4digital.io/'; ?>" target="_blank" class="x4email-btn" style="margin-top:1.5em;font-size:1.1em;font-weight:700;padding:0.7em 2.2em;">
			<?php echo esc_html__( 'Upgrade Now', 'x4email-lite' ); ?>
		</a>

		</div>
		</div>
		<div style="filter: blur(5px); pointer-events: none; opacity: 0.7;">
		<div class="x4email-card x4email-box-shadow" style="margin-bottom:2rem;display:flex;flex-direction:column;justify-content:center;align-items:center;">
			<h3 style="margin-bottom:1em;align-self:flex-start;">
			<?php echo esc_html__( 'Emails Sent Per Day (Last 7 Days)', 'x4email-lite' ); ?>
			</h3>
			<canvas id="x4email-bar" width="900" height="220"></canvas>
		</div>
		<div class="x4email-flex x4email-gap-lg" style="flex-wrap:nowrap;align-items:stretch;">
			<div class="x4email-card x4email-box-shadow" style="flex:0 1 30%;min-width:200px;max-width:340px;display:flex;flex-direction:column;align-items:center;justify-content:center;">
			<canvas id="x4email-piechart" width="180" height="180" style="margin-bottom:0.5em;"></canvas>
			<div style="font-size:1em; color:#444; margin-top:0.5em;">
				<?php echo esc_html__( 'Delivery Success vs Failed', 'x4email-lite' ); ?>
			</div>
			</div>
			<div class="x4email-card x4email-box-shadow" style="flex:1 1 70%;min-width:260px;max-width:1000px;display:flex;flex-direction:column;align-items:center;justify-content:center;">
			<h3 style="margin-bottom:1em;align-self:flex-start;">
				<?php echo esc_html__( 'Success Rate (Last 7 Days)', 'x4email-lite' ); ?>
			</h3>
			<canvas id="x4email-line" width="600" height="180"></canvas>
			</div>
		</div>
		</div>
	</div>

	<div class="x4email-flex x4email-gap-lg" style="flex-wrap:wrap;">
		<div class="x4email-card x4email-box-shadow" style="flex:1 1 320px; min-width:260px;">
		<h2 style="font-size:1.2em;display:flex;align-items:center;gap:0.5em;margin-bottom:1em;">
			<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24"><path stroke="#1976d2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M3 8l7.89 5.26a3 3 0 003.22 0L22 8"/><rect x="5" y="7" width="14" height="10" rx="2" stroke="#1976d2" stroke-width="2"/></svg>
			<?php echo esc_html__( 'SMTP Settings', 'x4email-lite' ); ?>
		</h2>
		<p><?php echo esc_html__( 'Configure your outgoing email server and test email delivery.', 'x4email-lite' ); ?></p>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=x4email-settings' ) ); ?>" class="x4email-btn" style="margin-top:1em;">
			<?php echo esc_html__( 'Go to SMTP Settings', 'x4email-lite' ); ?>
		</a>
		</div>
		<div class="x4email-card x4email-box-shadow" style="flex:1 1 320px; min-width:260px;">
		<h2 style="font-size:1.2em;display:flex;align-items:center;gap:0.5em;margin-bottom:1em;">
			<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="2" stroke="#1976d2" stroke-width="2"/><path stroke="#1976d2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M3 7l9 6 9-6"/></svg>
			<?php echo esc_html__( 'Email Logs', 'x4email-lite' ); ?>
		</h2>
		<p><?php echo esc_html__( 'View a record of all outgoing emails and their delivery status.', 'x4email-lite' ); ?></p>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=x4email-logs' ) ); ?>" class="x4email-btn" style="margin-top:1em;">
			<?php echo esc_html__( 'View Logs', 'x4email-lite' ); ?>
		</a>
		</div>
		<div class="x4email-card x4email-box-shadow" style="flex:1 1 320px; min-width:260px;">
		<h2 style="font-size:1.2em;display:flex;align-items:center;gap:0.5em;margin-bottom:1em;">
			<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24"><path stroke="#1976d2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M16.862 3.487a2.25 2.25 0 0 1 3.182 3.182l-13.5 13.5a2.25 2.25 0 0 1-3.182-3.182l13.5-13.5z"/></svg>
			<?php echo esc_html__( 'Email Hooks', 'x4email-lite' ); ?>
		</h2>
		<p><?php echo esc_html__( 'Enable, disable, and customize WooCommerce email notifications.', 'x4email-lite' ); ?></p>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=x4email-hooks' ) ); ?>" class="x4email-btn" style="margin-top:1em;">
			<?php echo esc_html__( 'Manage Hooks', 'x4email-lite' ); ?>
		</a>
		</div>
		<div class="x4email-card x4email-box-shadow" style="flex:1 1 320px; min-width:260px;">
		<h2 style="font-size:1.2em;display:flex;align-items:center;gap:0.5em;margin-bottom:1em;">
			<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24"><rect x="4" y="4" width="16" height="16" rx="2" stroke="#1976d2" stroke-width="2"/><path stroke="#1976d2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M8 8h8v8H8z"/></svg>
			<?php echo esc_html__( 'Template Editor', 'x4email-lite' ); ?>
		</h2>
		<p><?php echo esc_html__( 'Edit and customize your email templates for WooCommerce and system emails.', 'x4email-lite' ); ?></p>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=x4email-template-editor' ) ); ?>" class="x4email-btn" style="margin-top:1em;">
			<?php echo esc_html__( 'Open Template Editor', 'x4email-lite' ); ?>
		</a>
		</div>
		<div class="x4email-card x4email-box-shadow" style="flex:1 1 320px; min-width:260px;">
		<h2 style="font-size:1.2em;display:flex;align-items:center;gap:0.5em;margin-bottom:1em;">
			<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24"><rect width="24" height="24" fill="none"/><path d="M17 11V7a5 5 0 0 0-10 0v4" stroke="#1976d2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><rect x="5" y="11" width="14" height="9" rx="2" stroke="#1976d2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><circle cx="12" cy="15.5" r="1.5" fill="#1976d2"/></svg>
			<?php echo esc_html__( 'Security (Pro)', 'x4email-lite' ); ?>
		</h2>
		<p><?php echo esc_html__( 'Protect your admin area with login notifications and two-factor authentication.', 'x4email-lite' ); ?> <span style="color:#ef4444;font-weight:600;"><?php echo esc_html__( 'Pro Only', 'x4email-lite' ); ?></span></p>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=x4email-security' ) ); ?>" class="x4email-btn-outline" style="margin-top:1em;">
			<?php echo esc_html__( 'View Security', 'x4email-lite' ); ?>
		</a>
		</div>
		<div class="x4email-card x4email-box-shadow" style="flex:1 1 320px; min-width:260px; background: linear-gradient(90deg, #1976d2 0%, #60a5fa 100%); color: #fff;">
		<h2 style="font-size:1.2em;display:flex;align-items:center;gap:0.5em;margin-bottom:1em; color:white;">
			<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24"><path stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4"/></svg>
			<?php echo esc_html__( 'Upgrade to Pro', 'x4email-lite' ); ?>
		</h2>
		<p style="color:#fff;">
			<?php echo esc_html__( 'Unlock advanced features: full logs, filters, security, and more.', 'x4email-lite' ); ?>
		</p>
		<a href="<?php echo defined( 'X4EMAIL_PRO_URL' ) ? esc_url( X4EMAIL_PRO_URL ) : 'https://x4digital.io/'; ?>" target="_blank" class="x4email-btn" style="background:#fff;color:#1976d2;font-weight:700;margin-top:1em;">
			<?php echo esc_html__( 'Upgrade Now', 'x4email-lite' ); ?>
		</a>
		</div>
	</div>
	</div>
</div>

<?php
// Add inline script for charts.
$chart_script = "
document.addEventListener('DOMContentLoaded', function() {
  // Get modern palette colors from CSS variables.
  var rootStyles = getComputedStyle(document.documentElement);
  var colorSuccess = rootStyles.getPropertyValue('--color-green-600').trim() || '#22c55e';
  var colorFailed = rootStyles.getPropertyValue('--color-red-600').trim() || '#ef4444';

  // Pie (Doughnut) chart.
  var ctxPie = document.getElementById('x4email-piechart').getContext('2d');
  new Chart(ctxPie, {
    type: 'doughnut',
    data: {
      labels: ['Successful', 'Failed'],
      datasets: [{
        data: [120, 30], // FAKE DATA: 120 successful, 30 failed
        backgroundColor: [colorSuccess, colorFailed],
        borderWidth: 0,
        hoverOffset: 8
      }]
    },
    options: {
      cutout: '70%',
      plugins: {
        legend: {
          display: true,
          position: 'bottom',
          labels: {
            color: '#222',
            font: { size: 15, weight: 'bold' },
            boxWidth: 18,
            padding: 18
          }
        },
        tooltip: {
          backgroundColor: '#fff',
          titleColor: '#1976d2',
          bodyColor: '#222',
          borderColor: '#1976d2',
          borderWidth: 1,
          padding: 12,
          bodyFont: { size: 15 }
        }
      },
      animation: {
        animateRotate: true,
        duration: 1200,
        easing: 'easeOutQuart'
      },
      responsive: false,
      maintainAspectRatio: false
    }
  });

  // Bar chart (emails per day).
  var ctxBar = document.getElementById('x4email-bar').getContext('2d');
  new Chart(ctxBar, {
    type: 'bar',
    data: {
      labels: ['2024-06-01', '2024-06-02', '2024-06-03', '2024-06-04', '2024-06-05', '2024-06-06', '2024-06-07'], // FAKE DATES
      datasets: [
        {
          label: 'Total',
          data: [30, 45, 50, 38, 60, 55, 70], // FAKE DATA
          backgroundColor: 'rgba(25,118,210,0.85)',
          borderRadius: 10,
          barPercentage: 0.6,
          categoryPercentage: 0.6,
        },
        {
          label: 'Successful',
          data: [28, 40, 47, 18, 58, 53, 65], // FAKE DATA
          backgroundColor: 'rgba(34,197,94,0.85)',
          borderRadius: 10,
          barPercentage: 0.6,
          categoryPercentage: 0.6,
        },
        {
          label: 'Failed',
          data: [2, 5, 3, 20, 2, 2, 5], // FAKE DATA
          backgroundColor: 'rgba(239,68,68,0.85)',
          borderRadius: 10,
          barPercentage: 0.6,
          categoryPercentage: 0.6,
        }
      ]
    },
    options: {
      plugins: {
        legend: {
          display: true,
          position: 'bottom',
          labels: {
            color: '#222',
            font: { size: 14, weight: 'bold' },
            boxWidth: 16,
            padding: 14
          }
        },
        tooltip: {
          backgroundColor: '#fff',
          titleColor: '#1976d2',
          bodyColor: '#222',
          borderColor: '#1976d2',
          borderWidth: 1,
          padding: 12,
          bodyFont: { size: 15 }
        }
      },
      responsive: false,
      maintainAspectRatio: false,
      scales: {
        x: {
          stacked: true,
          grid: { display: false },
          ticks: { color: '#222', font: { size: 13 } }
        },
        y: {
          beginAtZero: true,
          stacked: true,
          grid: { color: '#e5e7eb' },
          ticks: { color: '#222', font: { size: 13 } }
        }
      },
      animation: {
        duration: 1200,
        easing: 'easeOutQuart'
      }
    }
  });

  // Line chart (success rate per day).
  var ctxLine = document.getElementById('x4email-line').getContext('2d');
  new Chart(ctxLine, {
    type: 'line',
    data: {
      labels: ['2024-06-01', '2024-06-02', '2024-06-03', '2024-06-04', '2024-06-05', '2024-06-06', '2024-06-07'], // FAKE DATES
      datasets: [
        {
          label: 'Success Rate (%)',
          data: [93, 89, 44, 65, 97, 96, 93], // FAKE DATA
          borderColor: '#22c55e',
          backgroundColor: 'rgba(34,197,94,0.13)',
          fill: true,
          tension: 0.45,
          pointRadius: 6,
          pointBackgroundColor: '#22c55e',
          pointBorderWidth: 2,
          pointBorderColor: '#fff',
          borderWidth: 3,
        }
      ]
    },
    options: {
      plugins: {
        legend: {
          display: true,
          position: 'bottom',
          labels: {
            color: '#222',
            font: { size: 14, weight: 'bold' },
            boxWidth: 16,
            padding: 14
          }
        },
        tooltip: {
          backgroundColor: '#fff',
          titleColor: '#1976d2',
          bodyColor: '#222',
          borderColor: '#1976d2',
          borderWidth: 1,
          padding: 12,
          bodyFont: { size: 15 }
        }
      },
      responsive: false,
      maintainAspectRatio: false,
      scales: {
        x: {
          grid: { display: false },
          ticks: { color: '#222', font: { size: 13 } }
        },
        y: {
          beginAtZero: true,
          max: 100,
          grid: { color: '#e5e7eb' },
          ticks: { color: '#222', font: { size: 13 } }
        }
      },
      animation: {
        duration: 1200,
        easing: 'easeOutQuart'
      }
    }
  });
});
";

wp_add_inline_script( 'chart-js', $chart_script );
?>
