<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../../database/connection.php';

$stocks = [
    ['AAPL','Apple Inc.'],
    ['MSFT','Microsoft Corp.'],
    ['AMZN','Amazon.com Inc.'],
    ['GOOGL','Alphabet Inc. (Class A)'],
    ['META','Meta Platforms Inc.'],
    ['TSLA','Tesla Inc.'],
    ['NVDA','NVIDIA Corp.'],
    ['JPM','JPMorgan Chase & Co.'],
    ['V','Visa Inc.'],
    ['NFLX','Netflix Inc.']
];

try {
    if (!$pdo) throw new Exception('Conexión de BD no disponible');
    $inserted = [];
    foreach ($stocks as [$symbol,$name]) {
        $stmt = $pdo->prepare("SELECT id FROM trading_instruments WHERE symbol = ? LIMIT 1");
        $stmt->execute([$symbol]);
        $exists = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($exists) {
            $upd = $pdo->prepare("UPDATE trading_instruments SET name = ?, category = 'stocks', base_currency = ?, quote_currency = 'USD', pip_size = 0.01, min_volume = 1, max_volume = 10000, volume_step = 1, contract_size = 1, margin_rate = 1.0, is_active = 1, updated_at = NOW() WHERE id = ?");
            $upd->execute([$name, $symbol, $exists['id']]);
            $inserted[] = ['symbol'=>$symbol,'status'=>'updated'];
        } else {
            $ins = $pdo->prepare("INSERT INTO trading_instruments (symbol, name, category, base_currency, quote_currency, pip_size, min_volume, max_volume, volume_step, contract_size, margin_rate, is_active, updated_at) VALUES (?, ?, 'stocks', ?, 'USD', 0.01, 1, 10000, 1, 1, 1.0, 1, NOW())");
            $ins->execute([$symbol, $name, $symbol]);
            $inserted[] = ['symbol'=>$symbol,'status'=>'inserted'];
        }
    }
    echo json_encode(['success'=>true,'inserted'=>$inserted]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success'=>false,'error'=>$e->getMessage()]);
}
?>
