<?php
// Enable pre-formatting for browser view
echo "<pre style='background:#000; color:#0f0; padding:15px; font-family:monospace;'>";

require_once __DIR__ . '/includes/ProxyHelper.php';

// Set up the environment to mimic a web request if needed
$activeProfileFile = __DIR__ . '/cookies/active_profile.txt';
$profile = 'default';
if (file_exists($activeProfileFile)) {
    $profile = trim(file_get_contents($activeProfileFile));
}
$_SESSION['cookie_profile'] = $profile;

echo "Starting Automated System Verification...\n";
echo "========================================\n";

$proxy = new ProxyHelper();

// 1. Check Cookie File
$cookieFile = __DIR__ . '/cookies/cookie_data_' . $profile . '.json';
if (file_exists($cookieFile)) {
    echo "[PASS] Cookie file found: " . basename($cookieFile) . "\n";
    $data = json_decode(file_get_contents($cookieFile), true);
    echo "       User Agent: " . substr($data['user_agent'] ?? 'N/A', 0, 50) . "...\n";
} else {
    echo "[FAIL] Cookie file missing: " . basename($cookieFile) . "!\n";
    exit(1);
}

// 2. Check Session/Login Status
echo "\nTesting Connection to BDRIS...\n";

// Check Admin Dashboard
echo "   [1] Checking Admin Access (https://bdris.gov.bd/admin/dashboard)...\n";
$respAdmin = $proxy->fetch('https://bdris.gov.bd/admin/dashboard', 'GET', [], false, 'https://bdris.gov.bd/login');
$isAdmin = false;
if ($respAdmin['status'] == 200) {
    preg_match('/<title>(.*?)<\/title>/', $respAdmin['body'], $matches);
    $title = $matches[1] ?? 'No Title';
    if (stripos($title, 'Login') === false && stripos($respAdmin['body'], 'login-page') === false) {
        echo "       [PASS] Admin Session Active. Title: $title\n";
        $isAdmin = true;
    } else {
        echo "       [FAIL] Redirected to Login. Title: $title\n";
    }
} else {
    echo "       [FAIL] HTTP " . $respAdmin['status'] . "\n";
}

// Check Public Application
echo "   [2] Checking Public Access (https://bdris.gov.bd/br/application)...\n";
$url = 'https://bdris.gov.bd/br/application';
$response = $proxy->fetch($url, 'GET', [], false, 'https://bdris.gov.bd/');

echo "       HTTP Status: " . $response['status'] . "\n";
$body = $response['body'] ?? '';

if ($response['status'] == 200 || $response['status'] == 302) {
    if (stripos($body, 'login-page') !== false || stripos($body, '<title>Login</title>') !== false) {
        echo "       [FAIL] Public Session is EXPIRED or Invalid (Redirected to Login).\n";
    } else {
        echo "       [PASS] Public Page Accessible.\n";
    }
} else {
    echo "       [FAIL] Connection Error (HTTP " . $response['status'] . ")\n";
}

if (!$isAdmin) {
    echo "\n[WARNING] You do not seem to have an Active ADMIN session.\n";
    echo "The Search API you are trying to use (/admin/...) likely requires Admin access.\n";
    echo "Please update the 'cookie_data_{$profile}.json' with a fresh ADMIN session.\n";
}

// 3. Test Encrypted Search
echo "\nTesting Encrypted Search functionality...\n";
// The data provided by user
$encryptedData = 'IMnsVsVRrC391a26Ye0R9qmpB1um-pmCq3aemQWs5-Q_RU30D9mOJOgufiscFRqhZa8BLoBqaEsRvb6X3_yuXqkhkv5XIxZYyEmCNXKFMz0ssyq5usiwkOn3IrUdyTZOcaMVxA3s0Q5zEJM55Q';

// TRY 1: /api/br/ (Standard)
$searchUrl1 = 'https://bdris.gov.bd/api/br/applications/search';
echo "Test 1: $searchUrl1\n";
$params = [
    'status' => 'ALL',
    'draw' => 1,
    'start' => 0,
    'length' => 50,
    'search[value]' => '',
    'search[regex]' => 'false',
    'data' => $encryptedData
];
// Use explicit referer for public app
$resp1 = $proxy->fetch($searchUrl1, 'GET', $params, false, 'https://bdris.gov.bd/br/application');
echo "       HTTP: " . $resp1['status'] . " | Length: " . strlen($resp1['body']) . "\n";
if ($resp1['status'] == 200 && json_decode($resp1['body'])) {
    echo "       [SUCCESS] JSON Received.\n";
} else {
    // Extract Title
    preg_match('/<title>(.*?)<\/title>/', $resp1['body'], $matches);
    echo "       [FAIL] Title: " . ($matches[1] ?? 'No Title') . "\n";
}

// TRY 2: /admin/br/ (User provided path)
$searchUrl2 = 'https://bdris.gov.bd/admin/br/applications/search';
echo "\nTest 2: $searchUrl2\n";
// Use explicit referer for admin
$resp2 = $proxy->fetch($searchUrl2, 'GET', $params, false, 'https://bdris.gov.bd/admin/dashboard');
echo "       HTTP: " . $resp2['status'] . " | Length: " . strlen($resp2['body']) . "\n";
if ($resp2['status'] == 200 && json_decode($resp2['body'])) {
    echo "       [SUCCESS] JSON Received.\n";
    $json = json_decode($resp2['body'], true);
    $total = $json['recordsTotal'] ?? 0;
    echo "       Records Found: $total\n";
} else {
    preg_match('/<title>(.*?)<\/title>/', $resp2['body'], $matches);
    echo "       [FAIL] Title: " . ($matches[1] ?? 'No Title') . "\n";
}


// 4. Test Application ID Search (Fallback Logic)
echo "\nTesting Application ID Search (Fallback)...\n";
$testAppId = '260400564';

// Method A: Direct View
$urlA = "https://bdris.gov.bd/api/br/application/view/$testAppId";
echo "   [A] Direct View: $urlA\n";
$respA = $proxy->fetch($urlA, 'GET', [], false, 'https://bdris.gov.bd/');
echo "       HTTP: " . $respA['status'] . "\n";
if ($respA['status'] == 200) {
    if (stripos($respA['body'], 'Page not found') !== false) {
        echo "       [FAIL] Content: Page not found\n";
    } else {
        echo "       [PASS] Content seems valid (Len: " . strlen($respA['body']) . ")\n";
    }
}

// Method B: Search API
$urlB = "https://bdris.gov.bd/api/br/applications/search";
echo "   [B] Search API: $urlB\n";
$paramsB = [
    'draw' => 1, 
    'start' => 0, 
    'length' => 10, 
    'search[value]' => $testAppId, 
    'search[regex]' => 'false'
];
$respB = $proxy->fetch($urlB, 'GET', $paramsB, false, 'https://bdris.gov.bd/');
echo "       HTTP: " . $respB['status'] . "\n";
if ($respB['status'] == 200) {
    $json = json_decode($respB['body'], true);
    if ($json && isset($json['data'])) {
        echo "       [PASS] JSON Valid. Records: " . count($json['data']) . "\n";
        if (count($json['data']) > 0) {
            echo "       Found ID: " . ($json['data'][0]['id'] ?? 'N/A') . "\n";
        }
    } else {
        echo "       [FAIL] Invalid JSON or No Data\n";
        // Check for login redirect
        if (stripos($respB['body'], '<title>Login</title>') !== false) {
             echo "       [FAIL] Redirected to Login\n";
        }
    }
}

echo "\n========================================\n";
echo "Verification Complete.\n";

