false, 'message' => 'Metodo non consentito.']); exit; } // $pdo and $currentUserId from hr_auth_check.php $itemName = trim($_POST['item_name'] ?? ''); $deliveryDate = trim($_POST['delivery_date'] ?? ''); $deliveredBy = trim($_POST['delivered_by'] ?? ''); $notes = trim($_POST['notes'] ?? ''); $employeeIds = $_POST['employee_ids'] ?? []; if (!is_array($employeeIds)) { $employeeIds = []; } $employeeIds = array_values(array_unique(array_filter(array_map('intval', $employeeIds), fn($v) => $v > 0))); if ($itemName === '') { echo json_encode(['success' => false, 'message' => 'Il nome del DPI รจ obbligatorio.']); exit; } if ($deliveryDate !== '' && !DateTime::createFromFormat('Y-m-d', $deliveryDate)) { echo json_encode(['success' => false, 'message' => 'Data di consegna non valida.']); exit; } if (empty($employeeIds)) { echo json_encode(['success' => false, 'message' => 'Selezionare almeno un dipendente.']); exit; } $deliveryDate = $deliveryDate === '' ? null : $deliveryDate; $deliveredBy = $deliveredBy !== '' ? $deliveredBy : null; $notes = $notes !== '' ? $notes : null; try { $pdo->beginTransaction(); // Only insert for employees that actually exist $checkEmp = $pdo->prepare("SELECT id FROM employees WHERE id = :id"); $ins = $pdo->prepare(" INSERT INTO employee_ppe (employee_id, item_name, delivery_date, delivered_by, notes, created_by, created_at, updated_at) VALUES (:employee_id, :item_name, :delivery_date, :delivered_by, :notes, :created_by, NOW(), NOW()) "); $created = 0; foreach ($employeeIds as $eid) { $checkEmp->execute(['id' => $eid]); if (!$checkEmp->fetchColumn()) { continue; } $ins->execute([ 'employee_id' => $eid, 'item_name' => $itemName, 'delivery_date' => $deliveryDate, 'delivered_by' => $deliveredBy, 'notes' => $notes, 'created_by' => $currentUserId, ]); $created++; } $pdo->commit(); echo json_encode([ 'success' => true, 'created' => $created, 'message' => 'DPI assegnato a ' . $created . ' dipendent' . ($created === 1 ? 'e' : 'i') . '.', ]); } catch (Exception $e) { if ($pdo->inTransaction()) $pdo->rollBack(); echo json_encode(['success' => false, 'message' => $e->getMessage()]); }