<?php
// This file is an AJAX endpoint that checks the connection to a source database
// and returns the list of available tables

// Include database connection
require_once '../layouts/dbconn.php';

// Initialize response array
$response = [
    'success' => false,
    'message' => '',
    'tables' => []
];

// Check if all required parameters are provided
if (!isset($_POST['host']) || !isset($_POST['username']) || !isset($_POST['database'])) {
    $response['message'] = 'Missing required parameters';
    echo json_encode($response);
    exit;
}

// Get parameters
$host = $_POST['host'];
$username = $_POST['username'];
$password = $_POST['password'] ?? '';
$database = $_POST['database'];

// Try to connect to the source database
try {
    $sourceConn = new mysqli($host, $username, $password, $database);
    
    if ($sourceConn->connect_error) {
        throw new Exception("Connection failed: " . $sourceConn->connect_error);
    }
    
    // Get list of tables
    $tablesQuery = "SHOW TABLES";
    $tablesResult = $sourceConn->query($tablesQuery);
    
    if (!$tablesResult) {
        throw new Exception("Error fetching tables: " . $sourceConn->error);
    }
    
    $tables = [];
    while ($row = $tablesResult->fetch_row()) {
        $tables[] = $row[0];
    }
    
    // Close connection
    $sourceConn->close();
    
    // Set success response
    $response['success'] = true;
    $response['message'] = 'Connection successful';
    $response['tables'] = $tables;
    
} catch (Exception $e) {
    $response['message'] = $e->getMessage();
}

// Return response as JSON
header('Content-Type: application/json');
echo json_encode($response);
?>