<?php
/**
 * POST /api/delete-product.php
 * Body: ids[]=1&ids[]=2
 */
require_once __DIR__ . '/../includes/db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(['ok' => false, 'error' => 'Doar POST'], 405);
}
if (!csrf_check($_POST['csrf_token'] ?? null)) {
    json_response(['ok' => false, 'error' => 'CSRF invalid'], 403);
}

$ids = $_POST['ids'] ?? [];
if (!is_array($ids) || !$ids) {
    json_response(['ok' => false, 'error' => 'Niciun ID furnizat.'], 422);
}

$ids = array_values(array_filter(array_map('intval', $ids), fn($v) => $v > 0));
if (!$ids) {
    json_response(['ok' => false, 'error' => 'ID-uri invalide.'], 422);
}

try {
    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $affected     = db_exec("DELETE FROM products WHERE id IN ($placeholders)", $ids);

    json_response(['ok' => true, 'deleted' => $affected]);
} catch (Throwable $ex) {
    error_log('[delete-product] ' . $ex->getMessage());
    json_response(['ok' => false, 'error' => 'Eroare DB: ' . $ex->getMessage()], 500);
}
