<?php

// Direct PDO connection to check database
$config = include 'data/config-internal.php';
$db = $config['database'];

try {
    $pdo = new PDO(
        "mysql:host={$db['host']};dbname={$db['dbname']}",
        $db['user'],
        $db['password']
    );
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "=== Junction-Tabelle Überprüfung ===\n\n";
    
    // Prüfe ob die Tabelle existiert
    $sql = "SHOW TABLES LIKE 'c_ai_collection_c_dokumente'";
    $stmt = $pdo->query($sql);
    $tableExists = $stmt->fetch();
    
    if ($tableExists) {
        echo "✓ Tabelle 'c_ai_collection_c_dokumente' existiert\n\n";
        
        // Zeige die Struktur
        echo "Tabellenstruktur:\n";
        echo str_repeat("-", 80) . "\n";
        printf("%-30s %-20s %-10s %-10s\n", "Field", "Type", "Null", "Key");
        echo str_repeat("-", 80) . "\n";
        
        $sql = "DESCRIBE c_ai_collection_c_dokumente";
        $stmt = $pdo->query($sql);
        $columns = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        foreach ($columns as $column) {
            printf("%-30s %-20s %-10s %-10s\n", 
                $column['Field'], 
                $column['Type'], 
                $column['Null'], 
                $column['Key']
            );
        }
        
        // Prüfe speziell auf syncId
        echo "\n" . str_repeat("-", 80) . "\n";
        $syncIdExists = false;
        foreach ($columns as $column) {
            if ($column['Field'] === 'sync_id') {
                $syncIdExists = true;
                break;
            }
        }
        
        if ($syncIdExists) {
            echo "✓ Spalte 'sync_id' ist in der Junction-Tabelle vorhanden\n";
        } else {
            echo "✗ Spalte 'sync_id' fehlt in der Junction-Tabelle\n";
            echo "\nVerfügbare Spalten: " . implode(', ', array_column($columns, 'Field')) . "\n";
        }
    } else {
        echo "✗ Tabelle 'c_ai_collection_c_dokumente' existiert nicht\n";
        echo "\nVerfügbare Tabellen (mit 'c_ai' oder 'c_dok' im Namen):\n";
        
        $sql = "SHOW TABLES LIKE '%c_ai%'";
        $stmt = $pdo->query($sql);
        while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
            echo "  - " . $row[0] . "\n";
        }
        
        echo "\n";
        $sql = "SHOW TABLES LIKE '%c_dok%'";
        $stmt = $pdo->query($sql);
        while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
            echo "  - " . $row[0] . "\n";
        }
    }
    
} catch (PDOException $e) {
    echo "Fehler: " . $e->getMessage() . "\n";
}
