<?php
/**
 * Admin Comment Management API
 * Handle comment approval, disapproval, and deletion
 */

require_once '../config.php';

// Start admin session
if (session_status() === PHP_SESSION_NONE) {
    session_name(ADMIN_SESSION_NAME);
    session_start();
}

// Check admin authentication
if (!isset($_SESSION['admin_id']) || !isset($_SESSION['admin_username'])) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => 'Admin authentication required'
    ]);
    exit;
}

header('Content-Type: application/json; charset=UTF-8');

try {
    $pdo = getDBConnection();
    
    if ($pdo === null) {
        throw new Exception("Failed to establish database connection");
    }
    
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? '';
    
    switch ($action) {
        case 'update_status':
            // Update comment approval status
            $commentId = (int)($input['comment_id'] ?? 0);
            $status = (int)($input['status'] ?? 0); // 1 = approved, -1 = disapproved, 0 = pending
            
            if ($commentId <= 0) {
                throw new Exception("Invalid comment ID");
            }
            
            if (!in_array($status, [-1, 0, 1])) {
                throw new Exception("Invalid status. Use -1 (disapproved), 0 (pending), or 1 (approved)");
            }
            
            // Get comment details before update for logging
            $getCommentStmt = $pdo->prepare("
                SELECT c.id, c.comment, u.user_name, l.title as lesson_title 
                FROM lesson_comments c 
                LEFT JOIN users u ON c.user_id = u.id 
                LEFT JOIN lessons l ON c.lesson_id = l.id 
                WHERE c.id = ?
            ");
            $getCommentStmt->execute([$commentId]);
            $comment = $getCommentStmt->fetch();
            
            if (!$comment) {
                throw new Exception("Comment not found");
            }
            
            // Update comment status
            $updateStmt = $pdo->prepare("
                UPDATE lesson_comments 
                SET is_approved = ?, updated_at = NOW() 
                WHERE id = ?
            ");
            $updateStmt->execute([$status, $commentId]);
            
            if ($updateStmt->rowCount() === 0) {
                throw new Exception("Failed to update comment status");
            }
            
            // Log admin action
            $statusText = '';
            switch ($status) {
                case 1: $statusText = 'approved'; break;
                case -1: $statusText = 'disapproved'; break;
                case 0: $statusText = 'set to pending'; break;
            }
            
            $logDescription = "Comment #{$commentId} {$statusText} - User: {$comment['user_name']}, Comment: " . substr($comment['comment'], 0, 100);
            logAdminAction($_SESSION['admin_id'], 'comment_status_update', $logDescription);
            
            http_response_code(200);
            echo json_encode([
                'success' => true,
                'message' => "Comment {$statusText} successfully",
                'comment_id' => $commentId,
                'new_status' => $status
            ]);
            break;
            
        case 'delete':
            // Delete comment permanently
            $commentId = (int)($input['comment_id'] ?? 0);
            
            if ($commentId <= 0) {
                throw new Exception("Invalid comment ID");
            }
            
            // Get comment details before deletion for logging
            $getCommentStmt = $pdo->prepare("
                SELECT c.id, c.comment, u.user_name, l.title as lesson_title 
                FROM lesson_comments c 
                LEFT JOIN users u ON c.user_id = u.id 
                LEFT JOIN lessons l ON c.lesson_id = l.id 
                WHERE c.id = ?
            ");
            $getCommentStmt->execute([$commentId]);
            $comment = $getCommentStmt->fetch();
            
            if (!$comment) {
                throw new Exception("Comment not found");
            }
            
            // Delete comment
            $deleteStmt = $pdo->prepare("DELETE FROM lesson_comments WHERE id = ?");
            $deleteStmt->execute([$commentId]);
            
            if ($deleteStmt->rowCount() === 0) {
                throw new Exception("Failed to delete comment");
            }
            
            // Log admin action
            $logDescription = "Comment #{$commentId} deleted - User: {$comment['user_name']}, Comment: " . substr($comment['comment'], 0, 100);
            logAdminAction($_SESSION['admin_id'], 'comment_delete', $logDescription);
            
            http_response_code(200);
            echo json_encode([
                'success' => true,
                'message' => 'Comment deleted successfully',
                'comment_id' => $commentId
            ]);
            break;
            
        case 'bulk_action':
            // Bulk approve/disapprove/delete multiple comments
            $commentIds = $input['comment_ids'] ?? [];
            $bulkAction = $input['bulk_action'] ?? '';
            
            if (empty($commentIds) || !is_array($commentIds)) {
                throw new Exception("No comments selected");
            }
            
            if (!in_array($bulkAction, ['approve', 'disapprove', 'delete'])) {
                throw new Exception("Invalid bulk action");
            }
            
            $placeholders = str_repeat('?,', count($commentIds) - 1) . '?';
            $affectedRows = 0;
            
            if ($bulkAction === 'delete') {
                // Get comment details for logging
                $getCommentsStmt = $pdo->prepare("
                    SELECT c.id, c.comment, u.user_name 
                    FROM lesson_comments c 
                    LEFT JOIN users u ON c.user_id = u.id 
                    WHERE c.id IN ($placeholders)
                ");
                $getCommentsStmt->execute($commentIds);
                $comments = $getCommentsStmt->fetchAll();
                
                // Delete comments
                $deleteStmt = $pdo->prepare("DELETE FROM lesson_comments WHERE id IN ($placeholders)");
                $deleteStmt->execute($commentIds);
                $affectedRows = $deleteStmt->rowCount();
                
                // Log action
                $commentIdsList = implode(', ', $commentIds);
                logAdminAction($_SESSION['admin_id'], 'bulk_comment_delete', "Bulk deleted {$affectedRows} comments: #{$commentIdsList}");
                
            } else {
                // Approve or disapprove
                $status = ($bulkAction === 'approve') ? 1 : -1;
                
                $updateStmt = $pdo->prepare("
                    UPDATE lesson_comments 
                    SET is_approved = ?, updated_at = NOW() 
                    WHERE id IN ($placeholders)
                ");
                $updateParams = array_merge([$status], $commentIds);
                $updateStmt->execute($updateParams);
                $affectedRows = $updateStmt->rowCount();
                
                // Log action
                $commentIdsList = implode(', ', $commentIds);
                $statusText = ($bulkAction === 'approve') ? 'approved' : 'disapproved';
                logAdminAction($_SESSION['admin_id'], "bulk_comment_{$bulkAction}", "Bulk {$statusText} {$affectedRows} comments: #{$commentIdsList}");
            }
            
            http_response_code(200);
            echo json_encode([
                'success' => true,
                'message' => "Bulk action completed. {$affectedRows} comments affected.",
                'affected_count' => $affectedRows,
                'action' => $bulkAction
            ]);
            break;
            
        case 'get_stats':
            // 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,
                    SUM(CASE WHEN is_approved = -1 THEN 1 ELSE 0 END) as disapproved,
                    COUNT(CASE WHEN DATE(created_at) = CURDATE() THEN 1 END) as today
                FROM lesson_comments
            ");
            $stats = $statsStmt->fetch();
            
            http_response_code(200);
            echo json_encode([
                'success' => true,
                'stats' => $stats
            ]);
            break;
            
        default:
            throw new Exception("Invalid action. Supported actions: update_status, delete, bulk_action, get_stats");
    }
    
} catch (Exception $e) {
    error_log("Admin Comments API Error: " . $e->getMessage());
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>