<?php
const FMP_BASE_URL = 'https://financialmodelingprep.com';

const FMP_ENDPOINTS = [
	'profile'                 		=> '/api/v3/profile/{symbol}',
	'metrics'                 		=> '/api/v3/key-metrics/{symbol}?limit=1',
	'income_statement'        		=> '/api/v3/income-statement/{symbol}',          		// ?period=annual|quarter
	'key_metrics_ttm'         		=> '/api/v3/key-metrics-ttm/{symbol}',
	'historical_price_full'   		=> '/api/v3/historical-price-full/{symbol}',     		// ?from=YYYY-MM-DD&to=...&serietype=line
	'quote'                   		=> '/api/v3/quote/{symbol}',
	'ratios'                  		=> '/api/v3/ratios/{symbol}?limit=1',
	'ratios_ttm'              		=> '/api/v3/ratios-ttm/{symbol}',
	'financial_growth'        		=> '/api/v3/financial-growth/{symbol}',
	'key_metrics'             		=> '/api/v3/key-metrics/{symbol}',               		// ?period=annual|quarter&limit=40
	'ratios'                  		=> '/api/v3/ratios/{symbol}',
	'analyst_recommendations' 		=> '/api/v3/analyst-stock-recommendations/{symbol}', 	// Buy/Hold/Sell Historie
	'price_target'            		=> '/api/v3/price-target/{symbol}',                  	// einzelne Price Target Einträge
	'price_target_summary'    		=> '/api/v3/price-target-summary/{symbol}',          	// avg/high/low
	'analyst_estimates'       		=> '/stable/analyst-estimates',                      	// ?symbol=&period=annual|quarter
	'rating' 						=> '/api/v3/rating/{symbol}', 
	'historical_rating' 			=> '/api/v3/historical-rating/{symbol}',
	'financial_scores'              => '/api/v3/financial-scores/{symbol}',            		// Altman Z, Piotroski F
	'owner_earnings'                => '/api/v3/owner-earnings/{symbol}',              		// Owner Earnings, je Aktie möglich
	'enterprise_values'             => '/api/v3/enterprise-values/{symbol}',           		// EV Historie
	'income_statement_growth'       => '/api/v3/income-statement-growth/{symbol}',     		// Detail-Wachstum GuV
	'balance_sheet_growth'          => '/api/v3/balance-sheet-statement-growth/{symbol}',
	'cashflow_growth'               => '/api/v3/cash-flow-statement-growth/{symbol}',
	'revenue_product_segmentation'  => '/api/v3/revenue-product-segmentation/{symbol}',
	'revenue_geo_segmentation'      => '/api/v3/revenue-geographic-segmentation/{symbol}',
	'stock_dividend' 				=> '/api/v3/historical-price-full/stock_dividend/{symbol}',
	'quote_short'    				=> '/api/v3/quote-short/{symbol}',
	'historical_stock_dividend' 	=> '/api/v3/historical-price-full/stock_dividend/{symbol}',
	'insider_trading' 				=> '/api/v4/insider-trading',
	'stock_news' 					=> '/api/v3/stock_news?tickers={symbol}&limit=50',
	'stock_market_gainers' 			=> '/api/v3/stock_market/gainers',
	'stock_market_losers'  			=> '/api/v3/stock_market/losers',
	'stock_market_actives' 			=> '/api/v3/stock_market/actives',
	'stock_screener' 				=> '/api/v3/stock-screener', 
	'earnings_company'           	=> '/stable/earnings-company',
	'earning_calendar_symbol' 		=> '/api/v3/historical/earning_calendar/{symbol}?limit={limit}',
	'earning_calendar' 				=> '/api/v3/earning_calendar/{symbol}?limit={limit}',
	'earnings' 						=> '/stable/earnings?symbol={symbol}',							// ?sector=&limit=&exchange=&country=
	'sectors_list'    				=> '/api/v3/sectors-list',
	'industries_list' 				=> '/api/v3/industries-list',
	'exchanges_list'  				=> '/api/v3/exchanges-list',
	'institutional_holders' 		=> '/api/v3/institutional-holder/{symbol}',
];

function fmp_fill_path(string $template, array $vars): string {
	foreach ($vars as $k => $v) {
		$template = str_replace('{'.$k.'}', rawurlencode((string)$v), $template);
	}
	return $template;
}

function fmp_build_url(string $key, array $vars = [], array $query = []): string {
	global $FmpApiKey;
	if (!isset(FMP_ENDPOINTS[$key])) {
		throw new InvalidArgumentException("Unknown FMP endpoint key: {$key}");
	}

	$path = fmp_fill_path(FMP_ENDPOINTS[$key], $vars);
	$templateQuery = [];
	$parts = parse_url($path);
	if (!empty($parts['query'])) {
		parse_str($parts['query'], $templateQuery);
		$path = str_replace('?'.$parts['query'], '', $path);
	}

	$finalQuery = array_filter(array_merge($templateQuery, $query, ['apikey' => $FmpApiKey]), fn($v) => $v !== null && $v !== '');
	$qs = http_build_query($finalQuery);

	return rtrim(FMP_BASE_URL, '/') . $path . ($qs ? '?' . $qs : '');
}