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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => false, 'message' => 'Invalid request']);
    exit;
}

$hostname = trim($_POST['hostname'] ?? '');
$username = trim($_POST['username'] ?? '');
$password = $_POST['password'] ?? '';
$database = trim($_POST['database'] ?? '');

if ($hostname === '' || $username === '' || $database === '') {
    echo json_encode([
        'status' => false,
        'message' => 'Database name is required and cannot be empty'
    ]);
    exit;
}

mysqli_report(MYSQLI_REPORT_OFF);

// Server connection
$conn = @mysqli_connect($hostname, $username, $password);
if (!$conn) {
    echo json_encode([
        'status' => false,
        'message' => 'Invalid database server credentials'
    ]);
    exit;
}

// Database selection (STRICT)
if (!@mysqli_select_db($conn, $database)) {
    echo json_encode([
        'status' => false,
        'message' => 'Invalid database name or permission denied'
    ]);
    exit;
}

mysqli_close($conn);

echo json_encode([
    'status' => true,
    'message' => 'Database verified successfully'
]);
