getConnection(); $id = isset($_POST['id']) && $_POST['id'] !== '' ? (int)$_POST['id'] : null; $employeeId = (int)($_POST['employee_id'] ?? 0); $ppeItemId = (int)($_POST['ppe_item_id'] ?? 0); $assignedDate = trim($_POST['assigned_date'] ?? ''); $expiryDate = trim($_POST['expiry_date'] ?? ''); $deliveredBy = trim($_POST['delivered_by'] ?? ''); $status = trim($_POST['status'] ?? 'assigned'); $notes = trim($_POST['notes'] ?? ''); $allowedStatuses = [ 'assigned', 'returned', 'expired', 'lost', 'damaged', ]; if ($employeeId <= 0) { echo json_encode([ 'success' => false, 'message' => 'Dipendente non valido.' ]); exit; } if ($ppeItemId <= 0) { echo json_encode([ 'success' => false, 'message' => 'Selezionare un DPI.' ]); exit; } if (!in_array($status, $allowedStatuses, true)) { $status = 'assigned'; } $checkEmployee = $pdo->prepare("SELECT id FROM employees WHERE id = ? LIMIT 1"); $checkEmployee->execute([$employeeId]); if (!$checkEmployee->fetchColumn()) { echo json_encode([ 'success' => false, 'message' => 'Dipendente non trovato.' ]); exit; } $checkPpe = $pdo->prepare("SELECT id FROM ppe_items WHERE id = ? LIMIT 1"); $checkPpe->execute([$ppeItemId]); if (!$checkPpe->fetchColumn()) { echo json_encode([ 'success' => false, 'message' => 'DPI non trovato.' ]); exit; } if ($id) { $stmt = $pdo->prepare(" UPDATE employee_ppe_items SET ppe_item_id = :ppe_item_id, assigned_date = :assigned_date, expiry_date = :expiry_date, delivered_by = :delivered_by, status = :status, notes = :notes, updated_at = NOW() WHERE id = :id AND employee_id = :employee_id "); $stmt->execute([ 'ppe_item_id' => $ppeItemId, 'assigned_date' => $assignedDate !== '' ? $assignedDate : null, 'expiry_date' => $expiryDate !== '' ? $expiryDate : null, 'delivered_by' => $deliveredBy !== '' ? $deliveredBy : null, 'status' => $status, 'notes' => $notes !== '' ? $notes : null, 'id' => $id, 'employee_id' => $employeeId, ]); echo json_encode([ 'success' => true, 'message' => 'DPI aggiornato.' ]); exit; } $stmt = $pdo->prepare(" INSERT INTO employee_ppe_items ( employee_id, ppe_item_id, assigned_date, expiry_date, delivered_by, quantity, status, notes, created_by, created_at, updated_at ) VALUES ( :employee_id, :ppe_item_id, :assigned_date, :expiry_date, :delivered_by, 1, :status, :notes, :created_by, NOW(), NOW() ) "); $stmt->execute([ 'employee_id' => $employeeId, 'ppe_item_id' => $ppeItemId, 'assigned_date' => $assignedDate !== '' ? $assignedDate : null, 'expiry_date' => $expiryDate !== '' ? $expiryDate : null, 'delivered_by' => $deliveredBy !== '' ? $deliveredBy : null, 'status' => $status, 'notes' => $notes !== '' ? $notes : null, 'created_by' => isset($iduserlogin) ? (int)$iduserlogin : null, ]); echo json_encode([ 'success' => true, 'message' => 'DPI assegnato.' ]); exit; } catch (Throwable $e) { echo json_encode([ 'success' => false, 'message' => $e->getMessage() ]); exit; }