<?php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

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

require_once '../config/database.php';

$database = new Database();
$conn = null;

try {
    $conn = $database->getConnection();
    
    // Check database connection
    $tables = [];
    $result = $conn->query("SHOW TABLES");
    while ($row = $result->fetch(PDO::FETCH_NUM)) {
        $tables[] = $row[0];
    }
    
    // Check for key tables
    $keyTables = ['users', 'items', 'clients', 'chart_of_accounts'];
    $missingTables = array_diff($keyTables, $tables);
    
    // Check for admin user
    $adminExists = false;
    if (in_array('users', $tables)) {
        $checkAdmin = $conn->prepare("SELECT COUNT(*) as count FROM users WHERE username = 'admin'");
        $checkAdmin->execute();
        $adminCount = $checkAdmin->fetch(PDO::FETCH_ASSOC)['count'];
        $adminExists = $adminCount > 0;
    }
    
    $isInitialized = empty($missingTables) && $adminExists;
    
    echo json_encode([
        "success" => true,
        "connected" => true,
        "initialized" => $isInitialized,
        "tables" => $tables,
        "table_count" => count($tables),
        "missing_tables" => $missingTables,
        "admin_user_exists" => $adminExists,
        "status" => $isInitialized ? "ready" : "needs_initialization"
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        "success" => false,
        "connected" => false,
        "initialized" => false,
        "error" => $e->getMessage(),
        "status" => "connection_failed"
    ]);
}
?>
