<?php
require_once '../includes/init.php';

// Check admin access
if (!isAuthenticated() || !$_SESSION['is_admin']) {
    jsonResponse(false, 'Admin access required');
    exit;
}

$db = getDB();

// Check current database state
$checkData = [];

// Check failed login columns
$stmt = $db->prepare("SHOW COLUMNS FROM users LIKE 'failed_login_attempts'");
$stmt->execute();
$checkData['has_failed_login_columns'] = $stmt->fetch() ? true : false;

// Check auto logout settings (key-value format)
$stmt = $db->prepare("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('auto_logout_enabled', 'auto_logout_minutes')");
$stmt->execute();
$settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

if ($settings) {
    $checkData['auto_logout_enabled'] = $settings['auto_logout_enabled'] === '1';
    $checkData['auto_logout_minutes'] = intval($settings['auto_logout_minutes']);
} else {
    $checkData['auto_logout_enabled'] = true;
    $checkData['auto_logout_minutes'] = 5;
}

$checkData['has_auto_logout_columns'] = !empty($settings);

// Get user statistics
$stmt = $db->prepare("
    SELECT 
        COUNT(*) as total_users,
        COUNT(CASE WHEN status = 'approved' THEN 1 END) as approved_users,
        COUNT(CASE WHEN status = 'blocked' THEN 1 END) as blocked_users,
        COUNT(CASE WHEN failed_login_attempts >= 5 THEN 1 END) as locked_users
    FROM users
    WHERE is_admin = 0
");
$stmt->execute();
$checkData['user_stats'] = $stmt->fetch();

jsonResponse(true, 'Database check completed', $checkData);
?>
