<?php
declare(strict_types=1);

require __DIR__ . '/../../config/bootstrap.php';
use App\Core\Database;

$db = Database::getInstance();

function table_exists($db,string $t):bool{
  $st=$db->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=:t");
  $st->execute([':t'=>$t]);
  return (int)$st->fetchColumn()>0;
}
function col_exists($db,string $t,string $c):bool{
  $st=$db->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=:t AND column_name=:c");
  $st->execute([':t'=>$t,':c'=>$c]);
  return (int)$st->fetchColumn()>0;
}

$defaultOrg=(int)$db->query("SELECT id FROM organizations ORDER BY id ASC LIMIT 1")->fetchColumn();
if($defaultOrg<=0) $defaultOrg=1;

echo "Pack203.6 start (defaultOrg={$defaultOrg})\n";

/* email_queue */
if(table_exists($db,'email_queue')){
  if(!col_exists($db,'email_queue','org_id')){
    $db->exec("ALTER TABLE email_queue ADD COLUMN org_id BIGINT UNSIGNED NULL");
    $db->exec("ALTER TABLE email_queue ADD KEY idx_org_id (org_id)");
    echo "Added email_queue.org_id\n";
  }
  $db->exec("UPDATE email_queue SET org_id={$defaultOrg} WHERE org_id IS NULL");
  echo "Migrated email_queue.org_id\n";
}

/* If you have rbac tables: roles/permissions/role_permissions/user_roles etc.
   We won't force a schema; we only add org_id if tables exist. */
$rbacTables = ['rbac_roles','rbac_permissions','rbac_role_permissions','rbac_user_roles'];
foreach($rbacTables as $t){
  if(!table_exists($db,$t)) continue;
  if(!col_exists($db,$t,'org_id')){
    $db->exec("ALTER TABLE {$t} ADD COLUMN org_id BIGINT UNSIGNED NULL");
    $db->exec("ALTER TABLE {$t} ADD KEY idx_org_id (org_id)");
    echo "Added {$t}.org_id\n";
  }
  $db->exec("UPDATE {$t} SET org_id={$defaultOrg} WHERE org_id IS NULL");
  echo "Migrated {$t}.org_id\n";
}

echo "Pack203.6 done\n";
