<?php
// api/db_viewer.php

header('Content-Type: application/json');
require_once '../config/database.php';

$action = $_GET['action'] ?? '';

try {
    $db = new Database();
    $conn = $db->getConnection();

    if (!$conn) {
        throw new Exception("Failed to connect to the database.");
    }

    if ($action === 'get_tables') {
        $stmt = $conn->query('SHOW TABLES');
        $tables = $stmt->fetchAll(PDO::FETCH_COLUMN);
        echo json_encode($tables);
    } elseif ($action === 'get_table_data') {
        $table = $_GET['table'] ?? '';

        if (empty($table)) {
            throw new Exception("Table name not specified.");
        }

        // Validate table name to prevent SQL injection
        $stmt = $conn->query('SHOW TABLES');
        $allowed_tables = $stmt->fetchAll(PDO::FETCH_COLUMN);
        if (!in_array($table, $allowed_tables)) {
            throw new Exception("Invalid table name.");
        }

        // Get column names
        $stmt = $conn->query("DESCRIBE `$table`");
        $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);

        // Get rows
        $stmt = $conn->query("SELECT * FROM `$table`");
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        echo json_encode(['columns' => $columns, 'rows' => $rows]);
    } else {
        throw new Exception("Invalid action.");
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
