<?php
/**
 * session-auto-capture.php
 * BDRIS লগিনের পরে অটো সেশন ক্যাপচার করার endpoint
 * Browser extension বা bookmarklet এই URL-এ session পাঠাবে
 */

$origin = isset($_SERVER['HTTP_ORIGIN']) ? trim((string)$_SERVER['HTTP_ORIGIN']) : '';
if ($origin !== '' && strtolower($origin) !== 'null') {
    header("Access-Control-Allow-Origin: " . $origin);
    header("Vary: Origin");
    header("Access-Control-Allow-Credentials: true");
} else {
    header("Access-Control-Allow-Origin: *");
}
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, X-CSRF-TOKEN, sender_name, profile");
header("Access-Control-Max-Age: 600");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

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

$baseDir = dirname(__DIR__);

function normCS(string $s): string {
    $s = trim($s);
    if (stripos($s, 'cookie:') === 0) $s = trim(substr($s, 7));
    $s = preg_replace('/[\r\n\t\s]+/', ' ', $s);
    $parts = explode(';', $s);
    $map = [];
    $order = [];
    foreach ($parts as $p) {
        $p = trim($p);
        if ($p === '') continue;
        $eq = strpos($p, '=');
        if ($eq === false || $eq <= 0) continue;
        $k = trim(substr($p, 0, $eq));
        $v = trim(substr($p, $eq + 1));
        if ($k === '') continue;
        $lk = strtolower($k);
        if (!array_key_exists($lk, $map)) $order[] = $lk;
        $map[$lk] = [$k, $v];
    }
    $out = [];
    foreach ($order as $lk) {
        if (!isset($map[$lk])) continue;
        $out[] = $map[$lk][0] . '=' . $map[$lk][1];
    }
    return implode('; ', $out);
}

// Read input
$rawInput = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $rawInput = (string)file_get_contents('php://input');
}

$cookieString = '';
$csrfToken = null;
$senderName = '';
$profile = '';
$extVersion = '';

// Try JSON first
$input = [];
if ($rawInput !== '') {
    $input = json_decode($rawInput, true);
    if (!is_array($input)) $input = [];
}

// Fallback to POST
if (empty($input) && !empty($_POST)) {
    $input = $_POST;
}

// Also check GET
if (isset($_GET['cookies'])) $input['cookie_string'] = $_GET['cookies'];
if (isset($_GET['csrf_token'])) $input['csrf_token'] = $_GET['csrf_token'];
if (isset($_GET['profile'])) $input['profile'] = $_GET['profile'];
if (isset($_GET['name'])) $input['sender_name'] = $_GET['name'];

// Extract cookie string
foreach (['cookie_string', 'cookieString', 'cookies', 'cookie'] as $k) {
    if (!empty($input[$k]) && is_string($input[$k])) {
        $cookieString = $input[$k];
        break;
    }
}

// Extract CSRF token
foreach (['csrf_token', 'csrfToken', 'csrf', '_csrf'] as $k) {
    if (!empty($input[$k]) && is_string($input[$k])) {
        $csrfToken = $input[$k];
        break;
    }
}

// Extract sender name
foreach (['sender_name', 'senderName', 'deviceName', 'name'] as $k) {
    if (!empty($input[$k]) && is_string($input[$k])) {
        $senderName = $input[$k];
        break;
    }
}

// Extract profile
if (!empty($input['profile']) && is_string($input['profile'])) {
    $profile = preg_replace('/[^a-zA-Z0-9_-]/', '', $input['profile']);
}

// Extract ext version
foreach (['ext_version', 'extVersion', 'version'] as $k) {
    if (!empty($input[$k]) && is_string($input[$k])) {
        $extVersion = trim($input[$k]);
        break;
    }
}

// Generate profile from UA if not given
if ($profile === '' || $profile === 'default') {
    $ua = $input['userAgent'] ?? $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
    $profile = 'pc_' . substr(md5($ua), 0, 10);
}

// Normalize cookie string
$cookieString = normCS((string)$cookieString);

if ($cookieString === '' || stripos($cookieString, 'SESSION=') === false) {
    // No valid session cookie
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['CONTENT_TYPE']) && stripos($_SERVER['CONTENT_TYPE'], 'json') !== false) {
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => 'No valid SESSION cookie found']);
        exit;
    }
    // Show friendly page
    header('Content-Type: text/html; charset=utf-8');
    echo '<!DOCTYPE html><html><head><title>Session Capture</title></head><body style="font-family:sans-serif;text-align:center;padding:40px;">
    <h3>❌ কোনো BDRIS SESSION cookie পাওয়া যায়নি</h3>
    <p>অনুগ্রহ করে BDRIS-এ লগইন করুন, তারপর আবার চেষ্টা করুন।</p>
    </body></html>';
    exit;
}

// Get IP
$senderIp = '';
foreach (['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'] as $h) {
    if (!empty($_SERVER[$h])) {
        $ip = trim((string)$_SERVER[$h]);
        if (strpos($ip, ',') !== false) $ip = trim(explode(',', $ip)[0]);
        if (filter_var($ip, FILTER_VALIDATE_IP)) { $senderIp = $ip; break; }
    }
}

