<?php
/**
 * Fix trading_accounts schema: ensure required columns exist in current DB
 */
header('Content-Type: application/json');
require_once __DIR__ . '/../../../database/connection.php';

try {
    if (!$pdo) throw new Exception('Conexión de BD no disponible');

    $dbName = $pdo->query('SELECT DATABASE()')->fetchColumn();
    if (!$dbName) throw new Exception('No se pudo determinar el nombre de la BD');

    // Crear tabla si no existe con columnas necesarias
    $pdo->exec("CREATE TABLE IF NOT EXISTS trading_accounts (
        id INT AUTO_INCREMENT PRIMARY KEY,
        client_id INT NOT NULL,
        account_number VARCHAR(32) NOT NULL UNIQUE,
        account_type VARCHAR(32) NOT NULL DEFAULT 'standard',
        currency VARCHAR(8) NOT NULL DEFAULT 'USD',
        leverage INT NOT NULL DEFAULT 100,
        balance DECIMAL(18,2) NOT NULL DEFAULT 0.00,
        equity DECIMAL(18,2) NOT NULL DEFAULT 0.00,
        margin DECIMAL(18,2) NOT NULL DEFAULT 0.00,
        free_margin DECIMAL(18,2) NOT NULL DEFAULT 0.00,
        margin_level DECIMAL(9,2) NOT NULL DEFAULT 0.00,
        status VARCHAR(16) NOT NULL DEFAULT 'active',
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME NULL,
        INDEX idx_ta_client (client_id),
        INDEX idx_ta_status (status)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    // Comprobar columnas existentes y agregar faltantes
    $colsStmt = $pdo->prepare("SELECT COLUMN_NAME FROM information_schema.columns WHERE table_schema = ? AND table_name = 'trading_accounts'");
    $colsStmt->execute([$dbName]);
    $existing = array_map('strtolower', array_column($colsStmt->fetchAll(PDO::FETCH_ASSOC), 'COLUMN_NAME'));

    $required = [
        'margin' => "ALTER TABLE trading_accounts ADD COLUMN margin DECIMAL(18,2) NOT NULL DEFAULT 0.00",
        'equity' => "ALTER TABLE trading_accounts ADD COLUMN equity DECIMAL(18,2) NOT NULL DEFAULT 0.00",
        'free_margin' => "ALTER TABLE trading_accounts ADD COLUMN free_margin DECIMAL(18,2) NOT NULL DEFAULT 0.00",
        'margin_level' => "ALTER TABLE trading_accounts ADD COLUMN margin_level DECIMAL(9,2) NOT NULL DEFAULT 0.00"
    ];

    $added = [];
    foreach ($required as $col => $ddl) {
        if (!in_array($col, $existing, true)) {
            try { $pdo->exec($ddl); $added[] = $col; } catch (Throwable $e) {}
        }
    }

    echo json_encode(['success' => true, 'database' => $dbName, 'added_columns' => $added]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>
