<?php
/**
 * Run Clean Migration for Phase 7 Additional Features
 * OBGYN Research & Collaboration Platform
 */

require_once __DIR__ . '/../config/config.php';

try {
    $db = getDB();

    // Read the migration file
    $migrationSQL = file_get_contents(__DIR__ . '/clean_migration.sql');

    if (!$migrationSQL) {
        throw new Exception("Could not read migration file");
    }

    // Split into individual statements
    $statements = array_filter(array_map('trim', explode(';', $migrationSQL)));

    // Disable foreign key checks for the session
    $db->exec("SET FOREIGN_KEY_CHECKS = 0;");

    foreach ($statements as $statement) {
        if (!empty($statement) && !preg_match('/^--/', $statement)) {
            echo "Executing: " . substr($statement, 0, 50) . "...\n";
            $db->exec($statement);
        }
    }

    // Re-enable foreign key checks
    $db->exec("SET FOREIGN_KEY_CHECKS = 1;");

    echo "\n✅ Clean migration completed successfully!\n";
    echo "All Phase 7 tables have been created.\n";

} catch (Exception $e) {
    if (isset($db) && $db->inTransaction()) {
        $db->rollBack();
    }
    echo "\n❌ Migration failed: " . $e->getMessage() . "\n";
    exit(1);
}
?>
