<?php
require_once __DIR__ . '/../../db/config.php';

try {
    $pdo = db();

    // First, add the column without the foreign key constraint
    $sql_add_column = "ALTER TABLE calendar_events ADD COLUMN event_type_id INT NULL;";
    $pdo->exec($sql_add_column);

    // Set a default value for existing rows to avoid foreign key constraint errors
    // Get the ID of the 'Other' event type
    $stmt = $pdo->query("SELECT id FROM event_types WHERE name = 'Other' LIMIT 1");
    $other_type = $stmt->fetch(PDO::FETCH_ASSOC);
    $default_type_id = $other_type ? $other_type['id'] : 1; // Fallback to 1 if 'Other' not found

    $sql_update_existing = "UPDATE calendar_events SET event_type_id = ? WHERE event_type_id IS NULL;";
    $stmt_update = $pdo->prepare($sql_update_existing);
    $stmt_update->execute([$default_type_id]);

    // Now, add the foreign key constraint
    $sql_add_fk = "ALTER TABLE calendar_events ADD CONSTRAINT fk_event_type FOREIGN KEY (event_type_id) REFERENCES event_types(id) ON DELETE SET NULL;";
    $pdo->exec($sql_add_fk);

    echo "Migration 004 completed successfully.\n";
} catch (PDOException $e) {
    // Check if the column already exists, which might happen on re-runs
    if (strpos($e->getMessage(), 'Duplicate column name') !== false) {
        echo "Migration 004 seems to be already applied (Column exists). Skipping.\n";
    } else {
        die("Migration 004 failed: " . $e->getMessage() . "\n");
    }
}

