<?php
require "api/config/database.php";
try {
    $db = Database::connect();
    
    // Find the foreign key constraint name for havala_id
    $stmt = $db->query("
        SELECT CONSTRAINT_NAME 
        FROM information_schema.KEY_COLUMN_USAGE 
        WHERE TABLE_SCHEMA = 'naveed_trader_db' 
          AND TABLE_NAME = 'sale_master' 
          AND COLUMN_NAME = 'havala_id' 
          AND REFERENCED_TABLE_NAME IS NOT NULL
    ");
    $fkName = $stmt->fetchColumn();
    
    if ($fkName) {
        $db->exec("ALTER TABLE sale_master DROP FOREIGN KEY {$fkName}");
        echo "Dropped FK {$fkName}. ";
    }
    
    // Change column type
    $db->exec("ALTER TABLE sale_master CHANGE havala_id havala_name VARCHAR(255) DEFAULT NULL COMMENT 'Open text reference/guarantor'");
    echo "Column changed successfully.";
} catch (Throwable $e) {
    echo "ERROR: " . $e->getMessage();
}
