<?php
require_once __DIR__ . "/../config.php";

header("Content-Type: application/json");

$q        = trim($_GET['q'] ?? '');
$asset    = $_GET['asset'] ?? 'All';

$whereQ   = $q ? "AND (s.symbol LIKE ? OR s.description LIKE ? OR b.name LIKE ?)" : "";
$whereAst = $asset != "All" ? "AND s.asset_type=?" : "";


$sql = "
SELECT
    s.symbol,
    s.description,
    s.asset_type,
    bs.broker_symbol,
    bs.digits,
    b.name        AS broker
FROM fxh_broker_symbols bs
JOIN fxh_symbols s ON bs.symbol_id = s.id
JOIN fxh_brokers b ON bs.broker_id = b.id
WHERE s.active=1 
AND bs.active=1
{$whereQ}
{$whereAst}
ORDER BY s.symbol ASC
LIMIT 100
";

$stmt = $conn->prepare($sql);

$params = [];
$types  = "";

if($q){
    $like = "%$q%";
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $types.="sss";
}

if($asset != 'All'){
    $params[] = $asset;
    $types.="s";
}

if($params){
    $stmt->bind_param($types, ...$params);
}

$stmt->execute();
$r = $stmt->get_result();

$data = [];

while($row = $r->fetch_assoc()){
    $data[] = $row;
}

echo json_encode([
    "status"=>"ok",
    "results"=>$data
]);
