<?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'] ?? '';
$ids        = $input['ids']        ?? [];

if ($table === '' || $primaryKey === '' || !is_array($ids) || empty($ids)) {
    http_response_code(400);
    die('Missing parameters');
}

// sicurezza minima su nomi
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);

// filtra gli ID
$cleanIds = [];
foreach ($ids as $id) {
    if (is_numeric($id)) {
        $cleanIds[] = (int)$id;
    }
}
if (empty($cleanIds)) {
    http_response_code(400);
    die('No valid IDs');
}

$idList = implode(',', $cleanIds);
$sql = "DELETE FROM `$tableSafe` WHERE `$pkSafe` IN ($idList)";
if (!$mysqli->query($sql)) {
    http_response_code(500);
    echo 'SQL error: ' . $mysqli->error;
    exit;
}

echo 'OK';
