<?php
include 'dbconn.php';

$clinicId = isset($_GET['id']) ? intval($_GET['id']) : 0;
$table = $_GET['table'] ?? '';
$search = trim($_GET['search'] ?? '');

// Whitelist allowed tables
$allowedTables = [
    'basic_information',
    'principal_investigators',
    'study_design',
    'site_facilities',
    'investigational_products',
    'recruitment_data'
];

if (!in_array($table, $allowedTables)) {
    echo "<p>Invalid table selected.</p>";
    exit;
}

// Build query
$query = "SELECT * FROM `$table` WHERE clinic_id = ?";
$params = [$clinicId];
$types = "i";

// Optional search
if ($search) {
    $columns = [];
    $colResult = $mysqli->query("SHOW COLUMNS FROM `$table`");
    if (!$colResult) {
        echo "Column fetch error: " . $mysqli->error;
        exit;
    }

    while ($col = $colResult->fetch_assoc()) {
        $columns[] = $col['Field'];
    }

    if (count($columns)) {
        $query .= " AND (";
        $searchParts = [];
        foreach ($columns as $col) {
            $searchParts[] = "`$col` LIKE ?";
            $params[] = "%$search%";
            $types .= "s";
        }
        $query .= implode(" OR ", $searchParts) . ")";
    }
}

$stmt = $mysqli->prepare($query);
if (!$stmt) {
    echo "SQL prepare error: " . $mysqli->error;
    exit;
}
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo "<p>No data found.</p>";
    exit;
}

// Display table
echo "<table class='table table-bordered table-striped'><thead><tr>";
$firstRow = $result->fetch_assoc();
foreach ($firstRow as $key => $val) {
    if ($key === 'id' || $key === 'clinic_id') continue;
    echo "<th>" . htmlspecialchars(ucwords(str_replace("_", " ", $key))) . "</th>";
}
echo "</tr></thead><tbody>";

// First row
echo "<tr>";
foreach ($firstRow as $key => $val) {
    if ($key === 'id' || $key === 'clinic_id') continue;

    if (strtolower($key) === 'status') {
        $status = strtolower($val);
        $class = match($status) {
            'approved'     => 'text-success fw-bold',
            'disapproved'  => 'text-danger fw-bold',
            'pending'      => 'text-dark fw-bold',
            default        => ''
        };
        echo "<td class='$class'>" . htmlspecialchars($val) . "</td>";
    } else {
        echo "<td>" . htmlspecialchars($val) . "</td>";
    }
}
echo "</tr>";

// Remaining rows
while ($row = $result->fetch_assoc()) {
    echo "<tr>";
    foreach ($row as $key => $val) {
        if ($key === 'id' || $key === 'clinic_id') continue;

        if (strtolower($key) === 'status') {
            $status = strtolower($val);
            $class = match($status) {
                'approved'     => 'text-success fw-bold',
                'disapproved'  => 'text-danger fw-bold',
                'pending'      => 'text-dark fw-bold',
                default        => ''
            };
            echo "<td class='$class'>" . htmlspecialchars($val) . "</td>";
        } else {
            echo "<td>" . htmlspecialchars($val) . "</td>";
        }
    }
    echo "</tr>";
}

echo "</tbody></table>";
?>
