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

function sendJson($data, $code = 200) {
    http_response_code((int)$code);
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$cookiesDir = __DIR__ . '/cookies';
if (!is_dir($cookiesDir)) {
    @mkdir($cookiesDir, 0755, true);
}

$activeProfile = '';
$activeProfileFile = $cookiesDir . '/active_profile.txt';
if (is_file($activeProfileFile)) {
    $activeProfile = preg_replace('/[^a-zA-Z0-9_-]/', '', trim((string)@file_get_contents($activeProfileFile)));
}

if ($activeProfile === '') {
    $files = glob($cookiesDir . '/cookie_data_*.json') ?: [];
    usort($files, function($a, $b) { return (int)@filemtime($b) - (int)@filemtime($a); });
    if (!empty($files)) {
        $base = basename((string)$files[0]);
        if (preg_match('/^cookie_data_(.+)\\.json$/', $base, $m)) {
            $activeProfile = preg_replace('/[^a-zA-Z0-9_-]/', '', (string)$m[1]);
        }
    }
    if ($activeProfile !== '') {
        @file_put_contents($activeProfileFile, $activeProfile);
    }
}

if ($activeProfile === '') {
    $activeProfile = 'default';
}

$cookieFile = $cookiesDir . '/cookie_data_' . $activeProfile . '.json';
$data = [];
if (is_file($cookieFile)) {
    $raw = (string)@file_get_contents($cookieFile);
    $decoded = json_decode($raw, true);
    if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
        $data = $decoded;
    }
}

$method = strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET'));
if ($method === 'GET') {
    $geoGroupGet = preg_replace('/[^a-zA-Z0-9_-]/', '', (string)($_GET['geoGroup'] ?? 'officeAddr'));
    $upazilaIdGet = preg_replace('/[^0-9]/', '', (string)($_GET['upazilaId'] ?? ''));
    $token = '';
    if (isset($data['uno_office_tokens']) && is_array($data['uno_office_tokens'])) {
        $g = $data['uno_office_tokens'][$geoGroupGet] ?? null;
        if (is_array($g)) {
            if ($upazilaIdGet !== '' && isset($g[$upazilaIdGet])) $token = (string)$g[$upazilaIdGet];
            if ($token === '' && isset($g['default'])) $token = (string)$g['default'];
        }
    }
    sendJson([
        'ok' => true,
        'profile' => $activeProfile,
        'csrfToken' => (string)($data['csrf_token'] ?? ''),
        'token' => $token
    ], 200);
}

if ($method !== 'POST') {
    sendJson(['ok' => false, 'error' => 'POST only'], 405);
}

$token = trim((string)($_POST['token'] ?? ''));
$csrfToken = trim((string)($_POST['csrfToken'] ?? ''));
$geoGroup = preg_replace('/[^a-zA-Z0-9_-]/', '', (string)($_POST['geoGroup'] ?? ''));
$upazilaId = preg_replace('/[^0-9]/', '', (string)($_POST['upazilaId'] ?? ''));

$changed = false;

if ($csrfToken !== '') {
    $data['csrf_token'] = $csrfToken;
    $data['updated_at'] = time();
    $data['last_status'] = 'active';
    $changed = true;

    $sessionJson = dirname(__DIR__) . '/session.json';
    $sj = [];
    if (is_file($sessionJson)) {
        $r = (string)@file_get_contents($sessionJson);
        $d = json_decode($r, true);
        if (json_last_error() === JSON_ERROR_NONE && is_array($d)) $sj = $d;
    }
    $sj['csrf'] = $csrfToken;
    @file_put_contents($sessionJson, json_encode($sj, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
}

if ($token !== '') {
    if ($geoGroup === '') $geoGroup = 'officeAddr';
    if (!isset($data['uno_office_tokens']) || !is_array($data['uno_office_tokens'])) {
        $data['uno_office_tokens'] = [];
    }
    if (!isset($data['uno_office_tokens'][$geoGroup]) || !is_array($data['uno_office_tokens'][$geoGroup])) {
        $data['uno_office_tokens'][$geoGroup] = [];
    }
    if ($upazilaId !== '') {
        $data['uno_office_tokens'][$geoGroup][$upazilaId] = $token;
    }
    $data['uno_office_tokens'][$geoGroup]['default'] = $token;
    $data['updated_at'] = time();
    $data['last_status'] = 'active';
    $changed = true;
}

if ($changed) {
    @file_put_contents($cookieFile, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
}

sendJson([
    'ok' => true,
    'profile' => $activeProfile,
    'saved' => [
        'token' => ($token !== ''),
        'csrfToken' => ($csrfToken !== '')
    ]
], 200);
