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

requireLogin();

$pdo = getDB();

// Get statistics
$total_posts = $pdo->query("SELECT COUNT(*) FROM posts")->fetchColumn();
$published_posts = $pdo->query("SELECT COUNT(*) FROM posts WHERE status = 'published'")->fetchColumn();
$draft_posts = $pdo->query("SELECT COUNT(*) FROM posts WHERE status = 'draft'")->fetchColumn();
$total_categories = $pdo->query("SELECT COUNT(*) FROM categories")->fetchColumn();

// Get recent posts
$recent_posts = $pdo->query("SELECT p.*, c.name as category_name FROM posts p
                            LEFT JOIN categories c ON p.category_id = c.id
                            ORDER BY p.created_at DESC LIMIT 5")->fetchAll();

// Get pending questions for review
$pending_questions = $pdo->query("SELECT q.*, u.username as instructor_name, qc.name as category_name
                                 FROM questions q
                                 LEFT JOIN users u ON q.instructor_id = u.id
                                 LEFT JOIN question_categories qc ON q.category_id = qc.id
                                 WHERE q.status = 'pending_review'
                                 ORDER BY q.created_at DESC LIMIT 10")->fetchAll();

$page_title = 'Dashboard';
include 'includes/admin_header.php';
?>

<div class="dashboard-stats">
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-file-alt"></i>
        </div>
        <div class="stat-info">
            <h3><?php echo $total_posts; ?></h3>
            <p>Total Posts</p>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-eye"></i>
        </div>
        <div class="stat-info">
            <h3><?php echo $published_posts; ?></h3>
            <p>Published</p>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-edit"></i>
        </div>
        <div class="stat-info">
            <h3><?php echo $draft_posts; ?></h3>
            <p>Drafts</p>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-folder"></i>
        </div>
        <div class="stat-info">
            <h3><?php echo $total_categories; ?></h3>
            <p>Categories</p>
        </div>
    </div>
</div>

<div class="dashboard-content">
    <div class="dashboard-section">
        <h2>Recent Posts</h2>
        <div class="posts-list">
            <?php foreach ($recent_posts as $post): ?>
                <div class="post-item">
                    <div class="post-info">
                        <h4><?php echo htmlspecialchars($post['title']); ?></h4>
                        <p class="post-meta">
                            <span class="category"><?php echo htmlspecialchars($post['category_name'] ?? 'Uncategorized'); ?></span>
                            <span class="status status-<?php echo $post['status']; ?>"><?php echo ucfirst($post['status']); ?></span>
                            <span class="date"><?php echo formatDate($post['created_at']); ?></span>
                        </p>
                    </div>
                    <div class="post-actions">
                        <a href="edit_post.php?id=<?php echo $post['id']; ?>" class="btn btn-sm">Edit</a>
                        <a href="../post.php?slug=<?php echo urlencode($post['slug']); ?>" class="btn btn-sm btn-secondary" target="_blank">View</a>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        <a href="posts.php" class="btn btn-primary">View All Posts</a>
    </div>

    <div class="dashboard-section">
        <h2>Pending Question Reviews</h2>
        <?php if (empty($pending_questions)): ?>
            <p class="no-data">No questions pending review.</p>
        <?php else: ?>
            <div class="questions-list">
                <?php foreach ($pending_questions as $question): ?>
                    <div class="question-item">
                        <div class="question-info">
                            <h4><?php echo htmlspecialchars(substr($question['title'], 0, 80)); ?><?php echo strlen($question['title']) > 80 ? '...' : ''; ?></h4>
                            <p class="question-meta">
                                <span class="instructor">By: <?php echo htmlspecialchars($question['instructor_name'] ?? 'Unknown'); ?></span>
                                <span class="category"><?php echo htmlspecialchars($question['category_name'] ?? 'Uncategorized'); ?></span>
                                <span class="type"><?php echo ucfirst(str_replace('_', ' ', $question['question_type'])); ?></span>
                                <span class="date"><?php echo formatDate($question['created_at']); ?></span>
                            </p>
                            <div class="question-content">
                                <?php echo htmlspecialchars(substr(strip_tags($question['content']), 0, 150)); ?><?php echo strlen(strip_tags($question['content'])) > 150 ? '...' : ''; ?>
                            </div>
                        </div>
                        <div class="question-actions">
                            <button class="btn btn-sm btn-success" onclick="approveQuestion(<?php echo $question['id']; ?>)">
                                <i class="fas fa-check"></i> Approve
                            </button>
                            <button class="btn btn-sm btn-danger" onclick="rejectQuestion(<?php echo $question['id']; ?>)">
                                <i class="fas fa-times"></i> Reject
                            </button>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
            <a href="../instructor/questions/index.php?status=pending_review" class="btn btn-primary">View All Pending Questions</a>
        <?php endif; ?>
    </div>

    <div class="dashboard-section">
        <h2>Quick Actions</h2>
        <div class="quick-actions">
            <a href="add_post.php" class="action-card">
                <i class="fas fa-plus"></i>
                <span>New Post</span>
            </a>
            <a href="posts.php" class="action-card">
                <i class="fas fa-list"></i>
                <span>Manage Posts</span>
            </a>
            <a href="categories.php" class="action-card">
                <i class="fas fa-folder"></i>
                <span>Categories</span>
            </a>
            <a href="../home.php" class="action-card">
                <i class="fas fa-eye"></i>
                <span>View Site</span>
            </a>
        </div>
    </div>
</div>

<script>
function approveQuestion(questionId) {
    if (confirm('Are you sure you want to approve this question? It will be available for use in exams.')) {
        updateQuestionStatus(questionId, 'approved');
    }
}

function rejectQuestion(questionId) {
    const reason = prompt('Please provide a reason for rejection:');
    if (reason !== null && reason.trim() !== '') {
        updateQuestionStatus(questionId, 'rejected', reason);
    }
}

function updateQuestionStatus(questionId, status, reason = '') {
    const formData = new FormData();
    formData.append('question_id', questionId);
    formData.append('status', status);
    if (reason) {
        formData.append('reason', reason);
    }

    fetch('../instructor/questions/update_status.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Question status updated successfully');
            location.reload();
        } else {
            alert('Error updating question status: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error updating question status');
    });
}
</script>

<style>
/* Question review styles */
.questions-list {
    margin-bottom: 1rem;
}

.question-item {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 1rem;
    border: 1px solid #e5e7eb;
    border-radius: 0.5rem;
    margin-bottom: 1rem;
    background: white;
}

.question-info {
    flex: 1;
    margin-right: 1rem;
}

.question-info h4 {
    margin: 0 0 0.5rem 0;
    font-size: 1.1rem;
    color: #1f2937;
}

.question-meta {
    display: flex;
    gap: 1rem;
    font-size: 0.875rem;
    color: #6b7280;
    margin-bottom: 0.5rem;
    flex-wrap: wrap;
}

.question-meta span {
    display: flex;
    align-items: center;
    gap: 0.25rem;
}

.question-content {
    font-size: 0.9rem;
    color: #4b5563;
    line-height: 1.4;
}

.question-actions {
    display: flex;
    gap: 0.5rem;
    flex-shrink: 0;
}

.no-data {
    text-align: center;
    color: #6b7280;
    font-style: italic;
    padding: 2rem;
}
</style>

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