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

$query = isset($_GET['query']) ? trim($_GET['query']) : '';

if (empty($query)) {
    echo json_encode(['status' => 'error', 'message' => 'Query is required.']);
    exit;
}

$jsonFile = $_SERVER['DOCUMENT_ROOT'] . '/opendart/data/corp_codes.json';

if (!file_exists($jsonFile)) {
    echo json_encode(['status' => 'error', 'message' => 'Data not synced. Please click "Sync Data" first.']);
    exit;
}

$jsonData = @file_get_contents($jsonFile);
if ($jsonData === false) {
    echo json_encode(['status' => 'error', 'message' => 'Failed to read data file. Check file permissions.']);
    exit;
}

$corpList = json_decode($jsonData, true);

if ($corpList === null) {
    $jsonError = json_last_error_msg();
    echo json_encode(['status' => 'error', 'message' => 'Invalid data file. JSON Error: ' . $jsonError]);
    exit;
}

if (!is_array($corpList)) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid data format. Expected array.']);
    exit;
}

$results = [];
$count = 0;
$limit = 50; // Limit results

foreach ($corpList as $corp) {
    // Simple case-insensitive search
    if (stripos($corp['corp_name'], $query) !== false) {
        $results[] = $corp;
        $count++;
        if ($count >= $limit) break;
    }
}

echo json_encode(['status' => 'success', 'results' => $results]);
?>
