<?php
// public/import_cookies.php
// CLI/Web helper to import cookies from curl paste or cookie string

header('Content-Type: text/html; charset=utf-8');

require_once 'includes/ProxyHelper.php';
$proxy = new ProxyHelper();

$cookiesDir = __DIR__ . '/cookies';
$activeProfileFile = $cookiesDir . "/active_profile.txt";
$profile = 'browser_8e33dfdf';
if (file_exists($activeProfileFile)) {
    $rawText = file_get_contents($activeProfileFile);
    $rawText = str_replace("\x00", "", $rawText); // Remove null bytes if UTF-16
    $profile = trim(preg_replace('/[^a-zA-Z0-9_-]/', '', $rawText));
}
if ($profile === '') $profile = 'browser_8e33dfdf';

$msg = '';
$msgClass = '';

function bootstrapCsrf($cookieString, $userAgent) {
    $headersBuf = '';
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => 'https://bdris.gov.bd/br/application',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_ENCODING => '',
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT => 12,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_COOKIE => $cookieString,
        CURLOPT_HEADERFUNCTION => static function ($ch, string $header) use (&$headersBuf) {
            $headersBuf .= $header;
            return strlen($header);
        },
        CURLOPT_HTTPHEADER => [
            'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'User-Agent: ' . $userAgent,
            'Referer: https://bdris.gov.bd/br/application',
            'Origin: https://bdris.gov.bd',
            'Connection: close'
        ],
    ]);
    $resp = curl_exec($ch);
    $status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $html = is_string($resp) ? $resp : '';
    $headersRaw = (string)$headersBuf;

    $csrf = null;
    $hdr = 'X-CSRF-TOKEN';

    if (preg_match('/<meta\s+name=["\']_csrf["\']\s+content=["\']([^"\']+)["\']/i', $html, $m2)) {
        $csrf = trim((string)$m2[1]);
    }
    
    if ($headersRaw !== '') {
        if (preg_match_all('/^Set-Cookie:\s*([A-Za-z0-9_\-]+)=([^;\r\n]*)/mi', $headersRaw, $m, PREG_SET_ORDER)) {
            foreach ($m as $row) {
                $name = strtolower(trim((string)($row[1] ?? '')));
                $val = (string)($row[2] ?? '');
                if ($name === 'xsrf-token' || $name === 'csrf-token' || $name === 'x-xsrf-token') {
                    $csrf = rawurldecode($val);
                }
            }
        }
    }

    return [$csrf, $hdr, $status, $html];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' || (php_sapi_name() === 'cli')) {
    if (php_sapi_name() === 'cli') {
        // hardcoded default fallback for CLI test
        $rawInput = "SESSION=YTNlZjRiYjEtZDUyYy00NTZlLWEwM2EtMzA5MDIwMDgyZTFl; TS00000000076=08f04b28f2ab28003033e4eb8ed73ea83a7fe2fdfe3de532d24da4cbf171b72c2fc0f4d09e39221dcd701e7e2cb37e7f084705423109d0001b1aabe455334ff764efd42d94c8c03030c25529c883f57dfb53c8b7ebed3a44b0226de7e9bf1ad56e635d0bd29f4329a7df82bc2065835c91887d28a58c5295ed29af894a5139a8315337b8e5e5f24d94197c4780ce39f3fff02d7ed6e22a9189721b6f6b538c06649cbd96e334b38b62f3090400faa056bdb418c7eecb42426d19e1fe306abf66fc617c4f1d0eef84d787d607f0077ca85e0745bd260ea8c2c8107672f8db03781ef5b827ce675868bc9920bead2b6ce9873d8830b1088c626342ed0c5f5adbd38aa63e079f19475; TSPD_101_DID=08f04b28f2ab28003033e4eb8ed73ea83a7fe2fdfe3de532d24da4cbf171b72c2fc0f4d09e39221dcd701e7e2cb37e7f0847054231063800fde28c4f7f368f7016736457e7d3cb6ab45e01927a5e05cfbe970a89207616d17ccb461718b0d8cdc3ece73943abc2cc4ea073270df52871; srv_id=4457c84807ae18e85f9bc6957cd96afd; TS01290640=019f799b8b2fe7c72c1468b193c006a77b9d147e57e8faa43678c3d7f59224cae8432ff6f18201b4e6fc78eb3c20908a2b9de67a2f; bdris_persist=!hLscroq8JzUU6BRNK1GGjxXIK2kQdWQ2M3RJJckbWJUU0JLbY/axX4d63/smq6ayzVHJfa0HiURkKOQ=; TS0108b707=01ab52a7c0bd250771839cd0092957f4954b023d971edf44209b0daac67c9a0e45c8d0f584a7fd9124a4434e83acf68a9325b9b2e1c9d04f9b174f044aaa2d58f64681d321e965883943dc272d7d397c3cfc771dd942cdc2a16af78f2141dc7bb83c3a34f8e64664258d558128f2cb131d21ca87c7; TSe25a3f03029=08f04b28f2ab2800accf1591d71b69f3a9a062da26c8c40a3109e199d7fdcacbc21a2be05e9c38904af945577d5e0f9c; TS734dcca1027=08f04b28f2ab2000a1618491bec3ceeee89918bc67d45eb1fa0d5aaee910679831ae0fdab00bdd9908d005850c113000528b3a76ba5b0130c3d557a9e605a243e7efb52406c394ac4e523f37ace67b685086403f800803074af47b62839758ce; TS00000000074=08f04b28f2ab2800427d134bf18d9527d00495d2336b99e4224721aff64d3d672ccb5dcc2d10114fbec8f8bd7c18821708b5c280c207d8013ca095e93791a12af39bff3f8c3c63fea0657708c3eef7521630a47a6c72b95bdb735950d5a64def2444d81128becfabdffe2440bdc8e62d89eda5e5b4c29ba12c661f68b3fbf72e739d5ccbea79a70af0a7b8c96be44a8c9260f06cc17e61ff391f27ec1e94c424aae3b6150fdfd45c513f6a7acf32b47328904df33d73e88e36efb1c21f96025651f8080ff50e00d54889aedaee70d52b74e1ea249e8631915d606b924d0345d423eaaaa8ab56916e329e1c2493b457ce27fc2464ae9f6d1e5d25b7adeca5a5183db53323daa047782eccce7a4e02e14d6dcc415acc31c46431767e619c080faf3760a25709b12146152a8ba0722b2959051f69f957428966ae648eeeaeb0ccea2bd9df671b48f1d787938d10cb2aa33ab6a5c3334074ea1582943c8072b5ce5051fdbf3d9a441279c8528f79eb097a276f3dabf296a7a46484aacfc260612e98b27e2ff5664eb5d6e48d38c439ea099f16167f444803651da5747e80527047bcd6836b2101a098665f0b1b65b3c02e9cdda827155064f947ffc0d4823f5a6bdb7eb9280e814418711b961c8b827b3efdd6b158d590d962dd7c692fa366a040cf180cc996915d3a666fa4265bc78a2a3b5a2adfbd4bf74973a53cbafbbaf67f01a2cc9016a966992aa5375e44d29d1beb";
        $userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36 Edg/149.0.0.0";
    } else {
        $rawInput = trim($_POST['cookies'] ?? '');
        $userAgent = trim($_POST['user_agent'] ?? $_SERVER['HTTP_USER_AGENT']);
    }

    $cookieString = $rawInput;
    if (preg_match('/-H\s+[\'"]cookie:\s*([^\'"]+)[\'"]/i', $rawInput, $m)) {
        $cookieString = $m[1];
    } elseif (preg_match('/cookie:\s*([^\r\n]+)/i', $rawInput, $m)) {
        $cookieString = $m[1];
    }
    
    // Clean up
    $cookieString = trim(preg_replace('/[\r\n\t\s]+/', ' ', $cookieString));
    
    if ($cookieString !== '') {
        list($csrf, $hdr, $status, $html) = bootstrapCsrf($cookieString, $userAgent);
        if ($csrf) {
            $cookieFile = $cookiesDir . "/cookie_data_{$profile}.json";
            
            $data = [
                'cookie_string' => $cookieString,
                'cookie_string_main' => $cookieString,
                'cookie_string_all' => $cookieString,
                'extra_headers' => [],
                'csrf_token' => $csrf,
                'csrf_header' => $hdr,
                'user_agent' => $userAgent,
                'accept_language' => 'en-US,en;q=0.9,bn;q=0.8',
                'sender_name' => 'Chrome PC (Manual Import)',
                'sender_ip' => $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1',
                'sender_ts' => time(),
                'sender_tz_offset' => 0,
                'browser_name' => $profile,
                'updated_at' => time(),
                'csrf_bootstrap_at' => time(),
                'last_status' => 'active',
                'last_status_checked' => time(),
                'csrf_bootstrap_http' => $status,
                'csrf_bootstrap_hint' => 'active',
                'cookies_json' => null,
                'ext_version' => ''
            ];
            
            file_put_contents($cookieFile, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
            file_put_contents(dirname($cookiesDir) . "/bdris_cookie.txt", $cookieString);
            
            if (php_sapi_name() === 'cli') {
                echo "CSRF bootstrapped successfully: $csrf\n";
                echo "SUCCESS: Saved active session to cookie file: $cookieFile\n";
                exit;
            } else {
                $msg = "✅ সেশন সফলভাবে আপডেট করা হয়েছে! প্রোফাইল: <strong>$profile</strong>";
                $msgClass = "alert-success";
            }
        } else {
            if (php_sapi_name() === 'cli') {
                echo "ERROR: Failed to bootstrap CSRF. HTTP Status: $status\n";
                exit(1);
            } else {
                $msg = "❌ CSRF টোকেন বুটস্ট্র্যাপ করতে ব্যর্থ হয়েছে! BDRIS সার্ভার থেকে রেসপন্স কোড: $status. সেশন হয়তো নিষ্ক্রিয়।";
                $msgClass = "alert-danger";
            }
        }
    } else {
        if (php_sapi_name() === 'cli') {
            echo "ERROR: No cookie string found\n";
            exit(1);
        } else {
            $msg = "❌ কোনো কুকি স্ট্রিং খুঁজে পাওয়া যায়নি!";
            $msgClass = "alert-danger";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <title>BDRIS Cookie Importer</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card shadow border-0" style="border-radius: 12px;">
                <div class="card-header bg-dark text-white py-3">
                    <h5 class="mb-0"><i class="fas fa-cookie-bite me-2"></i> BDRIS কুকি ইম্পোর্টার</h5>
                </div>
                <div class="card-body p-4">
                    <?php if ($msg): ?>
                        <div class="alert <?= $msgClass ?> alert-dismissible fade show" role="alert">
                            <?= $msg ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>
                    
                    <form method="POST">
                        <div class="mb-3">
                            <label class="form-label fw-bold">কুকি স্ট্রিং অথবা cURL পেস্ট করুন:</label>
                            <textarea name="cookies" class="form-control" rows="8" placeholder="SESSION=... অথবা ব্রাউজার থেকে কপি করা cURL কমান্ড..." required></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">ইউজার এজেন্ট (User Agent) - ঐচ্ছিক:</label>
                            <input type="text" name="user_agent" class="form-control" value="<?= htmlspecialchars($_SERVER['HTTP_USER_AGENT'] ?? '') ?>">
                        </div>
                        <div class="d-grid">
                            <button type="submit" class="btn btn-primary fw-bold"><i class="fas fa-sync me-2"></i> কুকি ও সেশন আপডেট করুন</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>
