<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

header('Content-Type: text/plain');

echo "=== Testing lessons.php ===\n\n";

// Test 1: Can we load config?
echo "1. Loading config.php...\n";
require_once 'config.php';
echo "   ✓ Config loaded\n\n";

// Test 2: Can we connect to DB?
echo "2. Connecting to database...\n";
$conn = getDBConnection();
if (!$conn) {
    echo "   ✗ Connection failed!\n";
    exit;
}
echo "   ✓ Connected to: " . DB_NAME . "\n\n";

// Test 3: Can we query lessons?
echo "3. Querying lessons table...\n";
try {
    $stmt = $conn->prepare("SELECT * FROM lessons WHERE is_active = 1 ORDER BY level ASC, order_index ASC");
    $stmt->execute();
    $lessons = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo "   ✓ Found " . count($lessons) . " lessons\n\n";
    
    // Test 4: Can we decode JSON?
    echo "4. Testing JSON decode...\n";
    foreach ($lessons as &$lesson) {
        $lesson['pronunciation_phrases'] = json_decode($lesson['pronunciation_phrases'] ?? '[]');
        $lesson['listen_write_phrases'] = json_decode($lesson['listen_write_phrases'] ?? '[]');
    }
    echo "   ✓ JSON decoded successfully\n\n";
    
    // Test 5: Can we group by level?
    echo "5. Grouping by level...\n";
    $groupedLessons = [];
    foreach ($lessons as $lesson) {
        $level = $lesson['level'];
        if (!isset($groupedLessons[$level])) {
            $groupedLessons[$level] = [];
        }
        $groupedLessons[$level][] = $lesson;
    }
    echo "   ✓ Grouped into " . count($groupedLessons) . " levels\n\n";
    
    echo "=== ALL TESTS PASSED ===\n";
    echo "\nNow testing actual lessons.php file...\n\n";
    
    // Include the actual file
    $_GET['action'] = 'list';
    ob_start();
    include 'lessons.php';
    $output = ob_get_clean();
    
    echo "Output from lessons.php:\n";
    echo $output;
    
} catch (Exception $e) {
    echo "   ✗ Error: " . $e->getMessage() . "\n";
    echo "   Stack trace:\n" . $e->getTraceAsString() . "\n";
}
