<?php
/**
 * Admin Comment Management Page
 * Approve, disapprove, and delete lesson comments
 */

require_once 'config.php';
requireAdminAuth();

// Get current admin info
$admin = getCurrentAdmin();

// Pagination settings
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = 20;
$offset = ($page - 1) * $limit;

// Filter settings
$status = $_GET['status'] ?? 'all'; // all, pending, approved
$lesson_id = $_GET['lesson_id'] ?? '';
$search = $_GET['search'] ?? '';

// Build WHERE clause for filtering
$whereConditions = [];
$params = [];

if ($status === 'pending') {
    $whereConditions[] = "c.is_approved = 0";
} elseif ($status === 'approved') {
    $whereConditions[] = "c.is_approved = 1";
}

if (!empty($lesson_id)) {
    $whereConditions[] = "c.lesson_id = ?";
    $params[] = $lesson_id;
}

if (!empty($search)) {
    $whereConditions[] = "(c.comment LIKE ? OR u.user_name LIKE ? OR u.email LIKE ?)";
    $searchTerm = "%$search%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

$whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';

try {
    $pdo = getDBConnection();
    
    // Get total count for pagination
    $countSql = "
        SELECT COUNT(*) as total 
        FROM lesson_comments c 
        JOIN users u ON c.user_id = u.id 
        LEFT JOIN lessons l ON c.lesson_id = l.id 
        $whereClause
    ";
    $countStmt = $pdo->prepare($countSql);
    $countStmt->execute($params);
    $totalComments = $countStmt->fetch()['total'];
    $totalPages = ceil($totalComments / $limit);
    
    // Get comments with pagination
    $sql = "
        SELECT 
            c.id,
            c.lesson_id,
            c.user_id,
            c.comment,
            c.is_approved,
            c.created_at,
            c.updated_at,
            u.user_name,
            u.email,
            l.title as lesson_title,
            l.level as lesson_level
        FROM lesson_comments c 
        JOIN users u ON c.user_id = u.id 
        LEFT JOIN lessons l ON c.lesson_id = l.id 
        $whereClause
        ORDER BY c.created_at DESC 
        LIMIT $limit OFFSET $offset
    ";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $comments = $stmt->fetchAll();
    
    // Get lessons for filter dropdown
    $lessonStmt = $pdo->query("SELECT id, title, level FROM lessons ORDER BY level ASC, title ASC");
    $lessons = $lessonStmt->fetchAll();
    
    // Get comment statistics
    $statsStmt = $pdo->query("
        SELECT 
            COUNT(*) as total,
            SUM(CASE WHEN is_approved = 0 THEN 1 ELSE 0 END) as pending,
            SUM(CASE WHEN is_approved = 1 THEN 1 ELSE 0 END) as approved,
            0 as disapproved
        FROM lesson_comments
    ");
    $stats = $statsStmt->fetch();

} catch (Exception $e) {
    error_log("Error loading comments: " . $e->getMessage());
    $comments = [];
    $totalComments = 0;
    $totalPages = 0;
    $lessons = [];
    $stats = ['total' => 0, 'pending' => 0, 'approved' => 0, 'disapproved' => 0];
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Comment Management - Admin Panel</title>
    <link rel="stylesheet" href="assets/style.css">
    <style>
        .comment-content {
            max-width: 300px;
            word-wrap: break-word;
            line-height: 1.4;
        }
        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8em;
            font-weight: 600;
        }
        .status-pending { background: #fff3cd; color: #664d03; }
        .status-approved { background: #d1edff; color: #0c5460; }
        .status-disapproved { background: #f8d7da; color: #721c24; }
        
        .comment-actions {
            white-space: nowrap;
        }
        .comment-actions button {
            margin: 0 2px;
            padding: 4px 8px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }
        .btn-approve { background: #d4edda; color: #155724; }
        .btn-disapprove { background: #f8d7da; color: #721c24; }
        .btn-delete { background: #e2e3e5; color: #383d41; }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border-left: 4px solid;
        }
        .stat-pending { border-left-color: #ffc107; }
        .stat-approved { border-left-color: #198754; }
        .stat-disapproved { border-left-color: #dc3545; }
        .stat-total { border-left-color: #0d6efd; }
        
        .filters-card {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .comments-table {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .table-header {
            background: #f8f9fa;
            padding: 15px 20px;
            border-bottom: 1px solid #dee2e6;
        }
        
        .pagination {
            padding: 15px 20px;
            background: #f8f9fa;
            border-top: 1px solid #dee2e6;
            text-align: center;
        }
        
        .pagination a {
            padding: 8px 12px;
            margin: 0 2px;
            text-decoration: none;
            color: #007bff;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            background: white;
        }
        
        .pagination a.active {
            background: #007bff;
            color: white;
        }
    </style>
</head>
<body>
    <?php include 'includes/header.php'; ?>
    
    <div class="container">
        <div class="page-header">
            <h1>💬 Comment Management</h1>
            <p>Manage lesson comments, approve, disapprove, and moderate user content</p>
        </div>
        
        <!-- Statistics Cards -->
        <div class="stats-grid">
            <div class="stat-card stat-total">
                <h3><?= number_format($stats['total']) ?></h3>
                <p>Total Comments</p>
            </div>
            <div class="stat-card stat-pending">
                <h3><?= number_format($stats['pending']) ?></h3>
                <p>Pending Review</p>
            </div>
            <div class="stat-card stat-approved">
                <h3><?= number_format($stats['approved']) ?></h3>
                <p>Approved</p>
            </div>
            <div class="stat-card stat-disapproved">
                <h3><?= number_format($stats['disapproved']) ?></h3>
                <p>Disapproved</p>
            </div>
        </div>
        
        <!-- Filters -->
        <div class="filters-card">
            <h3>Filter Comments</h3>
            <form method="GET" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; align-items: end; margin-top: 15px;">
                <div>
                    <label for="status">Status</label>
                    <select id="status" name="status" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 6px;">
                        <option value="all" <?= $status === 'all' ? 'selected' : '' ?>>All Comments</option>
                        <option value="pending" <?= $status === 'pending' ? 'selected' : '' ?>>Pending Review</option>
                        <option value="approved" <?= $status === 'approved' ? 'selected' : '' ?>>Approved</option>
                    </select>
                </div>
                <div>
                    <label for="lesson_id">Lesson</label>
                    <select id="lesson_id" name="lesson_id" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 6px;">
                        <option value="">All Lessons</option>
                        <?php foreach ($lessons as $lesson): ?>
                            <option value="<?= $lesson['id'] ?>" <?= $lesson_id == $lesson['id'] ? 'selected' : '' ?>>
                                Level <?= $lesson['level'] ?> - <?= htmlspecialchars($lesson['title']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label for="search">Search</label>
                    <input type="text" id="search" name="search" 
                           value="<?= htmlspecialchars($search) ?>" 
                           placeholder="Search comments, users..."
                           style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 6px;">
                </div>
                <div>
                    <button type="submit" class="btn btn-primary" style="width: 100%;">
                        🔍 Filter
                    </button>
                </div>
            </form>
        </div>
        
        <!-- Comments Table -->
        <div class="comments-table">
            <div class="table-header">
                <h3>
                    Comments (<?= number_format($totalComments) ?> total)
                    <?php if ($status !== 'all'): ?>
                        - <?= ucfirst($status) ?>
                    <?php endif; ?>
                </h3>
            </div>
            
            <?php if (empty($comments)): ?>
                <div style="text-align: center; padding: 60px 20px;">
                    <div style="font-size: 3rem; color: #ccc; margin-bottom: 15px;">💬</div>
                    <p style="color: #666;">No comments found matching your criteria.</p>
                </div>
            <?php else: ?>
                <div style="overflow-x: auto;">
                    <table style="width: 100%; border-collapse: collapse;">
                        <thead style="background: #f8f9fa; border-bottom: 2px solid #dee2e6;">
                            <tr>
                                <th style="padding: 12px; text-align: left; border-bottom: 1px solid #dee2e6;">ID</th>
                                <th style="padding: 12px; text-align: left; border-bottom: 1px solid #dee2e6;">User</th>
                                <th style="padding: 12px; text-align: left; border-bottom: 1px solid #dee2e6;">Lesson</th>
                                <th style="padding: 12px; text-align: left; border-bottom: 1px solid #dee2e6;">Comment</th>
                                <th style="padding: 12px; text-align: left; border-bottom: 1px solid #dee2e6;">Status</th>
                                <th style="padding: 12px; text-align: left; border-bottom: 1px solid #dee2e6;">Date</th>
                                <th style="padding: 12px; text-align: left; border-bottom: 1px solid #dee2e6;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($comments as $comment): ?>
                                <tr style="border-bottom: 1px solid #dee2e6;">
                                    <td style="padding: 12px;">#<?= $comment['id'] ?></td>
                                    <td style="padding: 12px;">
                                        <strong><?= htmlspecialchars($comment['user_name']) ?></strong><br>
                                        <small style="color: #666;"><?= htmlspecialchars($comment['email']) ?></small>
                                    </td>
                                    <td style="padding: 12px;">
                                        <?php if ($comment['lesson_title']): ?>
                                            <strong>Level <?= $comment['lesson_level'] ?></strong><br>
                                            <small><?= htmlspecialchars($comment['lesson_title']) ?></small>
                                        <?php else: ?>
                                            <span style="color: #666;">Lesson #<?= $comment['lesson_id'] ?> (Deleted)</span>
                                        <?php endif; ?>
                                    </td>
                                    <td style="padding: 12px;" class="comment-content">
                                        <?= nl2br(htmlspecialchars($comment['comment'])) ?>
                                    </td>
                                    <td style="padding: 12px;">
                                        <?php
                                        $statusClass = '';
                                        $statusText = '';
                                        
                                        switch ($comment['is_approved']) {
                                            case 0:
                                                $statusClass = 'status-pending';
                                                $statusText = '⏳ Pending';
                                                break;
                                            case 1:
                                                $statusClass = 'status-approved';
                                                $statusText = '✅ Approved';
                                                break;
                                        }
                                        ?>
                                        <span class="status-badge <?= $statusClass ?>">
                                            <?= $statusText ?>
                                        </span>
                                    </td>
                                    <td style="padding: 12px;">
                                        <small>
                                            <?= date('M j, Y', strtotime($comment['created_at'])) ?><br>
                                            <?= date('g:i A', strtotime($comment['created_at'])) ?>
                                        </small>
                                    </td>
                                    <td style="padding: 12px;" class="comment-actions">
                                        <?php if ($comment['is_approved'] == 0): ?>
                                            <button class="btn-approve" 
                                                    onclick="updateCommentStatus(<?= $comment['id'] ?>, 1)"
                                                    title="Approve">
                                                ✅ Approve
                                            </button>
                                        <?php else: ?>
                                            <button class="btn-disapprove" 
                                                    onclick="updateCommentStatus(<?= $comment['id'] ?>, 0)"
                                                    title="Set to Pending">
                                                ⏳ Set Pending
                                            </button>
                                        <?php endif; ?>
                                        
                                        <button class="btn-delete" 
                                                onclick="deleteComment(<?= $comment['id'] ?>)"
                                                title="Delete">
                                            🗑️ Delete
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
            
            <!-- Pagination -->
            <?php if ($totalPages > 1): ?>
                <div class="pagination">
                    <?php if ($page > 1): ?>
                        <a href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>">← Previous</a>
                    <?php endif; ?>
                    
                    <?php
                    $startPage = max(1, $page - 2);
                    $endPage = min($totalPages, $page + 2);
                    ?>
                    
                    <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
                        <a href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>" 
                           class="<?= $i === $page ? 'active' : '' ?>"><?= $i ?></a>
                    <?php endfor; ?>
                    
                    <?php if ($page < $totalPages): ?>
                        <a href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>">Next →</a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
    
    <script>
        function updateCommentStatus(commentId, status) {
            const statusText = status === 1 ? 'approve' : 'set to pending';
            
            if (!confirm(`Are you sure you want to ${statusText} this comment?`)) {
                return;
            }
            
            fetch('api/comments.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'update_status',
                    comment_id: commentId,
                    status: status
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    location.reload();
                } else {
                    // Show the actual error message from the server
                    alert('Error: ' + data.message + (data.debug ? '\nDebug: ' + data.debug : ''));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred while updating the comment status: ' + error.message);
            });
        }
        
        function deleteComment(commentId) {
            if (!confirm('Are you sure you want to delete this comment? This action cannot be undone.')) {
                return;
            }
            
            fetch('api/comments.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'delete',
                    comment_id: commentId
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    location.reload();
                } else {
                    // Show the actual error message from the server
                    alert('Error: ' + data.message + (data.debug ? '\nDebug: ' + data.debug : ''));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred while deleting the comment: ' + error.message);
            });
        }
    </script>
</body>
</html>