2026-02-01 20:37:49 +01:00

386 lines
16 KiB
PHP

<?php
// Forza la visualizzazione degli errori (solo dev)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
include('include/headscript.php');
// Connessione DB
$dbHandler = DBHandlerSelect::getInstance();
$pdo = $dbHandler->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();
?>
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="../assets/images/favicon-32x32.png" type="image/png" />
<?php include('cssinclude.php'); ?>
<?php include('siteinfo.php'); ?>
<title>Il Mio Profilo</title>
<style>
.avatar-preview {
width: 140px;
height: 140px;
object-fit: cover;
border-radius: 50%;
border: 4px solid #e5e7eb;
margin-bottom: 1rem;
}
.section-title {
font-size: 1.35rem;
font-weight: 700;
margin: 2rem 0 1.5rem;
color: #1f2937;
position: relative;
}
.section-title::after {
content: '';
position: absolute;
bottom: -8px;
left: 0;
width: 60px;
height: 3px;
background: #6366f1;
border-radius: 3px;
}
.btn-save {
background: linear-gradient(135deg, #10b981 0%, #059669 100%);
border: none;
}
.btn-save:hover {
transform: translateY(-2px);
box-shadow: 0 8px 20px rgba(16, 185, 129, 0.3);
}
</style>
</head>
<body>
<div class="wrapper">
<?php include('include/navbar.php'); ?>
<?php include('include/topbar.php'); ?>
<div class="page-wrapper">
<div class="page-content">
<div class="card radius-10">
<div class="card-header bg-light d-flex justify-content-between align-items-center">
<h6 class="mb-0">Il Mio Profilo</h6>
<a href="dashboard.php" class="btn btn-outline-secondary btn-sm">
<i class="bx bx-arrow-back me-1"></i> Dashboard
</a>
</div>
<div class="card-body">
<?php if ($flash): ?>
<div class="alert alert-<?= htmlspecialchars($flash['type']) ?> alert-dismissible fade show mb-4" role="alert">
<?= htmlspecialchars($flash['text']) ?>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>
<div class="row g-5">
<!-- Colonna sinistra: dati profilo -->
<div class="col-lg-7">
<form action="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="update_profile">
<div class="text-center mb-4">
<img src="../upload/users/<?= htmlspecialchars($user['avatar'] ? '' . $user['avatar'] : '../assets/images/default-user.png') ?>"
alt="Avatar" class="avatar-preview" id="avatarPreview">
<input type="file" class="form-control form-control-sm mt-2" name="avatar" id="avatarInput" accept="image/jpeg,image/png,image/heic,image/heif">
<small class="form-text text-muted">JPG, PNG, HEIC/HEIF (max 5MB)</small>
</div>
<div class="row g-3">
<div class="col-md-6">
<label class="form-label fw-bold">Nome</label>
<input type="text" class="form-control" name="first_name" value="<?= htmlspecialchars($user['first_name'] ?? '') ?>" required>
</div>
<div class="col-md-6">
<label class="form-label fw-bold">Cognome</label>
<input type="text" class="form-control" name="last_name" value="<?= htmlspecialchars($user['last_name'] ?? '') ?>" required>
</div>
<div class="col-md-6">
<label class="form-label fw-bold">Telefono</label>
<input type="tel" class="form-control" name="phone" value="<?= htmlspecialchars($user['phone'] ?? '') ?>">
</div>
<div class="col-md-6">
<label class="form-label fw-bold">Email</label>
<input type="email" class="form-control" name="email" value="<?= htmlspecialchars($user['email']) ?>" required>
</div>
<div class="col-md-6">
<label class="form-label fw-bold">Data di nascita</label>
<input type="date" class="form-control" name="birthday" value="<?= htmlspecialchars($user['birthday'] ?? '') ?>">
</div>
<div class="col-md-6">
<label class="form-label fw-bold">Indirizzo</label>
<input type="text" class="form-control" name="address" value="<?= htmlspecialchars($user['address'] ?? '') ?>">
</div>
</div>
<div class="d-grid mt-4">
<button type="submit" class="btn btn-primary btn-lg">Salva Modifiche Profilo</button>
</div>
</form>
</div>
<!-- Colonna destra: cambio password -->
<div class="col-lg-5">
<div class="card border shadow-sm">
<div class="card-header bg-light">
<h6 class="mb-0">Modifica Password</h6>
</div>
<div class="card-body">
<form action="" method="POST">
<input type="hidden" name="action" value="change_password">
<div class="mb-3">
<label class="form-label fw-bold">Vecchia password</label>
<input type="password" class="form-control" name="old_password" required autocomplete="current-password">
</div>
<div class="mb-3">
<label class="form-label fw-bold">Nuova password</label>
<input type="password" class="form-control" name="new_password" required minlength="8" autocomplete="new-password">
<small class="form-text text-muted">Minimo 8 caratteri</small>
</div>
<div class="mb-3">
<label class="form-label fw-bold">Conferma nuova password</label>
<input type="password" class="form-control" name="confirm_password" required autocomplete="new-password">
</div>
<div class="d-grid">
<button type="submit" class="btn btn-warning">Cambia Password</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<?php include('include/footer.php'); ?>
</div>
<?php include('jsinclude.php'); ?>
<script>
// Anteprima avatar
document.getElementById('avatarInput').addEventListener('change', function(e) {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(ev) {
document.getElementById('avatarPreview').src = ev.target.result;
};
reader.readAsDataURL(file);
}
});
</script>
</body>
</html>