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

try {
    $pdo = db();
    
    // First, check if the column already exists
    $stmt = $pdo->query("SHOW COLUMNS FROM `functions` LIKE 'bni_group_id'");
    $exists = $stmt->fetch(PDO::FETCH_ASSOC);

    // Check if the foreign key constraint already exists
    $stmt = $pdo->query("SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'functions' AND CONSTRAINT_NAME = 'fk_functions_bni_group'");
    $fk_exists = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($fk_exists) {
        echo "Migration 015 skipped: Foreign key 'fk_functions_bni_group' already exists." . PHP_EOL;
        return;
    }

    if (!$exists) {
        // Add the bni_group_id column allowing NULLs temporarily
        $pdo->exec("ALTER TABLE `functions` ADD COLUMN `bni_group_id` INT NULL AFTER `id`;");
        echo "Column 'bni_group_id' added." . PHP_EOL;
    }

    // Find a default group to assign to existing functions
    $stmt = $pdo->query("SELECT id FROM `bni_groups` ORDER BY id LIMIT 1");
    $default_group = $stmt->fetch(PDO::FETCH_ASSOC);
    $default_group_id = $default_group ? $default_group['id'] : null;

    if ($default_group_id) {
        // Update existing functions to use the default group where bni_group_id is not valid
        $pdo->exec("UPDATE `functions` SET `bni_group_id` = {$default_group_id} WHERE `bni_group_id` IS NULL OR `bni_group_id` NOT IN (SELECT id FROM bni_groups)");
        echo "Existing functions updated with a valid group ID." . PHP_EOL;
        
        // Now that existing rows are updated, alter the column to be NOT NULL
        $pdo->exec("ALTER TABLE `functions` MODIFY COLUMN `bni_group_id` INT NOT NULL;");
        echo "Column 'bni_group_id' modified to NOT NULL." . PHP_EOL;

        // Add the foreign key constraint
        $pdo->exec("ALTER TABLE `functions` ADD CONSTRAINT `fk_functions_bni_group` FOREIGN KEY (`bni_group_id`) REFERENCES `bni_groups`(`id`) ON DELETE CASCADE;");
        echo "Migration 015 successfully applied." . PHP_EOL;

    } else {
        // If there are no groups, we can't proceed if there are functions.
        $stmt = $pdo->query("SELECT COUNT(*) FROM `functions`");
        $function_count = $stmt->fetchColumn();
        if ($function_count > 0) {
            die("Migration 015 failed: Cannot create a required association to a BNI group because no BNI groups exist, but functions that need them do exist." . PHP_EOL);
        } else {
            // No functions exist, so we can just add the column and constraint
            $pdo->exec("ALTER TABLE `functions` MODIFY COLUMN `bni_group_id` INT NOT NULL;");
            $pdo->exec("ALTER TABLE `functions` ADD CONSTRAINT `fk_functions_bni_group` FOREIGN KEY (`bni_group_id`) REFERENCES `bni_groups`(`id`) ON DELETE CASCADE;");
            echo "Migration 015 successfully applied (no existing functions to update)." . PHP_EOL;
        }
    }


} catch (PDOException $e) {
    die("Migration 015 failed: " . $e->getMessage() . PHP_EOL);
}
