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

try {
    $action = isset($_GET['action']) ? strtolower(trim($_GET['action'])) : '';
    $finage = getFinageAPI();
    if ($action === 'prices') {
        $symbols = isset($_GET['symbols']) ? explode(',', $_GET['symbols']) : [];
        $symbols = array_values(array_filter(array_map('trim', $symbols)));
        if (!count($symbols)) { echo json_encode(['success'=>false,'message'=>'symbols required']); exit; }
        $data = $finage->getMultiplePrices($symbols);
        echo json_encode(['success'=>true,'data'=>$data]);
        exit;
    }
    if ($action === 'snapshot') {
        $symbols = isset($_GET['symbols']) ? explode(',', $_GET['symbols']) : [];
        $symbols = array_values(array_filter(array_map('trim', $symbols)));
        if (!count($symbols)) { echo json_encode(['success'=>false,'message'=>'symbols required']); exit; }
        $data = $finage->getStockSnapshot($symbols);
        echo json_encode(['success'=>true,'data'=>$data]);
        exit;
    }
    if ($action === 'intraday') {
        $symbol = isset($_GET['symbol']) ? strtoupper(trim($_GET['symbol'])) : '';
        $tf = isset($_GET['tf']) ? strtolower(trim($_GET['tf'])) : '1min';
        $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 200;
        if (!$symbol) { echo json_encode(['success'=>false,'message'=>'symbol required']); exit; }
        $data = $finage->getIntradayData($symbol, $tf, $limit, 'forex');
        echo json_encode(['success'=>true,'data'=>$data]);
        exit;
    }
    echo json_encode(['success'=>false,'message'=>'unknown action']);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}
?>
