<?php
// TEST FILE - Diagnostic for database connection
// This will show if the DB connection is working and what error is occurring
header('Content-Type: application/json; charset=utf-8');

$output = [];

// Check if db_config.php exists
$dbConfigPath = __DIR__ . '/db_config.php';
$output['db_config_exists'] = file_exists($dbConfigPath);

if (!file_exists($dbConfigPath)) {
    $output['error'] = 'db_config.php not found';
    echo json_encode($output);
    exit;
}

// Include db_config.php
$output['including_db_config'] = true;
require_once $dbConfigPath;

// Check if connection was created
$output['conn_is_set'] = isset($conn);
$output['conn_is_object'] = is_object($conn ?? null);
$output['conn_is_mysqli'] = ($conn instanceof mysqli);

// Check for connection errors
if (!isset($conn) || !$conn) {
    $output['error'] = 'Connection object not set';
    echo json_encode($output);
    exit;
}

if ($conn->connect_error) {
    $output['error'] = 'Connection error: ' . $conn->connect_error;
    echo json_encode($output);
    exit;
}

// Try a simple query
$output['attempting_query'] = 'SELECT COUNT(*) as count FROM users';

$result = $conn->query('SELECT COUNT(*) as count FROM users');
if (!$result) {
    $output['error'] = 'Query failed: ' . $conn->error;
    echo json_encode($output);
    exit;
}

$row = $result->fetch_assoc();
$output['user_count'] = $row['count'];

// Try to get user details
$output['attempting_list_users'] = true;
$users = [];
$res = $conn->query('SELECT id, username, email, IFNULL(name,"") as name FROM users ORDER BY id DESC');
if ($res) {
    while ($r = $res->fetch_assoc()) {
        $users[] = $r;
    }
}

$output['users'] = $users;
$output['success'] = true;
$output['status'] = 'Database connection working properly';

echo json_encode($output, JSON_PRETTY_PRINT);
?>
