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

try {
    $db = db();
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Starting migration 034: Set bni_group_id in meeting_attendance to NOT NULL.\n";

    // First, check if there are any NULL values in the bni_group_id column.
    $null_check = $db->query("SELECT COUNT(*) FROM meeting_attendance WHERE bni_group_id IS NULL;")->fetchColumn();

    if ($null_check > 0) {
        echo "WARNING: Found $null_check rows with NULL bni_group_id. Attempting to populate them.\n";
        
        // Try to populate from the corresponding meeting record
        $update_sql = "UPDATE meeting_attendance ma JOIN meetings m ON ma.meeting_id = m.id SET ma.bni_group_id = m.bni_group_id WHERE ma.bni_group_id IS NULL AND m.bni_group_id IS NOT NULL;";
        $stmt = $db->exec($update_sql);
        echo "Populated $stmt rows based on meeting ID.\n";

        // Re-check for NULLs
        $null_check_after = $db->query("SELECT COUNT(*) FROM meeting_attendance WHERE bni_group_id IS NULL;")->fetchColumn();
        if($null_check_after > 0) {
            // If still NULLs, we have to fail.
             throw new Exception("$null_check_after rows still have NULL bni_group_id after population attempt. Cannot proceed.");
        }
    }

    echo "No NULL values found in bni_group_id. Altering column to NOT NULL.\n";
    $db->exec("ALTER TABLE meeting_attendance MODIFY bni_group_id INT(11) NOT NULL;");
    echo "SUCCESS: Column bni_group_id in meeting_attendance is now NOT NULL.\n";

    echo "Migration 034 completed successfully.\n";

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