<?php
require_once __DIR__ . '/../includes/ProxyHelper.php';

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

$parentId = (string)($_GET['parentId'] ?? '');
$geoOrder = (string)($_GET['geoOrder'] ?? '');
$geoGroup = (string)($_GET['geoGroup'] ?? 'officeAddr');
$geoType = (string)($_GET['geoType'] ?? '1');

if ($parentId === '' || $geoOrder === '') {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid request'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$cacheDir = dirname(__DIR__) . '/cache/geo';
if (!is_dir($cacheDir)) {
    @mkdir($cacheDir, 0755, true);
}
$cacheKey = 'geo_' . preg_replace('/[^0-9A-Za-z_-]/', '', $parentId) . '_' . preg_replace('/[^0-9A-Za-z_-]/', '', $geoGroup) . '_' . preg_replace('/[^0-9A-Za-z_-]/', '', $geoOrder) . '_' . preg_replace('/[^0-9A-Za-z_-]/', '', $geoType);
$cacheFile = $cacheDir . '/' . $cacheKey . '.json';
if (is_file($cacheFile) && (time() - (int)@filemtime($cacheFile) < 86400)) {
    echo (string)@file_get_contents($cacheFile);
    exit;
}

$proxy = new ProxyHelper();
$url = "https://bdris.gov.bd/v1/api/geo/parentGeoIdWithGeoGroupAndGeoOrder/{$parentId}?geoGroup={$geoGroup}&geoOrder={$geoOrder}&geoType={$geoType}";
$response = $proxy->fetch($url, 'GET', [], true, 'https://bdris.gov.bd/');

if (($response['status'] ?? 0) === 200) {
    $body = (string)($response['body'] ?? '');
    $json = json_decode($body, true);
    if (json_last_error() === JSON_ERROR_NONE) {
        @file_put_contents($cacheFile, $body);
        echo $body;
        exit;
    }
    http_response_code(502);
    echo json_encode(['error' => 'Invalid JSON response'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

http_response_code(502);
echo json_encode(['error' => 'Failed to fetch from BDRIS', 'status' => (int)($response['status'] ?? 0)], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
