<?php
declare(strict_types=1);

require __DIR__ . '/../../config/bootstrap.php';

use App\Core\Database;

$db = Database::getInstance();

function colInfo(PDO $db, string $table, string $col): ?array {
  $st = $db->prepare("
    SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_TYPE
    FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = :t
      AND COLUMN_NAME = :c
    LIMIT 1
  ");
  $st->execute([':t'=>$table, ':c'=>$col]);
  $r = $st->fetch(PDO::FETCH_ASSOC);
  return $r ?: null;
}

function makeNullable(PDO $db, string $table, string $col): void {
  $info = colInfo($db,$table,$col);
  if(!$info){ echo "SKIP $table.$col (missing)\n"; return; }

  if (($info['IS_NULLABLE'] ?? '') === 'YES') {
    echo "OK   $table.$col already NULLABLE\n";
    return;
  }

  $ctype = (string)($info['COLUMN_TYPE'] ?? 'varchar(255)');
  // Make nullable with NULL default
  $sql = "ALTER TABLE `$table` MODIFY `$col` $ctype NULL DEFAULT NULL";
  $db->exec($sql);
  echo "FIX  $table.$col => NULL DEFAULT NULL ($ctype)\n";
}

$targets = [
  'attendance_registrations',
  'committee_members',
  'conference_committees',
  'registration_submissions',
];

foreach($targets as $t){
  makeNullable($db,$t,'full_name_en');
  // Some installs also have full_name_ar; if exists, make it nullable too
  makeNullable($db,$t,'full_name_ar');
}

echo "DONE Pack205.7Y\n";
