<?php

require_once 'bootstrap.php';

$app = new \Espo\Core\Application();
$entityManager = $app->getContainer()->get('entityManager');
$pdo = $entityManager->getPDO();

echo "=== Junction-Tabelle Überprüfung ===\n\n";

// Prüfe ob die Tabelle existiert
$sql = "SHOW TABLES LIKE 'c_ai_collection_c_dokumente'";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$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";
    $sql = "DESCRIBE c_ai_collection_c_dokumente";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $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 "Verfü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->prepare($sql);
    $stmt->execute();
    while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
        echo "  - " . $row[0] . "\n";
    }
    
    $sql = "SHOW TABLES LIKE '%c_dok%'";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
        echo "  - " . $row[0] . "\n";
    }
}
