<?php
require_once __DIR__ . '/../../../database/connection.php';
header('Content-Type: application/json');
function getAcc(){
    if (php_sapi_name()==='cli') { global $argv; return $argv[1]??null; }
    return $_GET['account_number']??null;
}
try{
    if(!$pdo) throw new Exception('Sin conexión');
    $accNum = trim((string)getAcc());
    if(!$accNum) throw new Exception('account_number requerido');
    $src = null;
    $s = $pdo->prepare("SELECT * FROM client_accounts WHERE account_number=? LIMIT 1");
    $s->execute([$accNum]);
    $src = $s->fetch(PDO::FETCH_ASSOC);
    if(!$src) throw new Exception('Cuenta origen no encontrada en client_accounts');
    $client_id = $src['client_id'] ?? null;
    $currency = $src['currency'] ?? 'USD';
    $leverage = isset($src['leverage']) ? (int)$src['leverage'] : 100;
    $balance = isset($src['balance']) ? (float)$src['balance'] : 0.0;
    $equity = isset($src['equity']) ? (float)$src['equity'] : $balance;
    $margin = isset($src['margin']) ? (float)$src['margin'] : 0.0;
    $free_margin = isset($src['free_margin']) ? (float)$src['free_margin'] : max(0.0, $equity - $margin);
    $status = $src['status'] ?? 'active';
    $ml = $margin>0 ? (($equity/$margin)*100.0) : 0.0;
    $ex = $pdo->prepare("SELECT id FROM trading_accounts WHERE account_number=? LIMIT 1");
    $ex->execute([$accNum]);
    $row = $ex->fetch(PDO::FETCH_ASSOC);
    if($row){
        $u = $pdo->prepare("UPDATE trading_accounts SET client_id=?, currency=?, leverage=?, balance=?, equity=?, margin=?, free_margin=?, margin_level=?, status=?, updated_at=NOW() WHERE account_number=?");
        $u->execute([$client_id, $currency, $leverage, $balance, $equity, $margin, $free_margin, $ml, $status, $accNum]);
        $id = $row['id'];
    } else {
        $i = $pdo->prepare("INSERT INTO trading_accounts (client_id, account_number, account_type, currency, leverage, balance, equity, margin, free_margin, margin_level, status, created_at) VALUES (?, ?, 'standard', ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
        $i->execute([$client_id, $accNum, $currency, $leverage, $balance, $equity, $margin, $free_margin, $ml, $status]);
        $id = $pdo->lastInsertId();
    }
    echo json_encode(['success'=>true,'account'=>[
        'id'=>$id,'client_id'=>$client_id,'account_number'=>$accNum,'currency'=>$currency,'leverage'=>$leverage,
        'balance'=>$balance,'equity'=>$equity,'margin'=>$margin,'free_margin'=>$free_margin,'margin_level'=>$ml,'status'=>$status
    ]]);
}catch(Exception $e){ http_response_code(400); echo json_encode(['success'=>false,'error'=>$e->getMessage()]); }
?>
