<?php
/**
 * cookie-inject.php
 * BDRIS-এ লগিন করে F12 > Network > যেকোনো request > Cookie হেডার কপি করে
 * এই পেজের form-এ paste করুন।
 * সার্ভারে cookie সেভ হবে এবং যেকোনো ইউনিয়ন সার্চ করা যাবে।
 */
require_once __DIR__ . '/includes/ProxyHelper.php';

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

$method = $_SERVER['REQUEST_METHOD'];

// POST: receive cookie
if ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    if (!$input) $input = $_POST;

    $cookie = trim((string)($input['cookie'] ?? $input['cookie_string'] ?? $input['cookies'] ?? ''));
    $csrf   = trim((string)($input['csrf'] ?? $input['csrf_token'] ?? ''));

    if ($cookie === '') {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'Cookie string is required']);
        exit;
    }

    $ph = new ProxyHelper();
    $ok = $ph->saveCookies($cookie, [], $csrf ?: null);

    // Also write to bdris_cookie.txt directly
    $cookiesDir = dirname(__DIR__) . '/cookies';
    if (!is_dir($cookiesDir)) @mkdir($cookiesDir, 0755, true);
    @file_put_contents(__DIR__ . '/bdris_cookie.txt', $cookie);
    @file_put_contents($cookiesDir . '/raw_cookie.txt', $cookie);

    echo json_encode([
        'ok'      => $ok,
        'message' => $ok ? 'Session saved! Any union search now works.' : 'Save failed - check permissions',
        'length'  => strlen($cookie),
    ]);
    exit;
}

// GET: Show instructions + quick-test
$ph = new ProxyHelper();
$currentCookie = $ph->getCookies();
$hasSession = $currentCookie !== '' && stripos($currentCookie, 'SESSION=') !== false;

// Test current session
$testResult = null;
if ($hasSession && isset($_GET['test'])) {
    $ubrn = preg_replace('/\D/', '', (string)($_GET['test']));
    if (strlen($ubrn) >= 9) {
        $r = $ph->fetch('https://bdris.gov.bd/api/br/info/ubrn/' . $ubrn, 'GET', [], false, 'https://bdris.gov.bd/');
        $testResult = [
            'status' => $r['status'] ?? 0,
            'body'   => substr($r['body'] ?? '', 0, 500),
        ];
    }
}

echo json_encode([
    'ok'           => true,
    'has_session'  => $hasSession,
    'cookie_len'   => strlen($currentCookie),
    'cookie_preview' => $hasSession ? substr($currentCookie, 0, 80) . '...' : '',
    'test'         => $testResult,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
