<?php
header('Content-Type: application/json');
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';

// API Security Configuration
define('API_KEY', 'ensi_app_2025_secure_key_v1'); // Must match lesson_service.dart
define('ALLOWED_USER_AGENTS', [
    'Dart/', // Flutter/Dart HTTP client
    'ensi-flutter-app', // Custom user agent for your app
]);

// Helper: Validate API access
function validateApiAccess() {
    // Check API Key
    $apiKey = $_SERVER['HTTP_X_API_KEY'] ?? $_GET['api_key'] ?? '';
    if ($apiKey !== API_KEY) {
        http_response_code(403);
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access. Invalid API key.',
            'status_code' => 403
        ]);
        exit;
    }
    
    // Check User Agent
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $isValidUserAgent = false;
    
    foreach (ALLOWED_USER_AGENTS as $allowedAgent) {
        if (strpos($userAgent, $allowedAgent) !== false) {
            $isValidUserAgent = true;
            break;
        }
    }
    
    if (!$isValidUserAgent) {
        http_response_code(403);
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access. Invalid client.',
            'status_code' => 403
        ]);
        exit;
    }
}

// Validate API access before processing any requests
validateApiAccess();

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Only POST requests are allowed');
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';

try {
    $conn = getDBConnection();
    
    switch ($action) {
        case 'get_comments':
            // Get approved comments for a lesson
            $lessonId = $input['lesson_id'] ?? 0;
            
            if (!$lessonId) {
                sendResponse(false, 'Lesson ID is required');
            }
            
            $stmt = $conn->prepare("
                SELECT c.*, 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
            ");
            $stmt->execute([$lessonId]);
            $comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            sendResponse(true, 'Comments retrieved successfully', $comments);
            break;
            
        case 'add_comment':
            // Add a new comment (requires authentication)
            $token = $input['token'] ?? '';
            $lessonId = $input['lesson_id'] ?? 0;
            $comment = trim($input['comment'] ?? '');
            
            if (empty($token)) {
                sendResponse(false, 'Authentication required');
            }
            
            if (!$lessonId || empty($comment)) {
                sendResponse(false, 'Lesson ID and comment are required');
            }
            
            // Validate session
            $stmt = $conn->prepare("
                SELECT user_id FROM user_sessions 
                WHERE token = ? AND expires_at > NOW()
            ");
            $stmt->execute([$token]);
            $session = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$session) {
                sendResponse(false, 'Invalid or expired session');
            }
            
            // Insert comment (pending approval)
            $stmt = $conn->prepare("
                INSERT INTO lesson_comments (lesson_id, user_id, comment, is_approved) 
                VALUES (?, ?, ?, 0)
            ");
            $stmt->execute([$lessonId, $session['user_id'], $comment]);
            
            sendResponse(true, 'Comment submitted successfully. It will appear after admin approval.');
            break;
            
        default:
            sendResponse(false, 'Invalid action');
    }
    
} catch (PDOException $e) {
    error_log("Comments API error: " . $e->getMessage());
    sendResponse(false, 'An error occurred');
}
