getConnection(); $userId = (int)($iduserlogin ?? 0); if ($userId <= 0) { die('Utente non valido.'); } if (session_status() === PHP_SESSION_NONE) { session_start(); } if (empty($_SESSION['notif_settings_csrf'])) { $_SESSION['notif_settings_csrf'] = bin2hex(random_bytes(32)); } $csrfToken = $_SESSION['notif_settings_csrf']; $successMessage = ''; $errorMessage = ''; // Load current user notification preferences. $stmtUser = $pdo->prepare(" SELECT id, email, first_name, last_name, notify_email, notify_webapp FROM auth_users WHERE id = ? LIMIT 1 "); $stmtUser->execute([$userId]); $profileUser = $stmtUser->fetch(PDO::FETCH_ASSOC); if (!$profileUser) { die('Utente non trovato.'); } function e($value) { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); } if ($_SERVER['REQUEST_METHOD'] === 'POST') { $postedToken = $_POST['csrf_token'] ?? ''; if (!hash_equals($csrfToken, $postedToken)) { $errorMessage = 'Sessione non valida. Ricarica la pagina e riprova.'; } else { $notifyEmail = isset($_POST['notify_email']) ? 1 : 0; $notifyWebapp = isset($_POST['notify_webapp']) ? 1 : 0; try { $stmtUpdate = $pdo->prepare(" UPDATE auth_users SET notify_email = :notify_email, notify_webapp = :notify_webapp, updated_at = NOW() WHERE id = :id LIMIT 1 "); $stmtUpdate->execute([ ':notify_email' => $notifyEmail, ':notify_webapp' => $notifyWebapp, ':id' => $userId, ]); $successMessage = 'Preferenze di notifica aggiornate correttamente.'; // Reload updated user. $stmtUser->execute([$userId]); $profileUser = $stmtUser->fetch(PDO::FETCH_ASSOC); $_SESSION['notif_settings_csrf'] = bin2hex(random_bytes(32)); $csrfToken = $_SESSION['notif_settings_csrf']; } catch (Exception $e) { $errorMessage = 'Errore durante il salvataggio delle preferenze.'; } } } $notifyEmail = (int)($profileUser['notify_email'] ?? 0); $notifyWebapp = (int)($profileUser['notify_webapp'] ?? 0); ?>