<?php
/**
 * Secure Lesson Comments API
 * Enhanced with comprehensive input validation and security measures
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-API-Key, User-Agent');

// Handle preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once 'config.php';
require_once 'enhanced_security.php';

// Validate API access with enhanced security
validateApiAccess();

// Get request method and handle accordingly
$method = $_SERVER['REQUEST_METHOD'];

try {
    $conn = getDBConnection();
    if (!$conn) {
        sendSecureResponse(false, 'Database connection failed', null, 500);
    }
    
    if ($method === 'GET') {
        // Get comments for a lesson
        handleGetComments($conn);
    } elseif ($method === 'POST') {
        // Add new comment
        handleAddComment($conn);
    } else {
        sendSecureResponse(false, 'Method not allowed', null, 405);
    }
    
} catch (Exception $e) {
    error_log("Comments API error: " . $e->getMessage());
    sendSecureResponse(false, 'An error occurred while processing your request', null, 500);
}

/**
 * Handle GET request to retrieve comments
 */
function handleGetComments($conn) {
    // Validate lesson_id parameter
    $lessonId = $_GET['lesson_id'] ?? '';
    if (empty($lessonId) || !is_numeric($lessonId)) {
        sendSecureResponse(false, 'Valid lesson ID is required', null, 400);
    }
    
    $lessonId = (int)$lessonId;
    if ($lessonId <= 0) {
        sendSecureResponse(false, 'Invalid lesson ID', null, 400);
    }
    
    // Pagination parameters with validation
    $page = max(1, (int)($_GET['page'] ?? 1));
    $perPage = min(50, max(5, (int)($_GET['per_page'] ?? 10))); // Limit between 5-50
    $offset = ($page - 1) * $perPage;
    
    try {
        // Verify lesson exists
        $stmt = $conn->prepare("SELECT id FROM lessons WHERE id = ? AND is_active = 1");
        $stmt->execute([$lessonId]);
        if (!$stmt->fetch()) {
            sendSecureResponse(false, 'Lesson not found', null, 404);
        }
        
        // Get total count of approved comments
        $stmt = $conn->prepare("
            SELECT COUNT(*) as total 
            FROM lesson_comments c
            JOIN users u ON c.user_id = u.id
            WHERE c.lesson_id = ? AND c.is_approved = 1 AND u.is_deleted = 0
        ");
        $stmt->execute([$lessonId]);
        $totalComments = $stmt->fetch()['total'];
        
        // Get paginated comments with user info
        $stmt = $conn->prepare("
            SELECT 
                c.id,
                c.comment,
                c.created_at,
                u.user_name,
                u.email,
                u.profile_picture
            FROM lesson_comments c
            JOIN users u ON c.user_id = u.id
            WHERE c.lesson_id = ? AND c.is_approved = 1 AND u.is_deleted = 0
            ORDER BY c.created_at DESC
            LIMIT ? OFFSET ?
        ");
        $stmt->execute([$lessonId, $perPage, $offset]);
        $comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Sanitize output data
        $sanitizedComments = array_map(function($comment) {
            return [
                'id' => (int)$comment['id'],
                'comment' => htmlspecialchars_decode($comment['comment']), // Safe to decode since it was sanitized on input
                'created_at' => $comment['created_at'],
                'user_name' => $comment['user_name'],
                'profile_picture' => $comment['profile_picture'],
                'user_email_hash' => hash('sha256', $comment['email']) // Don't expose actual email
            ];
        }, $comments);
        
        // Calculate pagination info
        $totalPages = ceil($totalComments / $perPage);
        
        sendSecureResponse(true, 'Comments retrieved successfully', [
            'comments' => $sanitizedComments,
            'pagination' => [
                'current_page' => $page,
                'per_page' => $perPage,
                'total_comments' => $totalComments,
                'total_pages' => $totalPages,
                'has_next' => $page < $totalPages,
                'has_previous' => $page > 1
            ]
        ]);
        
    } catch (Exception $e) {
        error_log("Get comments error: " . $e->getMessage());
        sendSecureResponse(false, 'Failed to retrieve comments', null, 500);
    }
}

/**
 * Handle POST request to add a new comment
 */
function handleAddComment($conn) {
    // Get and validate JSON input
    $rawInput = file_get_contents('php://input');
    if (empty($rawInput)) {
        sendSecureResponse(false, 'No input data provided', null, 400);
    }
    
    $input = json_decode($rawInput, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        sendSecureResponse(false, 'Invalid JSON format', null, 400);
    }
    
    try {
        // Validate required fields
        if (empty($input['token'])) {
            sendSecureResponse(false, 'Authentication token is required', null, 401);
        }
        
        if (empty($input['lesson_id'])) {
            sendSecureResponse(false, 'Lesson ID is required', null, 400);
        }
        
        if (empty($input['comment'])) {
            sendSecureResponse(false, 'Comment text is required', null, 400);
        }
        
        // Validate token and get user
        $token = SecurityValidator::validateText($input['token'], 255);
        $lessonId = (int)$input['lesson_id'];
        
        if ($lessonId <= 0) {
            sendSecureResponse(false, 'Invalid lesson ID', null, 400);
        }
        
        // Validate and sanitize comment
        $comment = SecurityValidator::validateComment($input['comment']);
        
        // Verify user session
        $stmt = $conn->prepare("
            SELECT s.user_id, u.user_name, u.email, u.is_deleted
            FROM user_sessions s
            JOIN users u ON s.user_id = u.id
            WHERE s.token = ? AND s.expires_at > NOW()
        ");
        $stmt->execute([$token]);
        $user = $stmt->fetch();
        
        if (!$user) {
            sendSecureResponse(false, 'Invalid or expired session', null, 401);
        }
        
        if ($user['is_deleted']) {
            sendSecureResponse(false, 'Account has been deleted', null, 403);
        }
        
        $userId = $user['user_id'];
        
        // Verify lesson exists and is active
        $stmt = $conn->prepare("SELECT id FROM lessons WHERE id = ? AND is_active = 1");
        $stmt->execute([$lessonId]);
        if (!$stmt->fetch()) {
            sendSecureResponse(false, 'Lesson not found', null, 404);
        }
        
        // Check if user has already commented on this lesson recently (prevent spam)
        $stmt = $conn->prepare("
            SELECT COUNT(*) as recent_comments
            FROM lesson_comments
            WHERE user_id = ? AND lesson_id = ? AND created_at > DATE_SUB(NOW(), INTERVAL 1 MINUTE)
        ");
        $stmt->execute([$userId, $lessonId]);
        $recentComments = $stmt->fetch()['recent_comments'];
        
        if ($recentComments > 0) {
            sendSecureResponse(false, 'Please wait before posting another comment', null, 429);
        }
        
        // Check daily comment limit (prevent spam)
        $stmt = $conn->prepare("
            SELECT COUNT(*) as daily_comments
            FROM lesson_comments
            WHERE user_id = ? AND created_at > DATE_SUB(NOW(), INTERVAL 1 DAY)
        ");
        $stmt->execute([$userId]);
        $dailyComments = $stmt->fetch()['daily_comments'];
        
        if ($dailyComments >= 20) { // Max 20 comments per day
            sendSecureResponse(false, 'Daily comment limit reached', null, 429);
        }
        
        // Insert comment (requires admin approval)
        $stmt = $conn->prepare("
            INSERT INTO lesson_comments (lesson_id, user_id, comment, is_approved, created_at, updated_at)
            VALUES (?, ?, ?, 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
        ");
        
        if (!$stmt->execute([$lessonId, $userId, $comment])) {
            error_log("Failed to insert comment: " . print_r($stmt->errorInfo(), true));
            sendSecureResponse(false, 'Failed to save comment', null, 500);
        }
        
        $commentId = $conn->lastInsertId();
        
        // Log successful comment submission
        error_log("Comment submitted - ID: $commentId, User: {$user['user_name']}, Lesson: $lessonId");
        
        sendSecureResponse(true, 'Comment submitted successfully and is pending approval', [
            'comment_id' => $commentId,
            'requires_approval' => true,
            'message' => 'Your comment will appear after admin approval'
        ]);
        
    } catch (InvalidArgumentException $e) {
        error_log("Comment validation error: " . $e->getMessage());
        sendSecureResponse(false, $e->getMessage(), null, 400);
        
    } catch (Exception $e) {
        error_log("Add comment error: " . $e->getMessage());
        sendSecureResponse(false, 'Failed to submit comment', null, 500);
    }
}
?>