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

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

$unionGeoId = $_GET['geoId'] ?? '';
$geoGroup = $_GET['geoGroup'] ?? 'officeAddr';
$geoOrder = $_GET['geoOrder'] ?? '4';
$geoType = $_GET['geoType'] ?? '5';

if (empty($unionGeoId)) {
    echo json_encode(['error' => 'Union Geo ID missing']);
    exit;
}

$proxy = new ProxyHelper();

// URL structure based on user input
$url = "https://bdris.gov.bd/api/office/find-office-geo-projection-by-geo-id/{$unionGeoId}?geoGroup={$geoGroup}&geoOrder={$geoOrder}&geoType={$geoType}";

$headers = [
    'X-Requested-With: XMLHttpRequest',
    'Accept: application/json, text/javascript, */*; q=0.01'
];

$response = $proxy->fetch($url, 'GET', [], true, 'https://bdris.gov.bd/admin/br/applications', $headers);

if ($response['status'] == 200) {
    $body = $response['body'];
    $data = json_decode($body, true);
    $officeVal = '';
    if (isset($data['geoObject'])) {
        $officeVal = isset($data['geoObject']['officeId']) ? (string)$data['geoObject']['officeId'] : (isset($data['geoObject']['id']) ? (string)$data['geoObject']['id'] : '');
    } elseif (isset($data['officeId'])) {
        $officeVal = (string)$data['officeId'];
    }
    if ($officeVal !== '') {
        $dir = __DIR__ . '/cookies';
        if (!is_dir($dir)) {
            @mkdir($dir, 0777, true);
        }
        @file_put_contents($proxy->getActiveOfficeFile(), $officeVal);
    }
    echo $body;
} else {
    echo json_encode([
        'error' => 'Failed to fetch office info',
        'status' => $response['status'],
        'url' => $url
    ]);
}
?>