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

try {
    $db = db();
    echo "Starting migration 032.\n";

    // Step 1: Add bni_group_id column
    try {
        echo "Step 1: Adding bni_group_id column...\n";
        $db->exec("ALTER TABLE meetings ADD COLUMN bni_group_id INT(11) UNSIGNED NULL;");
        echo "SUCCESS: Added nullable bni_group_id column.\n";
    } catch (PDOException $e) {
        if (strpos($e->getMessage(), 'Duplicate column name') !== false) {
            echo "INFO: bni_group_id column already exists.\n";
        } else {
            throw $e;
        }
    }

    // Step 2: Add meeting_datetime column
    try {
        echo "Step 2: Adding meeting_datetime column...\n";
        $db->exec("ALTER TABLE meetings ADD COLUMN meeting_datetime DATETIME NULL;");
        echo "SUCCESS: Added nullable meeting_datetime column.\n";
    } catch (PDOException $e) {
        if (strpos($e->getMessage(), 'Duplicate column name') !== false) {
            echo "INFO: meeting_datetime column already exists.\n";
        } else {
            throw $e;
        }
    }

    // Step 3: Add meeting_key column
    try {
        echo "Step 3: Adding meeting_key column...\n";
        $db->exec("ALTER TABLE meetings ADD COLUMN meeting_key VARCHAR(255) NULL;");
        echo "SUCCESS: Added nullable meeting_key column.\n";
    } catch (PDOException $e) {
        if (strpos($e->getMessage(), 'Duplicate column name') !== false) {
            echo "INFO: meeting_key column already exists.\n";
        } else {
            throw $e;
        }
    }

    // Step 4: Populate meeting_key
    echo "Step 4: Populating meeting_key...\n";
    $updateStmt = $db->prepare("UPDATE meetings SET meeting_key = CONCAT(bni_group_id, '_', meeting_datetime) WHERE (meeting_key IS NULL OR meeting_key = '') AND bni_group_id IS NOT NULL AND meeting_datetime IS NOT NULL");
    $updateStmt->execute();
    echo "SUCCESS: Populated meeting_key for " . $updateStmt->rowCount() . " rows.\n";

    // Step 5: Add unique index on meeting_key
    try {
        echo "Step 5: Adding unique index on meeting_key...\n";
        $db->exec("ALTER TABLE meetings ADD UNIQUE (meeting_key);");
        echo "SUCCESS: Added unique index on meeting_key.\n";
    } catch (PDOException $e) {
        if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
            echo "WARNING: Could not add UNIQUE index because duplicate meeting_key values exist.\n";
        } elseif (strpos($e->getMessage(), 'already exists') !== false) {
            echo "INFO: Unique index on meeting_key already exists.\n";
        } else {
            throw $e;
        }
    }

    echo "Migration 032 completed successfully.\n";

} catch (Exception $e) {
    error_log("Migration 032 failed: " . $e->getMessage());
    die("FATAL: Migration 032 failed: " . $e->getMessage() . "\n");
}