<?php
declare(strict_types=1);

require_once __DIR__ . '/../../engine/api-handling/fmp_client.php';

header('Content-Type: application/json; charset=utf-8');

$sector = trim($_GET['sector'] ?? '');
if ($sector===''){ http_response_code(400); echo json_encode(['error'=>'sector required']); exit; }

$resp = fmp_multi([
  's' => ['key'=>'stock_screener','query'=>['sector'=>$sector,'isEtf'=>'false','limit'=>5000]]
], 20);

$list = is_array($resp['s'] ?? null) ? $resp['s'] : [];
$inds=$ctrs=$exchs=[]; $items=[];
foreach ($list as $r){
  $ind = $r['industry'] ?? null;           if ($ind) $inds[$ind]=true;
  $ctr = $r['country'] ?? ($r['countryName'] ?? null); if ($ctr) $ctrs[$ctr]=true;
  $ex  = $r['exchangeShortName'] ?? ($r['exchange'] ?? null); if ($ex) $exchs[$ex]=true;

  $items[] = [
	'symbol'   => $r['symbol'] ?? null,
	'industry' => $ind,
	'country'  => $ctr,
	'exchange' => $ex,
  ];
}
$industries = array_values(array_keys($inds)); sort($industries, SORT_NATURAL|SORT_FLAG_CASE);
$countries  = array_values(array_keys($ctrs)); sort($countries,  SORT_NATURAL|SORT_FLAG_CASE);
$exchanges  = array_values(array_keys($exchs));sort($exchanges,  SORT_NATURAL|SORT_FLAG_CASE);

echo json_encode([
  'sector'     => $sector,
  'counts'     => ['screener'=>count($list)],
  'industries' => $industries,
  'countries'  => $countries,
  'exchanges'  => $exchanges,
  'items_meta' => $items
], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);
