<?php
/**
 * Comments API Endpoint
 * Handles lesson comments with security, pagination, and authentication
 */

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');

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

require_once 'config.php';

/**
 * Sanitize comment input to prevent XSS and SQL injection
 */
function sanitizeCommentInput($input) {
    // Remove script tags and dangerous content
    $input = preg_replace('/<script\b[^>]*>.*?<\/script>/is', '', $input);
    $input = preg_replace('/<iframe\b[^>]*>.*?<\/iframe>/is', '', $input);
    $input = preg_replace('/javascript:/i', '', $input);
    $input = preg_replace('/on\w+\s*=/i', '', $input);
    
    // Trim whitespace
    $input = trim($input);
    
    return $input;
}

/**
 * Validate comment content
 */
function validateComment($comment) {
    $comment = trim($comment);
    
    if (empty($comment)) {
        return ['valid' => false, 'message' => 'Comment cannot be empty'];
    }
    
    if (mb_strlen($comment) < 3) {
        return ['valid' => false, 'message' => 'Comment must be at least 3 characters'];
    }
    
    if (mb_strlen($comment) > 1000) {
        return ['valid' => false, 'message' => 'Comment must be less than 1000 characters'];
    }
    
    return ['valid' => true];
}

try {
    $conn = getDBConnection();
    
    // Check if database connection is successful
    if ($conn === null) {
        throw new PDOException("Failed to establish database connection");
    }
    
    // Get action from query parameter for GET or from body for POST
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        $action = $_GET['action'] ?? '';
    } else {
        $input = json_decode(file_get_contents('php://input'), true);
        $action = $input['action'] ?? '';
    }
    
    switch ($action) {
        case 'get':
            // Get approved comments with pagination
            $lessonId = $_GET['lesson_id'] ?? 0;
            $page = max(1, (int)($_GET['page'] ?? 1));
            $limit = min(20, max(1, (int)($_GET['limit'] ?? 5))); // Max 20 per page
            $offset = ($page - 1) * $limit;
            
            if (!$lessonId) {
                http_response_code(400);
                echo json_encode([
                    'success' => false,
                    'message' => 'Lesson ID is required'
                ], JSON_UNESCAPED_UNICODE);
                exit;
            }
            
            // Get total count
            $countStmt = $conn->prepare("
                SELECT COUNT(*) as total 
                FROM lesson_comments 
                WHERE lesson_id = ? AND is_approved = 1
            ");
            $countStmt->execute([$lessonId]);
            $totalComments = (int)$countStmt->fetch(PDO::FETCH_ASSOC)['total'];
            $totalPages = ceil($totalComments / $limit);
            
            // Get comments with user info
            $stmt = $conn->prepare("
                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
                FROM lesson_comments c
                JOIN users u ON c.user_id = u.id
                WHERE c.lesson_id = ? AND c.is_approved = 1
                ORDER BY c.created_at DESC
                LIMIT $limit OFFSET $offset
            ");
            $stmt->execute([$lessonId]);
            $comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Add profile picture URLs
            foreach ($comments as &$comment) {
                $comment['user_profile_picture'] = "https://api.dicebear.com/7.x/fun-emoji/jpg?seed=" . urlencode($comment['email']);
                unset($comment['email']); // Remove email from response for privacy
            }
            
            $response = [
                'success' => true,
                'message' => 'Comments loaded successfully',
                'data' => $comments,
                'total' => $totalComments,
                'page' => $page,
                'limit' => $limit,
                'total_pages' => $totalPages
            ];
            
            http_response_code(200);
            echo json_encode($response, JSON_UNESCAPED_UNICODE);
            exit;
            break;
            
        case 'post':
            // Post a new comment (requires authentication)
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                http_response_code(405);
                echo json_encode([
                    'success' => false,
                    'message' => 'Method not allowed'
                ], JSON_UNESCAPED_UNICODE);
                exit;
            }
            
            $input = json_decode(file_get_contents('php://input'), true);
            
            $authToken = $input['auth_token'] ?? '';
            $lessonId = $input['lesson_id'] ?? 0;
            $comment = $input['comment'] ?? '';
            
            // Validate auth token
            if (empty($authToken)) {
                http_response_code(401);
                echo json_encode([
                    'success' => false,
                    'message' => 'Authentication required. Please log in.'
                ], JSON_UNESCAPED_UNICODE);
                exit;
            }
            
            // Validate user session and get the REAL user_id from session (don't trust client)
            $sessionStmt = $conn->prepare("
                SELECT s.user_id, s.expires_at, u.is_verified
                FROM user_sessions s
                JOIN users u ON s.user_id = u.id
                WHERE s.token = ? AND u.is_deleted = 0
            ");
            $sessionStmt->execute([$authToken]);
            $session = $sessionStmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$session) {
                http_response_code(401);
                echo json_encode([
                    'success' => false,
                    'message' => 'Invalid session. Please log in again.'
                ], JSON_UNESCAPED_UNICODE);
                exit;
            }
            
            if (strtotime($session['expires_at']) < time()) {
                http_response_code(401);
                echo json_encode([
                    'success' => false,
                    'message' => 'Session expired. Please log in again.'
                ], JSON_UNESCAPED_UNICODE);
                exit;
            }
            
            // Use the user_id from the session (TRUSTED source), not from request
            $userId = $session['user_id'];
            
            // Check if user is verified
            if (!$session['is_verified']) {
                http_response_code(403);
                echo json_encode([
                    'success' => false,
                    'message' => 'You need to verify your account to post comments'
                ], JSON_UNESCAPED_UNICODE);
                exit;
            }
            
            // Sanitize comment
            $comment = sanitizeCommentInput($comment);
            
            // Validate comment
            $validation = validateComment($comment);
            if (!$validation['valid']) {
                http_response_code(400);
                echo json_encode([
                    'success' => false,
                    'message' => $validation['message']
                ], JSON_UNESCAPED_UNICODE);
                exit;
            }
            
            // Check if lesson exists
            $lessonStmt = $conn->prepare("SELECT id FROM lessons WHERE id = ?");
            $lessonStmt->execute([$lessonId]);
            if (!$lessonStmt->fetch()) {
                http_response_code(404);
                echo json_encode([
                    'success' => false,
                    'message' => 'Lesson not found'
                ], JSON_UNESCAPED_UNICODE);
                exit;
            }
            
            // Rate limiting: Check if user posted recently (prevent spam)
            $rateLimitStmt = $conn->prepare("
                SELECT created_at 
                FROM lesson_comments 
                WHERE user_id = ? 
                ORDER BY created_at DESC 
                LIMIT 1
            ");
            $rateLimitStmt->execute([$userId]);
            $lastComment = $rateLimitStmt->fetch(PDO::FETCH_ASSOC);
            
            if ($lastComment) {
                $timeSinceLastComment = time() - strtotime($lastComment['created_at']);
                if ($timeSinceLastComment < 30) { // 30 seconds cooldown
                    http_response_code(429);
                    echo json_encode([
                        'success' => false,
                        'message' => 'Please wait before posting another comment'
                    ], JSON_UNESCAPED_UNICODE);
                    exit;
                }
            }
            
            // Insert comment (pending admin approval)
            $insertStmt = $conn->prepare("
                INSERT INTO lesson_comments 
                (lesson_id, user_id, comment, is_approved, created_at, updated_at) 
                VALUES (?, ?, ?, 0, NOW(), NOW())
            ");
            
            try {
                $insertStmt->execute([$lessonId, $userId, $comment]);
                $commentId = $conn->lastInsertId();
                
                // Get the created comment
                $getCommentStmt = $conn->prepare("
                    SELECT 
                        c.id,
                        c.lesson_id,
                        c.user_id,
                        c.comment,
                        c.is_approved,
                        c.created_at,
                        c.updated_at,
                        u.user_name
                    FROM lesson_comments c
                    JOIN users u ON c.user_id = u.id
                    WHERE c.id = ?
                ");
                $getCommentStmt->execute([$commentId]);
                $newComment = $getCommentStmt->fetch(PDO::FETCH_ASSOC);
                
                http_response_code(200);
                echo json_encode([
                    'success' => true,
                    'message' => 'Thank you! Your comment has been submitted and will appear after admin approval. 🎉',
                    'data' => $newComment
                ], JSON_UNESCAPED_UNICODE);
                exit;
            } catch (PDOException $e) {
                error_log("Error inserting comment: " . $e->getMessage());
                http_response_code(500);
                echo json_encode([
                    'success' => false,
                    'message' => 'Failed to post comment. Please try again.'
                ], JSON_UNESCAPED_UNICODE);
                exit;
            }
            break;
            
        case 'count':
            // Get total approved comment count for a lesson
            $lessonId = $_GET['lesson_id'] ?? 0;
            
            if (!$lessonId) {
                http_response_code(400);
                echo json_encode([
                    'success' => false,
                    'message' => 'Lesson ID is required'
                ], JSON_UNESCAPED_UNICODE);
                exit;
            }
            
            $stmt = $conn->prepare("
                SELECT COUNT(*) as count 
                FROM lesson_comments 
                WHERE lesson_id = ? AND is_approved = 1
            ");
            $stmt->execute([$lessonId]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            
            http_response_code(200);
            echo json_encode([
                'success' => true,
                'message' => 'Count retrieved',
                'count' => (int)$result['count']
            ], JSON_UNESCAPED_UNICODE);
            exit;
            break;
            
        default:
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => 'Invalid action. Supported actions: get, post, count'
            ], JSON_UNESCAPED_UNICODE);
            exit;
    }
    
} catch (PDOException $e) {
    error_log("Comments API Database Error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'A database error occurred. Please try again later.'
    ], JSON_UNESCAPED_UNICODE);
    exit;
} catch (Exception $e) {
    error_log("Comments API Error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred. Please try again later.'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}
?>
