<?php
require_once __DIR__ . '/../config/user_functions.php';

if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once __DIR__ . '/../config/users_local.php';

$can_full   = user_has_permission('ibc_tables');
$can_delete = user_has_permission('ibc_tables_delete');

if (!($can_full || $can_delete)) {
    http_response_code(403);
    echo "Access denied";
    exit;
}

require_once __DIR__ . '/../config/db_ibc.php';

function ibc_get_primary_key($conn, $table) {
    $pk = [];
    if ($res = $conn->query("SHOW KEYS FROM `$table` WHERE Key_name = 'PRIMARY'")) {
        while ($row = $res->fetch_assoc()) {
            $pk[] = $row['Column_name'];
        }
    }
    return $pk;
}

$table = $_GET['table'] ?? '';
$table = $ibc_conn->real_escape_string($table);
if ($table === '') {
    echo "No table specified.";
    exit;
}

$pk_cols = ibc_get_primary_key($ibc_conn, $table);
if (!$pk_cols) {
    echo "Cannot delete: table has no primary key.";
    exit;
}

$parts = [];
foreach ($pk_cols as $pk) {
    if (!isset($_GET[$pk])) {
        echo "Missing primary key value.";
        exit;
    }
    $val = $ibc_conn->real_escape_string($_GET[$pk]);
    $parts[] = "`$pk` = '$val'";
}
$where_pk = implode(' AND ', $parts);
$sql = "DELETE FROM `$table` WHERE $where_pk LIMIT 1";
$ibc_conn->query($sql);

header("Location: ibc_tables.php?table=" . urlencode($table));
exit;
