getConnection(); // Verifica utente loggato if (!isset($iduserlogin)) { header("Location: ../login.php"); exit; } // Helpers flash function setFlash(string $type, string $text): void { $_SESSION['flash'] = ['type' => $type, 'text' => $text]; } function getFlash(): ?array { if (!isset($_SESSION['flash'])) return null; $f = $_SESSION['flash']; unset($_SESSION['flash']); return $f; } // Fetch dati utente $stmt = $pdo->prepare(" SELECT first_name, last_name, phone, email, avatar, address, birthday FROM auth_users WHERE id = ? "); $stmt->execute([$iduserlogin]); $user = $stmt->fetch(PDO::FETCH_ASSOC); if (!$user) { die("Errore: utente non trovato."); } // POST - Aggiorna profilo (escluso password) if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_profile') { try { $first_name = trim($_POST['first_name'] ?? ''); $last_name = trim($_POST['last_name'] ?? ''); $phone = trim($_POST['phone'] ?? ''); $email = trim($_POST['email'] ?? ''); $address = trim($_POST['address'] ?? ''); $birthday = !empty($_POST['birthday']) ? $_POST['birthday'] : null; // Validazioni if (empty($first_name) || empty($last_name)) { throw new Exception("Nome e Cognome sono obbligatori."); } if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { throw new Exception("Email non valida."); } // Upload avatar $avatar = $user['avatar']; $upload_dir = '../upload/users/'; if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true); if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] === UPLOAD_ERR_OK) { $file = $_FILES['avatar']; $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)); // Formati accettati (inclusi HEIC/HEIF da iPhone) $allowed = ['jpg', 'jpeg', 'png', 'heic', 'heif']; if (!in_array($ext, $allowed)) { throw new Exception("Formato non supportato. Usa JPG, PNG o HEIC/HEIF."); } // Nome file sicuro $original_name = preg_replace('/[^A-Za-z0-9\._-]/', '', pathinfo($file['name'], PATHINFO_FILENAME)); $timestamp = time(); $new_filename = "{$iduserlogin}-{$timestamp}-{$original_name}.{$ext}"; $dest_path = $upload_dir . $new_filename; // Sposta file temporaneo if (move_uploaded_file($file['tmp_name'], $dest_path)) { // Ridimensiona (max 400x400) list($width, $height) = getimagesize($dest_path); $max_size = 400; if ($width > $max_size || $height > $max_size) { $ratio = $max_size / max($width, $height); $new_width = (int)($width * $ratio); $new_height = (int)($height * $ratio); $thumb = imagecreatetruecolor($new_width, $new_height); if ($ext === 'png') { imagealphablending($thumb, false); imagesavealpha($thumb, true); } $source = match ($ext) { 'jpg', 'jpeg' => imagecreatefromjpeg($dest_path), 'png' => imagecreatefrompng($dest_path), 'heic', 'heif' => imagecreatefromstring(file_get_contents($dest_path)), // HEIC richiede GD recente o Imagick default => null }; if ($source) { imagecopyresampled($thumb, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height); imagejpeg($thumb, $dest_path, 85); // salva come jpg per compatibilità imagedestroy($source); imagedestroy($thumb); $new_filename = "{$iduserlogin}-{$timestamp}-{$original_name}.jpg"; // aggiorna estensione } } // Cancella vecchio avatar se esiste if ($avatar && file_exists('../' . $avatar)) { @unlink('../' . $avatar); } $avatar = "upload/users/" . $new_filename; } else { throw new Exception("Errore durante il caricamento dell'immagine."); } } // Update DB $stmt = $pdo->prepare(" UPDATE auth_users SET first_name = ?, last_name = ?, phone = ?, email = ?, address = ?, birthday = ?, avatar = ?, updated_at = NOW() WHERE id = ? "); $ok = $stmt->execute([ $first_name, $last_name, $phone ?: null, $email, $address ?: null, $birthday, $avatar, $iduserlogin ]); setFlash($ok ? 'success' : 'danger', $ok ? "Profilo aggiornato con successo!" : "Errore durante il salvataggio."); header("Location: profile.php"); exit; } catch (Exception $e) { setFlash('danger', $e->getMessage()); header("Location: profile.php"); exit; } } // POST - Cambio password if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'change_password') { try { $old_password = $_POST['old_password'] ?? ''; $new_password = $_POST['new_password'] ?? ''; $confirm_password = $_POST['confirm_password'] ?? ''; if (empty($old_password) || empty($new_password) || empty($confirm_password)) { throw new Exception("Tutti i campi sono obbligatori."); } if ($new_password !== $confirm_password) { throw new Exception("Le nuove password non coincidono."); } if (strlen($new_password) < 8) { throw new Exception("La nuova password deve avere almeno 8 caratteri."); } // Verifica vecchia password (Laravel Hash) $stmt = $pdo->prepare("SELECT password FROM auth_users WHERE id = ?"); $stmt->execute([$iduserlogin]); $hashed = $stmt->fetchColumn(); if (!password_verify($old_password, $hashed)) { throw new Exception("La vecchia password non è corretta."); } // Nuova password $new_hashed = password_hash($new_password, PASSWORD_DEFAULT); $stmt = $pdo->prepare("UPDATE auth_users SET password = ?, updated_at = NOW() WHERE id = ?"); $ok = $stmt->execute([$new_hashed, $iduserlogin]); setFlash($ok ? 'success' : 'danger', $ok ? "Password cambiata con successo!" : "Errore durante il cambio password."); header("Location: profile.php"); exit; } catch (Exception $e) { setFlash('danger', $e->getMessage()); header("Location: profile.php"); exit; } } $flash = getFlash(); ?>