<?php
session_start();
require_once __DIR__ . '/db/config.php';

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

echo "=== System Health Check ===\n\n";

// 1. Database Connection
echo "1. Database: ";
try {
    $db = db();
    $db->query("SELECT 1");
    echo "OK (Connected to " . DB_NAME . ")\n";
} catch (Exception $e) {
    echo "FAILED: " . $e->getMessage() . "\n";
}

// 2. Session Check
echo "2. Session: ";
$_SESSION['health_check_time'] = time();
if (isset($_SESSION['health_check_time'])) {
    echo "OK (Session working)\n";
    echo "   Session ID: " . session_id() . "\n";
    echo "   Admin ID: " . ($_SESSION['admin_id'] ?? 'Not logged in') . "\n";
    echo "   User ID: " . ($_SESSION['user_id'] ?? 'Not logged in') . "\n";
} else {
    echo "FAILED (Session not persisting)\n";
}

// 3. Table Check
echo "3. Tables:\n";
$tables = ['users', 'finance_requests', 'messages', 'chat_visitors', 'transactions'];
foreach ($tables as $t) {
    try {
        $stmt = db()->query("SELECT COUNT(*) FROM $t");
        $count = $stmt->fetchColumn();
        echo "   - $t: $count rows\n";
    } catch (Exception $e) {
        echo "   - $t: MISSING or ERROR (" . $e->getMessage() . ")\n";
    }
}

// 4. IP Check
echo "4. IP Info:\n";
echo "   Remote Addr: " . $_SERVER['REMOTE_ADDR'] . "\n";
echo "   Real IP (helper): " . getRealIP() . "\n";

echo "\n=== Check Complete ===\n";
echo "If any item above says FAILED, please check your server configuration (e.g. Baota database settings or PHP session permissions).\n";
