<?php
header("Content-Type: application/json; charset=UTF-8");

$category = strtolower(trim($_GET['category'] ?? ''));
$query = strtolower(trim($_GET['query'] ?? ''));

// Load allowed categories (as array)
$categoriesFile = "data/categories.json";
if (!file_exists($categoriesFile)) {
    echo json_encode(["error" => "Categories file missing"]);
    exit;
}

$allowedCategories = json_decode(file_get_contents($categoriesFile), true);

// Check if category is valid
if (!$category || !in_array($category, $allowedCategories)) {
    echo json_encode(["error" => "Invalid or missing category"]);
    exit;
}

// Load data file
$jsonPath = "data/{$category}.json";
if (!file_exists($jsonPath)) {
    echo json_encode(["error" => "Data file not found for this category"]);
    exit;
}

$data = json_decode(file_get_contents($jsonPath), true);
$dataList = $data[$category] ?? [];

if ($query) {
    $filtered = array_filter($dataList, function ($item) use ($query) {
        foreach (['name', 'specialization', 'hospital', 'area', 'phone'] as $field) {
            if (isset($item[$field]) && mb_stripos($item[$field], $query) !== false) {
                return true;
            }
        }
        return false;
    });
    $result = array_values($filtered);
} else {
    $result = $dataList;
}

echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
