add_user functionality

This commit is contained in:
Claudio 2026-01-20 09:57:44 +01:00
parent 7c574649a0
commit dda63d9711
3 changed files with 455 additions and 75 deletions

View File

@ -0,0 +1,369 @@
<?php
// add_user.php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include('include/headscript.php');
require_once 'class/mailer.php';
$dbHandler = DBHandlerSelect::getInstance();
$pdo = $dbHandler->getConnection();
if (!isset($iduserlogin)) {
die("Errore: utente non loggato.");
}
// 1. Recupera SOLO la scuola corrente del proprietario loggato
$stmt = $pdo->prepare("
SELECT id, name, email AS school_email
FROM schools
WHERE owner_id = ? AND status = 'active'
");
$stmt->execute([$iduserlogin]);
$school = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$school) {
die("Nessuna scuola trovata per questo proprietario.");
}
$school_id = $school['id'];
$school_name = $school['name'];
$school_email = $school['school_email'];
// 2. Messaggi di feedback
$success_message = $_GET['success'] ?? null;
$error_message = $_GET['error'] ?? null;
// 3. GESTIONE POST - Aggiungi/Collega Utente
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_or_link_user') {
$email = trim($_POST['email'] ?? '');
$first_name = trim($_POST['first_name'] ?? '');
$last_name = trim($_POST['last_name'] ?? '');
$phone = trim($_POST['phone'] ?? '');
// Validazioni
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error_message = "Email non valida.";
} elseif (empty($first_name) || empty($last_name)) {
$error_message = "Nome e cognome obbligatori.";
} else {
// CASE 1: Verifica se utente ESISTE già (case-insensitive)
$stmt = $pdo->prepare("
SELECT id, first_name, last_name, email_verified_at, status
FROM auth_users
WHERE LOWER(email) = LOWER(?)
");
$stmt->execute([$email]);
$existingUser = $stmt->fetch(PDO::FETCH_ASSOC);
if ($existingUser) {
// ✅ UTENTE ESISTE → SOLO COLLEGA alla scuola
$user_id = $existingUser['id'];
// Verifica se è già collegato a questa scuola
$stmt = $pdo->prepare("
SELECT id FROM user_schools
WHERE user_id = ? AND school_id = ?
");
$stmt->execute([$user_id, $school_id]);
if ($stmt->fetch()) {
$error_message = "Questo utente è già associato alla tua scuola.";
} else {
// COLLEGAMENTO
$stmt = $pdo->prepare("
INSERT INTO user_schools (user_id, school_id, status, created_at, updated_at)
VALUES (?, ?, 'active', NOW(), NOW())
");
$stmt->execute([$user_id, $school_id]);
// 📧 EMAIL: "Sei stato agganciato alla scuola XXXX"
$subject = "Associato a {$school_name} - Yogibook";
$body = "
<h2>Ciao {$first_name} {$last_name},</h2>
<p>Sei stato <strong>associato alla scuola {$school_name}</strong> sulla piattaforma Yogibook.</p>
<p>Ora puoi accedere con le tue credenziali e vedere le lezioni di questa scuola.</p>
<p><strong>Login:</strong> <a href='https://app.yogiboook.com/login'>app.yogiboook.com/login</a></p>
<hr>
<p><em>Se non riconosci questa scuola, contatta: {$school_email}</em></p>
<p style='color:#666; font-size:0.9em;'>Messaggio automatico non rispondere.</p>
";
$emailResult = sendEmail($email, $subject, $body);
if ($emailResult['success']) {
$success_message = "Utente <strong>{$first_name} {$last_name}</strong> collegato con successo a {$school_name}! 📧 Email inviata.";
} else {
$error_message = "Utente collegato, ma errore email: " . $emailResult['message'];
}
}
} else {
// ❌ UTENTE NON ESISTE → CREA + link reset password
$tempPassword = bin2hex(random_bytes(16)); // Password random (inutile)
$hashedPassword = password_hash($tempPassword, PASSWORD_DEFAULT);
$stmt = $pdo->prepare("
INSERT INTO auth_users (
email, first_name, last_name, phone,
password, role_id, status,
created_at, updated_at, email_verified_at
) VALUES (?, ?, ?, ?, ?, 2, 'active', NOW(), NOW(), NULL)
");
$success = $stmt->execute([
$email,
$first_name,
$last_name,
empty($phone) ? null : $phone,
$hashedPassword
]);
if ($success) {
$user_id = $pdo->lastInsertId();
// COLLEGA alla scuola
$stmt = $pdo->prepare("
INSERT INTO user_schools (user_id, school_id, status, created_at, updated_at)
VALUES (?, ?, 'active', NOW(), NOW())
");
$stmt->execute([$user_id, $school_id]);
// 📧 EMAIL: Link diretto a reset password
$resetLink = "https://app.yogiboook.com/public/password/reset?email=" . urlencode($email);
$subject = "Benvenuto in {$school_name} - Imposta Password | Yogibook";
$body = "
<h2>Ciao {$first_name}, benvenuto in {$school_name}!</h2>
<p>La scuola ti ha invitato sulla piattaforma Yogibook.</p>
<p><strong>PRIMO PASSO OBBLIGATORIO:</strong> imposta la tua password:</p>
<p style='text-align:center; margin:40px 0;'>
<a href='{$resetLink}' style='background:#0d6efd; color:white; padding:15px 30px; text-decoration:none; border-radius:8px; font-size:16px; font-weight:bold;'>
IMPOSTA LA TUA PASSWORD
</a>
</p>
<p><small>Non funziona il link? Copia-incolla: <br><strong>{$resetLink}</strong></small></p>
<hr>
<p><strong>Login:</strong> <a href='https://app.yogiboook.com/login'>app.yogiboook.com/login</a></p>
<p><em>Contatta la scuola: {$school_email}</em></p>
<p style='color:#666; font-size:0.9em;'>Messaggio automatico non rispondere.</p>
";
$emailResult = sendEmail($email, $subject, $body);
if ($emailResult['success']) {
$success_message = "✅ Nuovo utente <strong>{$first_name} {$last_name}</strong> creato e collegato a {$school_name}! 📧 Link reset password inviato.";
} else {
$error_message = "Utente creato/collegato, ma errore email: " . $emailResult['message'];
}
} else {
$error_message = "Errore creazione utente. Riprova.";
}
}
}
}
// 4. Lista UTENTI ASSOCIATI SOLO A QUESTA SCUOLA (punto 1 ✅)
$stmt = $pdo->prepare("
SELECT
au.id, au.first_name, au.last_name, au.email, au.phone,
au.email_verified_at, au.status AS user_status,
us.status AS school_status, us.created_at
FROM user_schools us
JOIN auth_users au ON us.user_id = au.id
WHERE us.school_id = ?
ORDER BY au.last_name, au.first_name
");
$stmt->execute([$school_id]);
$schoolUsers = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gestione Utenti - <?= htmlspecialchars($school_name) ?></title>
<?php include('cssinclude.php'); ?>
<?php include('siteinfo.php'); ?>
</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="row">
<div class="col-12">
<div class="page-title-box d-sm-flex align-items-center justify-content-between">
<h4 class="mb-sm-0">Gestione Utenti</h4>
<div class="page-title-right">
<a href="school_dashboard.php" class="btn btn-secondary">
<i class="bx bx-arrow-back me-1"></i> Dashboard
</a>
</div>
</div>
</div>
</div>
<!-- MESSAGGI -->
<?php if ($success_message): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<i class="bx bx-check-circle me-2"></i>
<?= $success_message ?>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>
<?php if ($error_message): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<i class="bx bx-error me-2"></i>
<?= htmlspecialchars($error_message) ?>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>
<div class="row">
<!-- FORM AGGIUNGI UTENTE -->
<div class="col-xl-6">
<div class="card radius-10">
<div class="card-header">
<h5 class="mb-0">👤 Aggiungi / Collega Utente</h5>
</div>
<div class="card-body">
<form method="POST">
<input type="hidden" name="action" value="add_or_link_user">
<div class="mb-3">
<label class="form-label fw-bold">Nome <span class="text-danger">*</span></label>
<input type="text" name="first_name" class="form-control" required
placeholder="Mario" maxlength="50">
</div>
<div class="mb-3">
<label class="form-label fw-bold">Cognome <span class="text-danger">*</span></label>
<input type="text" name="last_name" class="form-control" required
placeholder="Rossi" maxlength="50">
</div>
<div class="mb-3">
<label class="form-label fw-bold">Email <span class="text-danger">*</span></label>
<input type="email" name="email" class="form-control" required
placeholder="mario.rossi@email.com" autocomplete="email">
<div class="form-text">Se esiste già lo collega. Altrimenti lo crea.</div>
</div>
<div class="mb-3">
<label class="form-label">Telefono (opzionale)</label>
<input type="tel" name="phone" class="form-control"
placeholder="+39 333 1234567">
</div>
<button type="submit" class="btn btn-primary w-100">
<i class="bx bx-user-plus me-2"></i>
Aggiungi / Collega
</button>
</form>
</div>
</div>
</div>
<!-- STATS RAPIDE -->
<div class="col-xl-6">
<div class="card radius-10">
<div class="card-body text-center">
<h3 class="text-primary mb-1"><?= count($schoolUsers) ?></h3>
<p class="mb-0 text-muted">Utenti associati a <?= htmlspecialchars($school_name) ?></p>
<?php if (count($schoolUsers) > 0): ?>
<small class="text-success">
<i class="bx bx-check-circle"></i>
<?= count(array_filter($schoolUsers, fn($u) => $u['school_status'] === 'active')) ?> attivi
</small>
<?php endif; ?>
</div>
</div>
</div>
</div>
<!-- LISTA UTENTI ASSOCIATI SOLO A QUESTA SCUOLA -->
<div class="card radius-10">
<div class="card-header">
<h5 class="mb-0">👥 Utenti di <?= htmlspecialchars($school_name) ?> (<?= count($schoolUsers) ?>)</h5>
</div>
<div class="card-body">
<?php if (empty($schoolUsers)): ?>
<div class="text-center py-5 text-muted">
<i class="bx bx-user-plus fs-1 mb-3 opacity-50"></i>
<p>Nessun utente associato ancora.</p>
<p class="small">Usa il form qui sopra per aggiungerne uno!</p>
</div>
<?php else: ?>
<div class="table-responsive">
<table class="table table-hover align-middle">
<thead class="table-light">
<tr>
<th>Nome</th>
<th>Email</th>
<th>Telefono</th>
<th>Associato il</th>
<th>Stato Scuola</th>
<th>Email Verificata</th>
</tr>
</thead>
<tbody>
<?php foreach ($schoolUsers as $user): ?>
<tr>
<td>
<strong><?= htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) ?></strong>
</td>
<td>
<small class="text-muted"><?= htmlspecialchars($user['email']) ?></small>
</td>
<td><?= htmlspecialchars($user['phone'] ?: '<span class="text-muted">—</span>') ?></td>
<td>
<small class="text-muted">
<?= date('d/m/Y', strtotime($user['created_at'])) ?>
</small>
</td>
<td>
<span class="badge bg-<?= $user['school_status'] === 'active' ? 'success' : 'warning' ?>">
<?= ucfirst($user['school_status']) ?>
</span>
</td>
<td>
<?= $user['email_verified_at']
? '<span class="badge bg-success"><i class="bx bx-check"></i> Sì</span>'
: '<span class="badge bg-warning">Non ancora</span>' ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
<?php include('include/footer.php'); ?>
</div>
<?php include('jsinclude.php'); ?>
<script>
// Auto-hide alerts dopo 8 secondi
setTimeout(() => {
document.querySelectorAll('.alert').forEach(alert => {
var bsAlert = new bootstrap.Alert(alert);
bsAlert.close();
});
}, 8000);
</script>
</body>
</html>

View File

@ -72,7 +72,9 @@ if (!empty($_SESSION['school_id'])) {
<?= htmlspecialchars($school_display_name) ?>
</div>
</div>
<?php
//menù user
if ((Auth::user()->hasRole('User')) || (Auth::user()->hasRole('Admin'))) : ?>
<li class="menu-label">Utente</li>
<li>
<a href="user_dashboard.php">
@ -112,7 +114,11 @@ if (!empty($_SESSION['school_id'])) {
<div class="menu-title">Impostazioni</div>
</a>
</li>
<?php endif; ?>
<?php
//menù school_owner
if ((Auth::user()->hasRole('school_owner')) || (Auth::user()->hasRole('Admin'))) : ?>
<li class="menu-label">Proprietario Scuola</li>
<li>
<a href="school_dashboard.php">
@ -132,7 +138,11 @@ if (!empty($_SESSION['school_id'])) {
<div class="menu-title">Impostazioni</div>
</a>
</li>
<?php endif; ?>
<?php
//menù admin only
if ((Auth::user()->hasRole('Admin'))) : ?>
<li class="menu-label">Others</li>
<li>
<a href="emplate/index.html" target="_blank">
@ -152,6 +162,7 @@ if (!empty($_SESSION['school_id'])) {
<div class="menu-title">Support</div>
</a>
</li>
<?php endif; ?>
</ul>
<!--end navigation-->

View File

@ -859,9 +859,9 @@ $daily_sessions = $stmt->fetchAll();
<span class="fs-6">Prodotti</span>
</a>
<!-- Pulsante Abbonamenti -->
<a href="#" class="btn btn-info d-flex align-items-center px-3 py-2 shadow-sm rounded" style="min-width: 150px;">
<a href="add_user.php" class="btn btn-info d-flex align-items-center px-3 py-2 shadow-sm rounded" style="min-width: 150px;">
<i class="bx bx-calendar me-2" style="font-size: 20px;"></i>
<span class="fs-6">Abbonamenti</span>
<span class="fs-6">Aggiungi Utente</span>
</a>
<!-- Pulsante Day Off -->
<a href="day_off.php" class="btn btn-danger d-flex align-items-center px-3 py-2 shadow-sm rounded" style="min-width: 150px;">