$userAgent = $input['userAgent'] ?? $input['user_agent'] ?? $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown Browser';
$acceptLang = $input['acceptLanguage'] ?? $input['accept_language'] ?? $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '';
$now = time();

if ($senderName === '') {
    $senderName = 'BDRIS Auto-Capture (' . substr($profile, 0, 12) . ')';
}

// Save cookie data
$cookieFile = $cookiesDir . "/cookie_data_{$profile}.json";
$prev = null;
if (file_exists($cookieFile)) {
    $prev = json_decode((string)file_get_contents($cookieFile), true);
    if (!is_array($prev)) $prev = null;
}

$data = [
    'cookie_string'      => $cookieString,
    'cookie_string_main' => $cookieString,
    'cookie_string_all'  => $cookieString,
    'csrf_token'         => $csrfToken ?: ($prev['csrf_token'] ?? null),
    'csrf_header'        => 'X-CSRF-TOKEN',
    'user_agent'         => $userAgent,
    'accept_language'    => $acceptLang,
    'sender_name'        => $senderName,
    'sender_ip'          => $senderIp,
    'sender_ts'          => $now,
    'browser_name'       => $profile,
    'updated_at'         => $now,
    'last_status'        => 'active',
    'last_status_checked'=> $now,
    'ext_version'        => $extVersion,
];

$saved = file_put_contents($cookieFile, json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), LOCK_EX);

if ($saved !== false) {
    $activeProfileFile = $cookiesDir . '/active_profile.txt';
    $currentActive = file_exists($activeProfileFile) ? trim((string)@file_get_contents($activeProfileFile)) : '';
    
    // Auto-activate if no active profile, or if THIS is the active profile
    if ($currentActive === '' || $currentActive === $profile) {
        @file_put_contents($activeProfileFile, $profile);
        @file_put_contents($baseDir . '/bdris_cookie.txt', $cookieString);
    }
    
    // Try DB save
    try {
        require_once $baseDir . '/db_connect.php';
        if (isset($pdo) && $pdo) {
            $sql = "INSERT INTO bdris_sessions
                (profile, sender_name, sender_ip, sender_ts, cookie_string, cookie_string_main, cookie_string_all, csrf_token, csrf_header, user_agent, accept_language, updated_at, last_status, last_status_checked, ext_version)
                VALUES
                (:profile, :sender_name, :sender_ip, :sender_ts, :cookie_string, :cookie_string_main, :cookie_string_all, :csrf_token, :csrf_header, :user_agent, :accept_language, :updated_at, :last_status, :last_status_checked, :ext_version)
                ON DUPLICATE KEY UPDATE
                sender_name=VALUES(sender_name), sender_ip=VALUES(sender_ip), sender_ts=VALUES(sender_ts),
                cookie_string=VALUES(cookie_string), cookie_string_main=VALUES(cookie_string_main), cookie_string_all=VALUES(cookie_string_all),
                csrf_token=VALUES(csrf_token), csrf_header=VALUES(csrf_header), user_agent=VALUES(user_agent),
                accept_language=VALUES(accept_language), updated_at=VALUES(updated_at), last_status=VALUES(last_status),
                last_status_checked=VALUES(last_status_checked), ext_version=VALUES(ext_version)";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':profile'             => $profile,
                ':sender_name'         => $senderName,
                ':sender_ip'           => $senderIp,
                ':sender_ts'           => $now,
                ':cookie_string'       => $cookieString,
                ':cookie_string_main'  => $cookieString,
                ':cookie_string_all'   => $cookieString,
                ':csrf_token'          => $csrfToken ?: null,
                ':csrf_header'         => 'X-CSRF-TOKEN',
                ':user_agent'          => $userAgent,
                ':accept_language'     => $acceptLang,
                ':updated_at'          => $now,
                ':last_status'         => 'active',
                ':last_status_checked' => $now,
                ':ext_version'         => $extVersion,
            ]);
        }
    } catch (\Throwable $e) {
        // DB error ignored
    }
    
    // If JSON request, return JSON response
    $ct = $_SERVER['CONTENT_TYPE'] ?? $_SERVER['HTTP_CONTENT_TYPE'] ?? '';
    if (stripos($ct, 'json') !== false || (isset($_SERVER['HTTP_ACCEPT']) && stripos($_SERVER['HTTP_ACCEPT'], 'json') !== false)) {
        header('Content-Type: application/json');
        echo json_encode([
            'status'      => 'success',
            'message'     => 'Session saved and activated successfully',
            'profile'     => $profile,
            'sender_name' => $senderName,
            'has_csrf'    => !empty($csrfToken),
        ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }
    
    // Redirect to session manager
    $host   = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $base   = rtrim(dirname(dirname($_SERVER['PHP_SELF'])), '/');
    $mgr    = $scheme . '://' . $host . $base . '/session-manager.php';
    header('Location: ' . $mgr);
    exit;
    
} else {
    header('Content-Type: application/json');
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Failed to save session file']);
    exit;
}
