<?php
// Idempotent migration to add account_currency columns
header('Content-Type: application/json');
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

define('TONSUI_LOADED', true);
require_once __DIR__ . '/session_init.php';
requireAdmin(true);
require_once __DIR__ . '/db.php';

try {
  $actions = [];

  // Add users.account_currency if missing
  try {
    $c = $pdo->query("SHOW COLUMNS FROM users LIKE 'account_currency'");
    if (!$c || $c->rowCount() === 0) {
      $pdo->exec("ALTER TABLE users ADD COLUMN account_currency VARCHAR(10) DEFAULT 'EUR' AFTER account_number");
      $actions[] = 'Added users.account_currency';
    } else {
      $actions[] = 'users.account_currency already exists';
    }
  } catch (Throwable $e) {
    $actions[] = 'users.account_currency check/add failed: ' . $e->getMessage();
  }

  // Ensure user_profiles exists
  try {
    $t = $pdo->query("SHOW TABLES LIKE 'user_profiles'");
    if (!$t || $t->rowCount() === 0) {
      $pdo->exec("CREATE TABLE IF NOT EXISTS user_profiles (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        account_currency VARCHAR(10) NULL,
        account_type VARCHAR(100) NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX (user_id)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
      $actions[] = 'Created user_profiles with account_currency (minimal)';
    }
  } catch (Throwable $e) {
    $actions[] = 'user_profiles create check failed: ' . $e->getMessage();
  }

  // Add user_profiles.account_currency if missing
  try {
    $c = $pdo->query("SHOW COLUMNS FROM user_profiles LIKE 'account_currency'");
    if (!$c || $c->rowCount() === 0) {
      $pdo->exec("ALTER TABLE user_profiles ADD COLUMN account_currency VARCHAR(10) NULL AFTER gender");
      $actions[] = 'Added user_profiles.account_currency';
    } else {
      $actions[] = 'user_profiles.account_currency already exists';
    }
  } catch (Throwable $e) {
    // Retry add after last column if gender doesn't exist
    try {
      $pdo->exec("ALTER TABLE user_profiles ADD COLUMN account_currency VARCHAR(10) NULL");
      $actions[] = 'Added user_profiles.account_currency (generic)';
    } catch (Throwable $e2) {
      $actions[] = 'user_profiles.account_currency add failed: ' . $e2->getMessage();
    }
  }

  echo json_encode(['success' => true, 'actions' => $actions]);
} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
