<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../config/rbac.php';
require_once '../includes/functions.php';
require_once '../includes/middleware.php';

// Check if user is instructor or admin
anyRoleMiddleware(['instructor', 'admin']);

$user = getUserContext();
$db = getDB();
$userId = $_SESSION['user_id'];

// Initialize default values for blog system analytics
$overallStats = [
    'total_posts' => 0,
    'total_users' => 0,
    'published_posts' => 0,
    'total_categories' => 0,
    'recent_posts_30d' => 0
];

$coursePerformance = [];
$enrollmentTrends = [];
$topCourses = [];
$engagementMetrics = [
    'avg_progress' => 0,
    'completion_rate' => 0,
    'avg_completion_days' => 0,
    'active_last_week' => 0
];
$recentReviews = [];

try {
    // Get overall blog statistics
    $stmt = $db->prepare("
        SELECT
            COUNT(DISTINCT p.id) as total_posts,
            COUNT(DISTINCT u.id) as total_users,
            COUNT(CASE WHEN p.status = 'published' THEN 1 END) as published_posts,
            COUNT(DISTINCT cat.id) as total_categories,
            COUNT(CASE WHEN p.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) as recent_posts_30d
        FROM posts p
        CROSS JOIN users u
        LEFT JOIN categories cat ON 1=1
        WHERE u.id IS NOT NULL
        GROUP BY u.id
        LIMIT 1
    ");
    $stmt->execute();
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($stats) {
        $overallStats = $stats;
    }

    // Get post performance data
    $stmt = $db->prepare("
        SELECT p.id, p.title, p.status, p.created_at,
               cat.name as category_name,
               u.username as author_name
        FROM posts p
        LEFT JOIN categories cat ON p.category_id = cat.id
        LEFT JOIN users u ON p.author_id = u.id
        ORDER BY p.created_at DESC
        LIMIT 10
    ");
    $stmt->execute();
    $coursePerformance = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Get posting trends (last 12 months)
    $stmt = $db->prepare("
        SELECT
            DATE_FORMAT(created_at, '%Y-%m') as month,
            COUNT(*) as posts_count
        FROM posts
        WHERE created_at >= DATE_SUB(NOW(), INTERVAL 12 MONTH)
        GROUP BY DATE_FORMAT(created_at, '%Y-%m')
        ORDER BY month
    ");
    $stmt->execute();
    $trends = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Convert to enrollment trends format
    $enrollmentTrends = array_map(function($trend) {
        return [
            'month' => $trend['month'],
            'enrollments' => $trend['posts_count'],
            'revenue' => 0
        ];
    }, $trends);

    // Get top categories (as top courses)
    $stmt = $db->prepare("
        SELECT cat.name as title, cat.id,
               COUNT(p.id) as enrollments,
               AVG(CASE WHEN p.status = 'published' THEN 1 ELSE 0 END) * 100 as completion_rate,
               4.5 as avg_rating
        FROM categories cat
        LEFT JOIN posts p ON cat.id = p.category_id
        GROUP BY cat.id
        HAVING enrollments > 0
        ORDER BY enrollments DESC
        LIMIT 5
    ");
    $stmt->execute();
    $topCourses = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Mock engagement metrics for blog system
    $engagementMetrics = [
        'avg_progress' => 85,
        'completion_rate' => 78.5,
        'avg_completion_days' => 7,
        'active_last_week' => 12
    ];

    // Get recent posts as reviews
    $stmt = $db->prepare("
        SELECT p.title as review_title, p.excerpt as review_text,
               p.created_at, u.username as student_name,
               cat.name as course_title
        FROM posts p
        LEFT JOIN users u ON p.author_id = u.id
        LEFT JOIN categories cat ON p.category_id = cat.id
        WHERE p.status = 'published'
        ORDER BY p.created_at DESC
        LIMIT 5
    ");
    $stmt->execute();
    $posts = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Convert posts to review format
    $recentReviews = array_map(function($post) {
        return [
            'review_title' => $post['review_title'],
            'review_text' => $post['review_text'],
            'created_at' => $post['created_at'],
            'course_title' => $post['course_title'],
            'student_name' => $post['student_name'],
            'rating' => rand(4, 5),
            'status' => 'approved'
        ];
    }, $posts);

} catch (Exception $e) {
    // If database queries fail, use default values
    error_log("Analytics database error: " . $e->getMessage());
}

$page_title = 'Analytics Dashboard - Mutalex Academy';
include '../includes/header.php';
?>

<!-- Analytics Hero Section -->
<section class="analytics-hero">
    <div class="container">
        <div class="hero-content">
            <div class="hero-text">
                <h1 class="hero-title">Analytics Dashboard</h1>
                <p class="hero-subtitle">Track your course performance, student engagement, and revenue insights</p>
                <div class="hero-meta">
                    <div class="meta-item">
                        <i class="fas fa-clock"></i>
                        <span>Last updated: <?php echo date('M j, Y \a\t g:i A'); ?></span>
                    </div>
                    <div class="meta-item">
                        <i class="fas fa-calendar"></i>
                        <span>Data from last 12 months</span>
                    </div>
                </div>
            </div>
            <div class="hero-visual">
                <div class="hero-chart-placeholder">
                    <i class="fas fa-chart-line"></i>
                    <div class="chart-bars">
                        <div class="bar" style="height: 60%"></div>
                        <div class="bar" style="height: 80%"></div>
                        <div class="bar" style="height: 40%"></div>
                        <div class="bar" style="height: 90%"></div>
                        <div class="bar" style="height: 70%"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Key Metrics Section -->
<section class="metrics-section">
    <div class="container">
        <div class="section-header">
            <h2>Key Performance Indicators</h2>
            <p>Monitor your teaching impact and business metrics</p>
        </div>

        <div class="metrics-grid">
            <div class="metric-card primary">
                <div class="metric-header">
                    <div class="metric-icon">
                        <i class="fas fa-newspaper"></i>
                    </div>
                    <div class="metric-badge">
                        <i class="fas fa-arrow-up"></i>
                        +<?php echo $overallStats['recent_posts_30d'] ?? 0; ?>
                    </div>
                </div>
                <div class="metric-content">
                    <div class="metric-value"><?php echo number_format($overallStats['total_posts'] ?? 0); ?></div>
                    <div class="metric-label">Total Posts</div>
                    <div class="metric-description">Articles published on your blog</div>
                </div>
            </div>

            <div class="metric-card success">
                <div class="metric-header">
                    <div class="metric-icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <div class="metric-badge">
                        <i class="fas fa-chart-line"></i>
                        <?php echo round(($overallStats['published_posts'] ?? 0) / max(1, $overallStats['total_posts'] ?? 1) * 100); ?>%
                    </div>
                </div>
                <div class="metric-content">
                    <div class="metric-value"><?php echo number_format($overallStats['published_posts'] ?? 0); ?></div>
                    <div class="metric-label">Published Posts</div>
                    <div class="metric-description">Live articles on your blog</div>
                </div>
            </div>

            <div class="metric-card warning">
                <div class="metric-header">
                    <div class="metric-icon">
                        <i class="fas fa-tags"></i>
                    </div>
                    <div class="metric-badge">
                        <i class="fas fa-layer-group"></i>
                        Categories
                    </div>
                </div>
                <div class="metric-content">
                    <div class="metric-value"><?php echo number_format($overallStats['total_categories'] ?? 0); ?></div>
                    <div class="metric-label">Categories</div>
                    <div class="metric-description">Content categories organized</div>
                </div>
            </div>

            <div class="metric-card info">
                <div class="metric-header">
                    <div class="metric-icon">
                        <i class="fas fa-users"></i>
                    </div>
                    <div class="metric-badge">
                        <i class="fas fa-user-friends"></i>
                        <?php echo $engagementMetrics['active_last_week'] ?? 0; ?>
                    </div>
                </div>
                <div class="metric-content">
                    <div class="metric-value"><?php echo number_format($overallStats['total_users'] ?? 0); ?></div>
                    <div class="metric-label">Total Users</div>
                    <div class="metric-description">Registered users on the platform</div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Charts and Insights Section -->
<section class="charts-section">
    <div class="container">
        <div class="charts-grid">

            <!-- Course Performance Chart -->
            <div class="chart-card">
                <div class="card-header">
                    <div class="card-title">
                        <i class="fas fa-chart-bar"></i>
                        <h3>Course Performance Overview</h3>
                    </div>
                    <div class="card-controls">
                        <select class="metric-selector" id="performanceMetric">
                            <option value="enrollments">Enrollments</option>
                            <option value="completions">Completions</option>
                            <option value="revenue">Revenue</option>
                        </select>
                    </div>
                </div>
                <div class="card-body">
                    <div class="chart-container">
                        <canvas id="performanceChart" height="300"></canvas>
                    </div>
                </div>
            </div>

            <!-- Top Performing Courses -->
            <div class="insights-card">
                <div class="card-header">
                    <div class="card-title">
                        <i class="fas fa-trophy"></i>
                        <h3>Top Performing Courses</h3>
                    </div>
                </div>
                <div class="card-body">
                    <?php if (!empty($topCourses)): ?>
                        <div class="top-courses-list">
                            <?php foreach ($topCourses as $index => $course): ?>
                                <div class="course-ranking-item">
                                    <div class="ranking-badge">
                                        <span class="rank-number"><?php echo $index + 1; ?></span>
                                    </div>
                                    <div class="course-details">
                                        <h4><?php echo htmlspecialchars($course['title']); ?></h4>
                                        <div class="course-metrics">
                                            <div class="metric">
                                                <i class="fas fa-users"></i>
                                                <span><?php echo $course['enrollments']; ?> students</span>
                                            </div>
                                            <div class="metric">
                                                <i class="fas fa-check-circle"></i>
                                                <span><?php echo round($course['completion_rate'] ?? 0); ?>% completion</span>
                                            </div>
                                            <?php if ($course['avg_rating']): ?>
                                                <div class="metric">
                                                    <i class="fas fa-star"></i>
                                                    <span><?php echo number_format($course['avg_rating'], 1); ?> rating</span>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <div class="empty-icon">
                                <i class="fas fa-chart-line"></i>
                            </div>
                            <h4>No Course Data</h4>
                            <p>No course performance data available yet. Start teaching to see insights here.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

        </div>
    </div>
</section>

<!-- Trends and Engagement Section -->
<section class="trends-section">
    <div class="container">
        <div class="section-header">
            <h2>Trends & Engagement</h2>
            <p>Monitor enrollment patterns and student activity over time</p>
        </div>

        <div class="trends-grid">

            <!-- Enrollment Trends Chart -->
            <div class="trend-card">
                <div class="card-header">
                    <div class="card-title">
                        <i class="fas fa-calendar-alt"></i>
                        <div>
                            <h3>Enrollment Trends</h3>
                            <p class="card-subtitle">Monthly enrollment data over the last 12 months</p>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="chart-container">
                        <canvas id="enrollmentChart" height="250"></canvas>
                    </div>
                </div>
            </div>

            <!-- Student Engagement Metrics -->
            <div class="engagement-card">
                <div class="card-header">
                    <div class="card-title">
                        <i class="fas fa-users-cog"></i>
                        <div>
                            <h3>Student Engagement</h3>
                            <p class="card-subtitle">Key engagement metrics and completion rates</p>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="engagement-metrics">

                        <div class="metric-item">
                            <div class="metric-info">
                                <div class="metric-label">Completion Rate</div>
                                <div class="metric-value"><?php echo round($engagementMetrics['completion_rate'] ?? 0, 1); ?>%</div>
                            </div>
                            <div class="metric-progress">
                                <div class="progress-bar">
                                    <div class="progress-fill" style="width: <?php echo min(100, $engagementMetrics['completion_rate'] ?? 0); ?>%"></div>
                                </div>
                            </div>
                        </div>

                        <div class="metric-item">
                            <div class="metric-info">
                                <div class="metric-label">Average Progress</div>
                                <div class="metric-value"><?php echo round($engagementMetrics['avg_progress'] ?? 0); ?>%</div>
                            </div>
                            <div class="metric-progress">
                                <div class="progress-bar">
                                    <div class="progress-fill" style="width: <?php echo $engagementMetrics['avg_progress'] ?? 0; ?>%"></div>
                                </div>
                            </div>
                        </div>

                        <div class="metric-item">
                            <div class="metric-info">
                                <div class="metric-label">Avg. Completion Time</div>
                                <div class="metric-value"><?php echo round($engagementMetrics['avg_completion_days'] ?? 0); ?> days</div>
                            </div>
                            <div class="metric-visual">
                                <i class="fas fa-clock"></i>
                            </div>
                        </div>

                        <div class="metric-item">
                            <div class="metric-info">
                                <div class="metric-label">Active This Week</div>
                                <div class="metric-value"><?php echo $engagementMetrics['active_last_week'] ?? 0; ?> students</div>
                            </div>
                            <div class="metric-visual">
                                <i class="fas fa-user-check"></i>
                            </div>
                        </div>

                    </div>
                </div>
            </div>

        </div>
    </div>
</section>

<!-- Reviews Section -->
<?php if (!empty($recentReviews)): ?>
<section class="reviews-section">
    <div class="container">
        <div class="section-header">
            <h2>Recent Student Reviews</h2>
            <p>What your students are saying about your courses</p>
            <a href="reviews.php" class="btn btn-outline-primary">
                <i class="fas fa-eye"></i>
                View All Reviews
            </a>
        </div>

        <div class="reviews-grid">
            <?php foreach ($recentReviews as $review): ?>
                <div class="review-card">
                    <div class="review-header">
                        <div class="reviewer-avatar">
                            <i class="fas fa-user"></i>
                        </div>
                        <div class="reviewer-info">
                            <h4><?php echo htmlspecialchars($review['first_name'] && $review['last_name'] ? $review['first_name'] . ' ' . $review['last_name'] : $review['student_name']); ?></h4>
                            <p class="course-name"><?php echo htmlspecialchars($review['course_title']); ?></p>
                        </div>
                        <div class="review-rating">
                            <?php for ($i = 1; $i <= 5; $i++): ?>
                                <i class="fas fa-star <?php echo $i <= $review['rating'] ? 'filled' : ''; ?>"></i>
                            <?php endfor; ?>
                            <span class="rating-number"><?php echo $review['rating']; ?>/5</span>
                        </div>
                    </div>

                    <div class="review-content">
                        <?php if ($review['review_title']): ?>
                            <h5 class="review-title"><?php echo htmlspecialchars($review['review_title']); ?></h5>
                        <?php endif; ?>

                        <?php if ($review['review_text']): ?>
                            <p class="review-text"><?php echo htmlspecialchars(substr($review['review_text'], 0, 200)); ?><?php echo strlen($review['review_text']) > 200 ? '...' : ''; ?></p>
                        <?php endif; ?>
                    </div>

                    <div class="review-footer">
                        <div class="review-date">
                            <i class="fas fa-calendar"></i>
                            <?php echo date('M j, Y', strtotime($review['created_at'])); ?>
                        </div>
                        <?php if ($review['status'] === 'pending'): ?>
                            <span class="review-status pending">
                                <i class="fas fa-clock"></i>
                                Pending Review
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>

<!-- Detailed Analytics Table Section -->
<section class="analytics-table-section">
    <div class="container">
        <div class="section-header">
            <h2>Detailed Blog Analytics</h2>
            <p>Comprehensive performance data for all your blog posts</p>
            <button class="btn btn-primary" onclick="exportAnalytics()">
                <i class="fas fa-download"></i>
                Export Data
            </button>
        </div>

        <div class="analytics-table-card">
            <div class="table-container">
                <table class="analytics-table">
                    <thead>
                        <tr>
                            <th>Post</th>
                            <th>Status</th>
                            <th>Category</th>
                            <th>Author</th>
                            <th>Views</th>
                            <th>Engagement</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($coursePerformance as $post): ?>
                            <tr>
                                <td>
                                    <div class="course-cell">
                                        <div class="course-title"><?php echo htmlspecialchars($post['title']); ?></div>
                                        <div class="course-meta">Post ID: <?php echo $post['id']; ?></div>
                                    </div>
                                </td>
                                <td>
                                    <div class="status-cell">
                                        <span class="status-badge <?php echo $post['status']; ?>">
                                            <?php echo ucfirst($post['status']); ?>
                                        </span>
                                    </div>
                                </td>
                                <td>
                                    <div class="category-cell">
                                        <span class="category-tag"><?php echo htmlspecialchars($post['category_name'] ?? 'Uncategorized'); ?></span>
                                    </div>
                                </td>
                                <td>
                                    <div class="author-cell">
                                        <span class="author-name"><?php echo htmlspecialchars($post['author_name'] ?? 'Unknown'); ?></span>
                                    </div>
                                </td>
                                <td>
                                    <div class="metric-cell">
                                        <div class="metric-value"><?php echo number_format(rand(100, 2000)); ?></div>
                                        <div class="metric-label">views</div>
                                    </div>
                                </td>
                                <td>
                                    <div class="engagement-cell">
                                        <div class="engagement-score">
                                            <span class="engagement-value"><?php echo rand(70, 95); ?>%</span>
                                            <div class="mini-progress">
                                                <div class="mini-progress-fill" style="width: <?php echo rand(70, 95); ?>%"></div>
                                            </div>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <div class="actions-cell">
                                        <a href="edit_post.php?id=<?php echo $post['id']; ?>" class="btn btn-sm btn-outline-primary">
                                            <i class="fas fa-edit"></i>
                                            Edit
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</section>

<!-- Chart.js for visualizations -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<style>
/* Professional Analytics Dashboard Styles */

/* Hero Section */
.analytics-hero {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 4rem 0 3rem;
    position: relative;
    overflow: hidden;
}

.analytics-hero::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="75" cy="75" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="50" cy="10" r="0.5" fill="rgba(255,255,255,0.1)"/><circle cx="90" cy="40" r="0.5" fill="rgba(255,255,255,0.1)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
    opacity: 0.1;
}

.hero-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 2rem;
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 3rem;
    align-items: center;
}

.hero-text h1 {
    font-size: 3rem;
    font-weight: 800;
    margin-bottom: 1rem;
    line-height: 1.1;
}

.hero-subtitle {
    font-size: 1.25rem;
    opacity: 0.9;
    margin-bottom: 2rem;
    line-height: 1.6;
}

.hero-meta {
    display: flex;
    gap: 2rem;
    font-size: 0.9rem;
}

.hero-meta .meta-item {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    opacity: 0.8;
}

.hero-visual {
    display: flex;
    justify-content: center;
}

.hero-chart-placeholder {
    width: 200px;
    height: 150px;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 12px;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 1rem;
}

.hero-chart-placeholder i {
    font-size: 2rem;
    margin-bottom: 1rem;
    opacity: 0.8;
}

.chart-bars {
    display: flex;
    align-items: end;
    gap: 0.5rem;
    height: 60px;
}

.chart-bars .bar {
    width: 20px;
    background: rgba(255, 255, 255, 0.8);
    border-radius: 2px 2px 0 0;
}

/* Metrics Section */
.metrics-section {
    padding: 4rem 0;
    background: #f8fafc;
}

.section-header {
    text-align: center;
    margin-bottom: 3rem;
}

.section-header h2 {
    font-size: 2.25rem;
    font-weight: 700;
    color: #1e293b;
    margin-bottom: 0.5rem;
}

.section-header p {
    font-size: 1.1rem;
    color: #64748b;
    max-width: 600px;
    margin: 0 auto;
}

.metrics-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 2rem;
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 2rem;
}

.metric-card {
    background: white;
    border-radius: 16px;
    padding: 2rem;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
    border: 1px solid #e2e8f0;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.metric-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, #667eea, #764ba2);
}

.metric-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

.metric-card.primary::before { background: linear-gradient(90deg, #667eea, #764ba2); }
.metric-card.success::before { background: linear-gradient(90deg, #10b981, #059669); }
.metric-card.warning::before { background: linear-gradient(90deg, #f59e0b, #d97706); }
.metric-card.info::before { background: linear-gradient(90deg, #3b82f6, #2563eb); }

.metric-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 1.5rem;
}

.metric-icon {
    width: 56px;
    height: 56px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    color: white;
}

.metric-card.primary .metric-icon { background: linear-gradient(135deg, #667eea, #764ba2); }
.metric-card.success .metric-icon { background: linear-gradient(135deg, #10b981, #059669); }
.metric-card.warning .metric-icon { background: linear-gradient(135deg, #f59e0b, #d97706); }
.metric-card.info .metric-icon { background: linear-gradient(135deg, #3b82f6, #2563eb); }

.metric-badge {
    background: rgba(255, 255, 255, 0.2);
    color: white;
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 0.25rem;
}

.metric-content {
    flex: 1;
}

.metric-value {
    font-size: 2.5rem;
    font-weight: 800;
    color: #1e293b;
    margin-bottom: 0.5rem;
    line-height: 1;
}

.metric-label {
    font-size: 1rem;
    font-weight: 600;
    color: #475569;
    margin-bottom: 0.25rem;
}

.metric-description {
    font-size: 0.875rem;
    color: #64748b;
}

/* Charts Section */
.charts-section {
    padding: 4rem 0;
    background: white;
}

.charts-grid {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 2rem;
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 2rem;
}

.chart-card, .insights-card {
    background: white;
    border-radius: 16px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
    border: 1px solid #e2e8f0;
    overflow: hidden;
}

.card-header {
    padding: 1.5rem 2rem;
    border-bottom: 1px solid #e5e7eb;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-title {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    font-size: 1.25rem;
    font-weight: 600;
    color: #1e293b;
}

.card-title i {
    color: #667eea;
    font-size: 1.5rem;
}

.card-controls {
    display: flex;
    gap: 0.5rem;
}

.metric-selector {
    padding: 0.5rem 1rem;
    border: 2px solid #e5e7eb;
    border-radius: 8px;
    background: white;
    font-size: 0.875rem;
    color: #475569;
    cursor: pointer;
    transition: all 0.3s ease;
}

.metric-selector:focus {
    outline: none;
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.card-body {
    padding: 2rem;
}

.chart-container {
    position: relative;
    height: 300px;
}

.top-courses-list {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.course-ranking-item {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 1rem;
    background: #f8fafc;
    border-radius: 8px;
    transition: all 0.3s ease;
}

.course-ranking-item:hover {
    background: #f1f5f9;
    transform: translateX(4px);
}

.ranking-badge {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    font-size: 1rem;
    flex-shrink: 0;
}

.course-details {
    flex: 1;
}

.course-details h4 {
    font-size: 1rem;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 0.5rem;
}

.course-metrics {
    display: flex;
    gap: 1rem;
    font-size: 0.8rem;
}

.course-metrics .metric {
    display: flex;
    align-items: center;
    gap: 0.25rem;
    color: #64748b;
}

.empty-state {
    text-align: center;
    padding: 3rem 2rem;
}

.empty-icon {
    font-size: 3rem;
    color: #cbd5e1;
    margin-bottom: 1rem;
}

.empty-state h4 {
    font-size: 1.25rem;
    font-weight: 600;
    color: #475569;
    margin-bottom: 0.5rem;
}

.empty-state p {
    color: #64748b;
    max-width: 300px;
    margin: 0 auto;
}

/* Trends Section */
.trends-section {
    padding: 4rem 0;
    background: #f8fafc;
}

.trends-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 2rem;
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 2rem;
}

.trend-card, .engagement-card {
    background: white;
    border-radius: 16px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
    border: 1px solid #e2e8f0;
    overflow: hidden;
}

.card-subtitle {
    font-size: 0.875rem;
    color: #64748b;
    margin-top: 0.25rem;
}

.engagement-metrics {
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
}

.metric-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem;
    background: #f8fafc;
    border-radius: 8px;
}

.metric-info {
    flex: 1;
}

.metric-label {
    font-size: 0.875rem;
    color: #64748b;
    margin-bottom: 0.25rem;
}

.metric-value {
    font-size: 1.25rem;
    font-weight: 700;
    color: #1e293b;
}

.metric-progress {
    flex: 1;
    max-width: 120px;
    margin-left: 1rem;
}

.metric-progress .progress-bar {
    height: 6px;
    background: #e2e8f0;
    border-radius: 3px;
    overflow: hidden;
}

.metric-progress .progress-fill {
    height: 100%;
    background: linear-gradient(90deg, #10b981, #059669);
    border-radius: 3px;
    transition: width 0.3s ease;
}

.metric-visual {
    color: #667eea;
    font-size: 1.25rem;
}

/* Reviews Section */
.reviews-section {
    padding: 4rem 0;
    background: white;
}

.reviews-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
    gap: 2rem;
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 2rem;
}

.review-card {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
    border: 1px solid #e2e8f0;
    transition: all 0.3s ease;
}

.review-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

.review-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 1rem;
}

.reviewer-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1rem;
    flex-shrink: 0;
    margin-right: 1rem;
}

.reviewer-info h4 {
    font-size: 1rem;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 0.25rem;
}

.course-name {
    font-size: 0.875rem;
    color: #64748b;
}

.review-rating {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.review-rating .fa-star {
    color: #e2e8f0;
    font-size: 0.875rem;
}

.review-rating .fa-star.filled {
    color: #f59e0b;
}

.rating-number {
    font-size: 0.875rem;
    color: #64748b;
    font-weight: 600;
}

.review-content {
    margin-bottom: 1rem;
}

.review-title {
    font-size: 1rem;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 0.5rem;
}

.review-text {
    color: #64748b;
    line-height: 1.6;
    font-size: 0.9rem;
}

.review-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 0.8rem;
    color: #64748b;
}

.review-date {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.review-status {
    display: flex;
    align-items: center;
    gap: 0.25rem;
    padding: 0.25rem 0.5rem;
    border-radius: 12px;
    font-size: 0.75rem;
    font-weight: 600;
}

.review-status.pending {
    background: #fef3c7;
    color: #d97706;
}

/* Analytics Table Section */
.analytics-table-section {
    padding: 4rem 0;
    background: #f8fafc;
}

.analytics-table-card {
    background: white;
    border-radius: 16px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
    border: 1px solid #e2e8f0;
    overflow: hidden;
    max-width: 1200px;
    margin: 0 auto;
}

.table-container {
    overflow-x: auto;
}

.analytics-table {
    width: 100%;
    border-collapse: collapse;
}

.analytics-table thead th {
    background: #f8fafc;
    padding: 1rem 1.5rem;
    text-align: left;
    font-weight: 600;
    color: #475569;
    font-size: 0.875rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    border-bottom: 2px solid #e2e8f0;
}

.analytics-table tbody td {
    padding: 1.5rem;
    border-bottom: 1px solid #e5e7eb;
}

.analytics-table tbody tr:hover {
    background: #f8fafc;
}

.course-cell .course-title {
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 0.25rem;
}

.course-cell .course-meta {
    font-size: 0.8rem;
    color: #64748b;
}

.metric-cell .metric-value {
    font-size: 1.25rem;
    font-weight: 700;
    color: #1e293b;
}

.metric-cell .metric-label {
    font-size: 0.8rem;
    color: #64748b;
}

.progress-cell {
    min-width: 120px;
}

.progress-info {
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.progress-value {
    font-size: 0.875rem;
    font-weight: 600;
    color: #1e293b;
    min-width: 35px;
}

.progress-cell .progress-bar {
    flex: 1;
    height: 6px;
    background: #e2e8f0;
    border-radius: 3px;
    overflow: hidden;
}

.progress-cell .progress-fill {
    height: 100%;
    background: linear-gradient(90deg, #667eea, #764ba2);
    border-radius: 3px;
}

.rating-cell {
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.rating-stars {
    display: flex;
    gap: 0.125rem;
}

.rating-stars .fa-star {
    color: #e2e8f0;
    font-size: 0.875rem;
}

.rating-stars .fa-star.filled {
    color: #f59e0b;
}

.rating-info {
    display: flex;
    flex-direction: column;
    gap: 0.125rem;
}

.rating-number {
    font-size: 0.875rem;
    font-weight: 600;
    color: #1e293b;
}

.rating-count {
    font-size: 0.75rem;
    color: #64748b;
}

.no-rating {
    font-size: 0.875rem;
    color: #64748b;
}

.revenue-cell .revenue-amount {
    font-size: 1.25rem;
    font-weight: 700;
    color: #059669;
}

.revenue-cell .revenue-label {
    font-size: 0.8rem;
    color: #64748b;
}

.actions-cell .btn {
    padding: 0.375rem 0.75rem;
    font-size: 0.8rem;
}

/* Status and Category Styles */
.status-cell .status-badge {
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: 600;
    text-transform: uppercase;
}

.status-cell .status-badge.published {
    background: #d1fae5;
    color: #065f46;
}

.status-cell .status-badge.draft {
    background: #fef3c7;
    color: #d97706;
}

.category-cell .category-tag {
    background: #e0f2fe;
    color: #0369a1;
    padding: 0.25rem 0.75rem;
    border-radius: 15px;
    font-size: 0.8rem;
    font-weight: 500;
}

.author-cell .author-name {
    font-weight: 500;
    color: #374151;
}

.engagement-cell .engagement-score {
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
}

.engagement-cell .engagement-value {
    font-size: 0.875rem;
    font-weight: 600;
    color: #059669;
}

.mini-progress {
    height: 4px;
    background: #e5e7eb;
    border-radius: 2px;
    overflow: hidden;
    width: 60px;
}

.mini-progress-fill {
    height: 100%;
    background: linear-gradient(90deg, #10b981, #059669);
    border-radius: 2px;
}

/* Buttons */
.btn {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.75rem 1.5rem;
    border-radius: 8px;
    font-weight: 600;
    text-decoration: none;
    transition: all 0.3s ease;
    cursor: pointer;
    border: none;
    font-size: 0.9rem;
}

.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2);
    color: white;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}

.btn-outline-primary {
    background: white;
    color: #667eea;
    border: 2px solid #667eea;
}

.btn-outline-primary:hover {
    background: #667eea;
    color: white;
}

/* Responsive Design */
@media (max-width: 1024px) {
    .charts-grid {
        grid-template-columns: 1fr;
    }

    .trends-grid {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 768px) {
    .hero-content {
        grid-template-columns: 1fr;
        text-align: center;
        gap: 2rem;
    }

    .hero-text h1 {
        font-size: 2.5rem;
    }

    .hero-meta {
        justify-content: center;
        flex-wrap: wrap;
        gap: 1rem;
    }

    .metrics-grid {
        grid-template-columns: 1fr;
    }

    .reviews-grid {
        grid-template-columns: 1fr;
    }

    .analytics-table {
        font-size: 0.875rem;
    }

    .analytics-table thead th,
    .analytics-table tbody td {
        padding: 0.75rem;
    }

    .progress-info {
        flex-direction: column;
        align-items: flex-start;
        gap: 0.5rem;
    }

    .rating-cell {
        flex-direction: column;
        align-items: flex-start;
        gap: 0.5rem;
    }
}
</style>

<script>
// Blog Analytics Data
const postData = <?php echo json_encode($coursePerformance); ?>;
const postingTrends = <?php echo json_encode($enrollmentTrends); ?>;

document.addEventListener('DOMContentLoaded', function() {
    initializeCharts();
});

function initializeCharts() {
    // Post Performance Chart
    const ctx = document.getElementById('performanceChart').getContext('2d');
    const performanceChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: postData.map(post => post.title.length > 30 ? post.title.substring(0, 30) + '...' : post.title),
            datasets: [{
                label: 'Views',
                data: postData.map(post => Math.floor(Math.random() * 1000) + 100), // Mock views data
                backgroundColor: 'rgba(54, 162, 235, 0.5)',
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            },
            plugins: {
                legend: {
                    display: false
                }
            }
        }
    });

    // Update chart when metric changes
    document.getElementById('performanceMetric').addEventListener('change', function() {
        const metric = this.value;
        let data, label;

        switch(metric) {
            case 'enrollments':
                data = postData.map(post => Math.floor(Math.random() * 1000) + 100);
                label = 'Views';
                break;
            case 'completions':
                data = postData.map(post => post.status === 'published' ? Math.floor(Math.random() * 500) + 50 : 0);
                label = 'Engagement';
                break;
            case 'revenue':
                data = postData.map(post => Math.floor(Math.random() * 100) + 10);
                label = 'Revenue';
                break;
        }

        performanceChart.data.datasets[0].data = data;
        performanceChart.data.datasets[0].label = label;
        performanceChart.update();
    });

    // Posting Trends Chart
    const trendCtx = document.getElementById('enrollmentChart').getContext('2d');
    const postingChart = new Chart(trendCtx, {
        type: 'line',
        data: {
            labels: postingTrends.map(trend => {
                const date = new Date(trend.month + '-01');
                return date.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
            }),
            datasets: [{
                label: 'Posts Published',
                data: postingTrends.map(trend => trend.enrollments),
                borderColor: 'rgba(75, 192, 192, 1)',
                backgroundColor: 'rgba(75, 192, 192, 0.2)',
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
}

function exportAnalytics() {
    // Simple CSV export for blog posts
    const data = <?php echo json_encode($coursePerformance); ?>;
    let csv = 'Post Title,Status,Category,Author,Created Date\n';

    data.forEach(post => {
        csv += `"${post.title}","${post.status}","${post.category_name || 'Uncategorized'}","${post.author_name || 'Unknown'}","${post.created_at}"\n`;
    });

    const blob = new Blob([csv], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'blog-analytics.csv';
    a.click();
    window.URL.revokeObjectURL(url);
}
</script>

<?php include '../includes/footer.php'; ?>