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

if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['user'])) {
    http_response_code(401);
    die('Not authorized');
}
$role = $_SESSION['user']['role'] ?? 'viewer';
if (!in_array($role, ['admin','warehouse'])) {
    http_response_code(403);
    die('Forbidden');
}

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

$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    http_response_code(400);
    die('Invalid JSON');
}

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

if ($table === '' || $primaryKey === '' || $id === null || !is_array($data)) {
    http_response_code(400);
    die('Missing parameters');
}

if (!preg_match('/^[A-Za-z0-9_]+$/', $table) ||
    !preg_match('/^[A-Za-z0-9_]+$/', $primaryKey)) {
    http_response_code(400);
    die('Invalid table or primary key');
}

$tableSafe = $mysqli->real_escape_string($table);
$pkSafe    = $mysqli->real_escape_string($primaryKey);

// recupera elenco colonne valide
$colsRes = $mysqli->query("SHOW COLUMNS FROM `$tableSafe`");
if (!$colsRes) {
    http_response_code(500);
    die('Cannot load columns: ' . $mysqli->error);
}
$cols = $colsRes->fetch_all(MYSQLI_ASSOC);
$validCols = [];
foreach ($cols as $c) {
    $validCols[] = $c['Field'];
}

$setParts = [];
foreach ($data as $col => $val) {
    if (!in_array($col, $validCols, true)) continue;
    if ($col === $primaryKey) continue; // non modificare PK
    if (!preg_match('/^[A-Za-z0-9_]+$/', $col)) continue;
    $colSafe = $mysqli->real_escape_string($col);
    $valEsc  = $mysqli->real_escape_string($val);
    $setParts[] = "`$colSafe` = '$valEsc'";
}

if (empty($setParts)) {
    http_response_code(400);
    die('Nothing to update');
}

$idVal = (int)$id;
$sql   = "UPDATE `$tableSafe` SET " . implode(', ', $setParts) . " WHERE `$pkSafe` = $idVal";

if (!$mysqli->query($sql)) {
    http_response_code(500);
    echo 'SQL error: ' . $mysqli->error;
    exit;
}

echo 'OK';
