<?php
header('Content-Type: application/json');
require_once '../includes/ProxyHelper.php';

$ph = new ProxyHelper();
$cookies = $ph->getCookies();

// Persist set_office_id and set_upazila_id to cached files
if (isset($_GET['set_office_id'])) {
    $officeId = trim((string)$_GET['set_office_id']);
    if ($officeId !== '') {
        $resolvedId = $ph->getIntegerOfficeId($officeId);
        if ($resolvedId !== '') {
            $officeId = $resolvedId;
        }
        // ✅ শুধুমাত্র integer officeId সেভ করো
        if (ctype_digit($officeId)) {
            $officeFile = $ph->getActiveOfficeFile();
            if ($officeFile) {
                @file_put_contents($officeFile, $officeId);
            }
        }
        // encrypted token হলে সেভ করা হবে না
    }
}

if (isset($_GET['set_upazila_id'])) {
    $upazilaId = trim((string)$_GET['set_upazila_id']);
    if ($upazilaId !== '') {
        $upazilaFile = $ph->getActiveUpazilaFile();
        if ($upazilaFile) {
            @file_put_contents($upazilaFile, $upazilaId);
        }
    }
}

$status = [
    'connected' => false,
    'message' => 'Disconnected'
];

if (!empty($cookies)) {
    // Ideally we should ping BDRIS, but for now just check if cookies exist
    // A better check would be to fetch dashboard and check for login
    $status['connected'] = true;
    $status['message'] = 'Connected';
    
    // Optional: Real ping
    // $res = $ph->fetch('https://bdris.gov.bd/admin/', 'GET');
    // if ($res['status'] == 200 && strpos($res['body'], 'Sign In') === false) { ... }
}

echo json_encode($status);
?>