<?php
require_once 'config.php';

$conn = getDBConnection();

// Check if user_id column exists
$result = $conn->query("SHOW COLUMNS FROM events LIKE 'user_id'");

if ($result->num_rows === 0) {
    // Add user_id column
    $sql = "ALTER TABLE events ADD COLUMN user_id INT(11) NOT NULL DEFAULT 0 AFTER id";
    
    if ($conn->query($sql) === TRUE) {
        echo "Added user_id column to events table successfully!<br>";
        
        // Add index
        $conn->query("ALTER TABLE events ADD INDEX idx_user_id (user_id)");
        
        // Add unique constraint for user_id and event_slug combination
        // First, check if unique constraint already exists
        $result = $conn->query("SHOW INDEX FROM events WHERE Key_name = 'unique_user_slug'");
        if ($result->num_rows === 0) {
            $conn->query("ALTER TABLE events ADD UNIQUE KEY unique_user_slug (user_id, event_slug)");
        }
        
        echo "Migration completed successfully!<br>";
    } else {
        echo "Error: " . $conn->error . "<br>";
    }
} else {
    echo "Events table already has user_id column. No migration needed.<br>";
}

// Check if celebrant2 allows NULL
$result = $conn->query("SHOW COLUMNS FROM events WHERE Field = 'celebrant2' AND Null = 'YES'");
if ($result->num_rows === 0) {
    $conn->query("ALTER TABLE events MODIFY celebrant2 VARCHAR(255) NULL");
    echo "Updated celebrant2 to allow NULL values.<br>";
}

$conn->close();
echo "<br><strong>Migration completed!</strong><br>";
echo "<a href='register.php'>Go to Registration</a>";
?>

