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

if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['user']) || !user_has_permission('settings')) {
    http_response_code(403);
    exit('Forbidden');
}

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

$raw = file_get_contents('php://input');
$data = json_decode($raw, true);

if (!$data) {
    http_response_code(400);
    echo 'Invalid JSON';
    exit;
}

$table = $data['table']      ?? '';
$pk    = $data['primaryKey'] ?? '';
$id    = $data['id']         ?? null;
$fields= $data['data']       ?? [];

if (!$table || !$pk || $id === null || !is_array($fields)) {
    http_response_code(400);
    echo 'Missing parameters';
    exit;
}

// sanitize table
$tableSafe = preg_replace('/[^A-Za-z0-9_]/', '', $table);
if ($tableSafe !== $table) {
    http_response_code(400);
    echo 'Invalid table name';
    exit;
}

// load columns, validate pk & fields
$colsRes = $mysqli->query("SHOW COLUMNS FROM `$tableSafe`");
if (!$colsRes) {
    http_response_code(400);
    echo 'Table not found';
    exit;
}
$cols = [];
while ($c = $colsRes->fetch_assoc()) {
    $cols[] = $c['Field'];
}
if (!in_array($pk, $cols, true)) {
    http_response_code(400);
    echo 'Invalid primary key';
    exit;
}

$setParts = [];
$values = [];

foreach ($fields as $col => $val) {
    if (!in_array($col, $cols, true)) continue;
    if ($col === $pk) continue; // never update PK
    $setParts[] = "`$col` = ?";
    $values[] = $val;
}

if (empty($setParts)) {
    echo 'NO_FIELDS';
    exit;
}

$sql = "UPDATE `$tableSafe` SET " . implode(', ', $setParts) . " WHERE `$pk` = ?";
$values[] = (string)$id;
$types = str_repeat('s', count($values));

$stmt = $mysqli->prepare($sql);
if (!$stmt) {
    http_response_code(500);
    echo 'Prepare failed';
    exit;
}

$stmt->bind_param($types, ...$values);
$stmt->execute();

if ($stmt->errno) {
    http_response_code(500);
    echo 'DB error: ' . $stmt->error;
} else {
    echo 'OK';
}
