<?php
header('Content-Type: application/json');

$response = ['success' => false, 'message' => '', 'data' => []];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['message'] = 'Invalid request method.';
    echo json_encode($response);
    exit;
}

$host     = isset($_POST['host']) ? trim($_POST['host']) : '';
$dbname   = isset($_POST['dbname']) ? trim($_POST['dbname']) : '';
$username = isset($_POST['username']) ? trim($_POST['username']) : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$port     = isset($_POST['port']) ? (int)$_POST['port'] : 3306;

if (empty($host) || empty($dbname) || empty($username)) {
    $response['message'] = 'Host, database name, and username are required.';
    echo json_encode($response);
    exit;
}

try {
    $dsn = "mysql:host={$host};port={$port};charset=utf8mb4";
    $pdo = new PDO($dsn, $username, $password, [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);

    $response['success'] = true;
    $response['message'] = 'Database connection successful! Server version: ' . $pdo->getAttribute(PDO::ATTR_SERVER_VERSION);
} catch (PDOException $e) {
    $errorMsg = 'Connection failed: ';
    if (strpos($e->getMessage(), 'Unknown database') !== false) {
        $errorMsg .= 'Database "' . htmlspecialchars($dbname) . '" does not exist. It will be created during installation.';
        $response['success'] = true;
        $response['message'] = $errorMsg;
    } else {
        $errorMsg .= $e->getMessage();
        $response['message'] = $errorMsg;
    }
}

echo json_encode($response);
exit;
