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

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

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

if (empty($parentId)) {
    echo json_encode(['error' => 'Parent ID missing']);
    exit;
}

if (empty($geoOrder)) {
    echo json_encode(['error' => 'Geo Order missing']);
    exit;
}

// Caching Logic
$cacheDir = __DIR__ . '/cache/geo';
if (!is_dir($cacheDir)) {
    mkdir($cacheDir, 0755, true);
}

$cacheKey = "geo_{$parentId}_{$geoGroup}_{$geoOrder}_{$geoType}";
$cacheFile = "$cacheDir/$cacheKey.json";

// Check if cache exists and is fresh (e.g., 24 hours)
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 86400)) {
    echo file_get_contents($cacheFile);
    exit;
}

$proxy = new ProxyHelper();

// Dynamic URL based on user input
$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'] == 200) {
    // Check if body is valid JSON
    $json = json_decode($response['body'], true);
    if ($json) {
        // Save to cache
        file_put_contents($cacheFile, $response['body']);
        echo $response['body'];
    } else {
        // Fallback or error
        echo json_encode(['error' => 'Invalid JSON response from BDRIS', 'body' => substr($response['body'], 0, 500)]);
    }
} else {
    echo json_encode([
        'error' => 'Failed to fetch from BDRIS',
        'status' => $response['status'],
        'url' => $url
    ]);
}
?>