fixed products

This commit is contained in:
Claudio 2025-12-06 20:11:54 +01:00
parent 279bdd615e
commit 8c5b9a0d85
4 changed files with 641 additions and 290 deletions

View File

@ -663,94 +663,109 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
</div>
</div>
<!-- Modale per aggiungere un prodotto -->
<!-- ================================================================== -->
<!-- MODALE AGGIUNGI PRODOTTO (era mancante!) -->
<!-- ================================================================== -->
<div class="modal fade" id="addProductModal" tabindex="-1" aria-labelledby="addProductModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" style="max-width: 90vw; height: 90vh;">
<div class="modal-content d-flex flex-column" style="height: 100%;">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addProductModalLabel">Aggiungi Nuovo Prodotto</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form action="" method="POST">
<div class="modal-body">
<input type="hidden" name="action" value="add_product">
<div class="row">
<div class="col-md-6 mb-3">
<label for="add_product_name" class="form-label">Nome Prodotto</label>
<input type="text" class="form-control" id="add_product_name" name="name" required>
<div class="row g-3">
<div class="col-md-6">
<label class="form-label">Nome Prodotto <span class="text-danger">*</span></label>
<input type="text" class="form-control" name="name" required>
</div>
<div class="col-md-6 mb-3">
<label for="add_product_variation_name" class="form-label">Nome Variazione</label>
<input type="text" class="form-control" id="add_product_variation_name" name="variation_name" required placeholder="Es. 5 Ingressi">
<div class="col-md-6">
<label class="form-label">Nome Variazione <span class="text-danger">*</span></label>
<input type="text" class="form-control" name="variation_name" required placeholder="es. 10 ingressi">
</div>
<div class="col-md-6 mb-3">
<label for="add_product_type" class="form-label">Tipo</label>
<select class="form-control" id="add_product_type" name="type" required>
<div class="col-md-6">
<label class="form-label">Tipo <span class="text-danger">*</span></label>
<select class="form-select" name="type" required>
<option value="carnet">Carnet</option>
<option value="subscription">Abbonamento</option>
<option value="drop_in">Lezione Singola</option>
</select>
</div>
<div class="col-md-6 mb-3">
<label for="add_product_price" class="form-label">Prezzo ()</label>
<input type="number" step="0.01" class="form-control" id="add_product_price" name="price" required>
<div class="col-md-6">
<label class="form-label">Prezzo () <span class="text-danger">*</span></label>
<input type="number" step="0.01" class="form-control" name="price" required>
</div>
<div class="col-md-6 mb-3">
<label for="add_product_duration_days" class="form-label">Durata (giorni)</label>
<input type="number" class="form-control" id="add_product_duration_days" name="duration_days">
<small class="form-text text-muted">Lascia vuoto per lezioni singole.</small>
<div class="col-md-6">
<label class="form-label">Durata (giorni)</label>
<input type="number" class="form-control" name="duration_days">
<small class="text-muted">Lascia vuoto per lezioni singole</small>
</div>
<div class="col-md-6 mb-3">
<label for="add_product_max_entries" class="form-label">Numero Massimo di Ingressi</label>
<input type="number" class="form-control" id="add_product_max_entries" name="max_entries">
<small class="form-text text-muted">Lascia vuoto per abbonamenti illimitati.</small>
<div class="col-md-6">
<label class="form-label">Max Ingressi</label>
<input type="number" class="form-control" name="max_entries">
<small class="text-muted">Lascia vuoto per abbonamenti illimitati</small>
</div>
<div class="col-md-6 mb-3">
<label for="add_product_weekly_limit" class="form-label">Limite Settimanale</label>
<input type="number" class="form-control" id="add_product_weekly_limit" name="weekly_limit">
<small class="form-text text-muted">Lascia vuoto se non applicabile.</small>
<div class="col-md-6">
<label class="form-label">Limite settimanale</label>
<input type="number" class="form-control" name="weekly_limit">
</div>
<div class="col-md-6 mb-3">
<label for="add_product_max_recoveries" class="form-label">Numero Massimo di Recuperi</label>
<input type="number" class="form-control" id="add_product_max_recoveries" name="max_recoveries">
<small class="form-text text-muted">Lascia vuoto se non applicabile.</small>
<div class="col-md-6">
<label class="form-label">Max Recuperi</label>
<input type="number" class="form-control" name="max_recoveries">
</div>
<div class="col-md-6 mb-3">
<label for="add_product_recovery_validity_days" class="form-label">Validità Recuperi (giorni)</label>
<input type="number" class="form-control" id="add_product_recovery_validity_days" name="recovery_validity_days">
<small class="form-text text-muted">Lascia vuoto se non applicabile.</small>
<div class="col-md-6">
<label class="form-label">Validità recuperi (giorni)</label>
<input type="number" class="form-control" name="recovery_validity_days">
</div>
<div class="col-md-6 mb-3">
<label for="add_product_max_inventory" class="form-label">Inventario Massimo</label>
<input type="number" class="form-control" id="add_product_max_inventory" name="max_inventory">
<small class="form-text text-muted">Lascia vuoto per illimitato.</small>
<div class="col-md-6">
<label class="form-label">Inventario massimo</label>
<input type="number" class="form-control" name="max_inventory">
</div>
<div class="col-md-6 mb-3">
<label for="add_product_allow_freeze" class="form-label">Permetti Congelamento</label>
<select class="form-control" id="add_product_allow_freeze" name="allow_freeze">
<div class="col-md-6">
<label class="form-label">Permetti congelamento</label>
<select class="form-select" name="allow_freeze">
<option value="0">No</option>
<option value="1"></option>
</select>
</div>
<div class="col-md-6 mb-3">
<label for="add_product_freeze_max_days" class="form-label">Giorni Massimi di Congelamento</label>
<input type="number" class="form-control" id="add_product_freeze_max_days" name="freeze_max_days">
<small class="form-text text-muted">Lascia vuoto se non applicabile.</small>
<div class="col-md-6">
<label class="form-label">Giorni max congelamento</label>
<input type="number" class="form-control" name="freeze_max_days">
</div>
<div class="col-md-6 mb-3">
<label for="add_product_is_full_access" class="form-label">Accesso Completo</label>
<select class="form-control" id="add_product_is_full_access" name="is_full_access">
<div class="col-md-6">
<label class="form-label">Accesso completo a tutte le classi</label>
<select class="form-select" id="add_product_is_full_access" name="is_full_access" onchange="toggleClassTypesSection(this.value, 'add')">
<option value="0">No</option>
<option value="1"></option>
</select>
<small class="form-text text-muted">Se , il prodotto accesso a tutte le classi.</small>
</div>
<div class="col-md-6 mb-3">
<label for="add_product_auto_propagate" class="form-label">Propaga in Automatico all'Ordine</label>
<select class="form-control" id="add_product_auto_propagate" name="auto_propagate_to_order">
<div class="col-md-6">
<label class="form-label">Propaga automaticamente all'ordine</label>
<select class="form-select" name="auto_propagate_to_order">
<option value="0">No</option>
<option value="1"></option>
</select>
<small class="form-text text-muted">Se , il prodotto verrà aggiunto automaticamente agli ordini futuri.</small>
</div>
<div class="col-md-12 mb-3" id="add_class_types_section">
<label class="form-label">Classi e Variazioni Associate</label>
<!-- SEZIONE CLASSI (nascondibile) -->
<div class="col-12" id="add_class_types_section">
<label class="form-label">Classi e orari associati</label>
<div class="border rounded p-3" style="max-height: 300px; overflow-y: auto;">
<?php foreach ($all_classes as $class_id => $class): ?>
<div class="form-check">
<input class="form-check-input class-checkbox" type="checkbox" id="add_class_<?php echo $class_id; ?>" data-class-id="<?php echo $class_id; ?>">
<label class="form-check-label" for="add_class_<?php echo $class_id; ?>">
<label class="form-check-label fw-bold" for="add_class_<?php echo $class_id; ?>">
<?php echo htmlspecialchars($class['name']); ?>
</label>
<?php if (!empty($class['variations'])): ?>
@ -770,11 +785,25 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annulla</button>
<button type="submit" class="btn btn-primary">Crea Prodotto</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Modale per aggiungere una variazione a un prodotto esistente -->
<!-- Modale per aggiungere una variazione a un prodotto esistente -->
<div class="modal fade" id="addVariationModal" tabindex="-1" aria-labelledby="addVariationModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-dialog modal-dialog-centered" style="max-width: 90vw; height: 90vh;">
<div class="modal-content d-flex flex-column" style="height: 100%;">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addVariationModalLabel">Aggiungi Variazione</h5>
@ -881,6 +910,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
</div>
</div>
</div>
</div>
<!-- Modale per modificare un prodotto -->
<div class="modal fade" id="editProductModal" tabindex="-1" aria-labelledby="editProductModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">

View File

@ -0,0 +1,135 @@
<?php
require_once 'include/headscript.php'; // Include il file con la connessione al database
// Connessione al database
$dbHandler = DBHandlerSelect::getInstance();
$pdo = $dbHandler->getConnection();
try {
// Inizia una transazione
$pdo->beginTransaction();
// Seleziona gli ordini con status 'completed' e lezioni disponibili
$stmt = $pdo->prepare("
SELECT o.id, o.user_id, o.class_type_id, o.available_entries, o.school_id
FROM orders o
WHERE o.status = 'completed' AND o.available_entries > 0
");
$stmt->execute();
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
$bookings_created = 0;
$orders_propagated = 0;
foreach ($orders as $order) {
$order_id = $order['id'];
$user_id = $order['user_id'];
$class_type_id = $order['class_type_id'];
$available_entries = $order['available_entries'];
$school_id = $order['school_id'];
// Recupera i giorni di chiusura della scuola
$offStmt = $pdo->prepare("
SELECT start_date, end_date
FROM day_off
WHERE school_id = ? AND (
(start_date >= CURDATE()) OR
(end_date >= CURDATE()) OR
(start_date <= CURDATE() AND end_date >= CURDATE())
)
");
$offStmt->execute([$school_id]);
$off_periods = $offStmt->fetchAll(PDO::FETCH_ASSOC);
// Crea un array di date di chiusura
$off_dates = [];
foreach ($off_periods as $period) {
$start_date = new DateTime($period['start_date']);
$end_date = new DateTime($period['end_date']);
$interval = new DateInterval('P1D');
$date_range = new DatePeriod($start_date, $interval, $end_date->modify('+1 day'));
foreach ($date_range as $date) {
$off_dates[] = $date->format('Y-m-d');
}
}
// Trova le prossime sessioni disponibili per questo class_type_id
$sessionStmt = $pdo->prepare("
SELECT id, session_date
FROM class_sessions
WHERE class_type_id = ? AND session_date >= CURDATE() AND status = 'scheduled'
ORDER BY session_date ASC, start_time ASC
LIMIT ?
");
$sessionStmt->execute([$class_type_id, $available_entries]);
$sessions = $sessionStmt->fetchAll(PDO::FETCH_ASSOC);
$bookings_for_order = 0;
foreach ($sessions as $session) {
$session_id = $session['id'];
$session_date = $session['session_date'];
// Salta se la data è un giorno di chiusura
if (in_array($session_date, $off_dates)) {
continue;
}
// Verifica la capacità massima della sessione
$capacityStmt = $pdo->prepare("
SELECT max_capacity
FROM class_sessions
WHERE id = ?
");
$capacityStmt->execute([$session_id]);
$max_capacity = $capacityStmt->fetchColumn();
$bookingCountStmt = $pdo->prepare("
SELECT COUNT(*)
FROM session_bookings
WHERE session_id = ? AND status IN ('booked', 'attended', 'rescheduled')
");
$bookingCountStmt->execute([$session_id]);
$current_bookings = $bookingCountStmt->fetchColumn();
if ($max_capacity !== null && $current_bookings >= $max_capacity) {
continue; // Salta se la sessione è piena
}
// Inserisci la prenotazione in session_bookings
$insertStmt = $pdo->prepare("
INSERT INTO session_bookings (
session_id, user_id, status, booked_at, created_at, updated_at
)
VALUES (?, ?, 'booked', NOW(), NOW(), NOW())
");
$insertStmt->execute([
$session_id,
$user_id
]);
$bookings_created++;
$bookings_for_order++;
}
// Aggiorna available_entries e lo stato dell'ordine
if ($bookings_for_order > 0) {
$updateStmt = $pdo->prepare("
UPDATE orders
SET available_entries = available_entries - ?,
status = 'propagated'
WHERE id = ?
");
$updateStmt->execute([$bookings_for_order, $order_id]);
$orders_propagated++;
}
}
// Conferma la transazione
$pdo->commit();
echo "Propagazione completata con successo: $bookings_created prenotazioni create, $orders_propagated ordini aggiornati.";
} catch (PDOException $e) {
// In caso di errore, annulla la transazione
$pdo->rollBack();
echo "Errore durante la propagazione: " . $e->getMessage();
}

View File

@ -449,9 +449,9 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
} else {
// Verifica che la variazione appartenga alla scuola
$stmt = $pdo->prepare("
SELECT day_of_week, start_time, typical_duration, teacher_id
FROM class_types
WHERE id = ? AND school_id = ?
SELECT ct.day_of_week, ct.start_time, ct.typical_duration, ct.teacher_id, ct.class_id, ct.school_id, ct.max_capacity, ct.notes
FROM class_types ct
WHERE ct.id = ? AND ct.school_id = ?
");
$stmt->execute([$class_type_id, $school_id]);
$variation = $stmt->fetch();
@ -519,45 +519,89 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$end_date_dt = new DateTime($end_date);
$end_date_dt->setTime(23, 59, 59); // Include l'ultimo giorno
// Prepara la query per verificare se una sessione esiste già
$checkStmt = $pdo->prepare("
SELECT id
FROM class_sessions
WHERE class_type_id = ? AND session_date = ?
");
// Prepara la query di inserimento
$stmt = $pdo->prepare("
INSERT INTO class_sessions (class_type_id, session_date, start_time, end_time, teacher_id, status, propagation_id)
VALUES (?, ?, ?, ?, ?, 'scheduled', ?)
");
INSERT INTO class_sessions (class_id, school_id, class_type_id, session_date, start_time, end_time, teacher_id, max_capacity, notes, status, propagation_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'scheduled', ?)
");
$sessions_created = 0;
$sessions_skipped = 0;
while ($current_date <= $end_date_dt) {
$day_of_week = $current_date->format('l'); // Giorno della settimana in inglese (es. Monday)
$day_of_week = $current_date->format('l');
$current_date_str = $current_date->format('Y-m-d');
// Verifica se il giorno è un giorno di chiusura e se corrisponde al giorno della settimana della variazione
if (!in_array($current_date_str, $off_dates) && $day_of_week === $day_of_week_english) {
$session_date = $current_date->format('Y-m-d');
$start_time_str = $start_time->format('H:i:s');
$end_time_str = $end_time->format('H:i:s');
// Verifica se una sessione esiste già per questa variazione e data
$checkStmt->execute([$class_type_id, $session_date]);
if ($checkStmt->fetch()) {
$sessions_skipped++;
continue; // Salta se esiste già
}
try {
$stmt->execute([
$variation['class_id'],
$variation['school_id'],
$class_type_id,
$session_date,
$start_time_str,
$end_time_str,
$variation['teacher_id'],
$variation['max_capacity'],
$variation['notes'],
$propagation_id
]);
$sessions_created++;
} catch (PDOException $e) {
// Ignora errori di chiave unica (sessioni già esistenti)
if ($e->getCode() != 23000) {
$error = "Errore durante la propagazione delle sessioni: " . $e->getMessage();
break;
}
}
}
$current_date->modify('+1 day');
}
if (!isset($error)) {
$success_message = "Propagate $sessions_created sessioni con successo! (Saltate $sessions_skipped sessioni già esistenti) (ID Propagazione: $propagation_id)";
echo "<script>
document.addEventListener('DOMContentLoaded', function() {
var successModalElement = document.getElementById('successPropagationModal');
var successModal = new bootstrap.Modal(successModalElement, { backdrop: true });
document.getElementById('successPropagationMessage').innerText = '$success_message';
successModal.show();
setTimeout(function() {
successModal.hide();
// Rimuove il backdrop manualmente
document.querySelector('.modal-backdrop')?.remove();
document.body.classList.remove('modal-open');
document.body.style.overflow = 'auto'; // Ripristina lo scroll
// Reindirizza dopo la chiusura del modale
window.location.href = 'school_dashboard.php';
}, 3000); // Chiude il modale dopo 3 secondi
});
</script>";
}
if (!isset($error)) {
$success_message = "Propagate $sessions_created sessioni con successo! (ID Propagazione: $propagation_id)";
echo "<script>
document.addEventListener('DOMContentLoaded', function() {
var successModal = new bootstrap.Modal(document.getElementById('successPropagationModal'), {});
document.getElementById('successPropagationMessage').innerText = '$success_message';
successModal.show();
});
</script>";
}
}
}
@ -664,9 +708,8 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
}
}
}
// Reindirizza per evitare il doppio invio del form
header("Location: school_dashboard.php");
exit;
// Non Reindirizza per evitare il doppio invio del form
}
}
@ -847,11 +890,6 @@ $daily_sessions = $stmt->fetchAll();
</div>
</div>
<div class="card-body">
<?php if (isset($success_message)): ?>
<div class="alert alert-success" role="alert">
<?php echo $success_message; ?>
</div>
<?php endif; ?>
<?php if (isset($error)): ?>
<div class="alert alert-danger" role="alert">
<?php echo $error; ?>
@ -1553,6 +1591,23 @@ $daily_sessions = $stmt->fetchAll();
</div>
</div>
</div>
<!-- Modale per il messaggio di successo della propagazione -->
<div class="modal fade" id="successPropagationModal" tabindex="-1" aria-labelledby="successPropagationModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="successPropagationModalLabel">Propagazione Completata</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p id="successPropagationMessage"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-bs-dismiss="modal">Chiudi</button>
</div>
</div>
</div>
</div>
<div class="overlay toggle-icon"></div>
<a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
<?php include('include/footer.php'); ?>

View File

@ -221,7 +221,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
?>
<!doctype html>
<html lang="en">
<html lang="it">
<head>
<meta charset="utf-8">
@ -229,12 +229,29 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
<?php include('cssinclude.php'); ?>
<?php include('siteinfo.php'); ?>
<!-- Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
integrity="sha256-sA+Zcx6cNpCzIvJczQqny0Sg0r7GDL2wMpN4k1kJ0fPQ=" crossorigin="" />
<style>
#map {
height: 350px;
border-radius: 10px;
margin-top: 15px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}
.geocode-btn {
margin-top: 10px;
}
</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">
@ -242,115 +259,165 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
<h6 class="mb-0"><?php echo $is_new ? 'Crea Profilo Scuola' : 'Profilo Scuola'; ?></h6>
</div>
<div class="card-body">
<?php if (isset($success_message)): ?>
<div class="alert alert-success" role="alert">
<?php echo $success_message; ?>
</div>
<div class="alert alert-success"><?php echo $success_message; ?></div>
<?php endif; ?>
<?php if (isset($error)): ?>
<div class="alert alert-danger" role="alert">
<?php echo $error; ?>
</div>
<div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?>
<form method="POST" enctype="multipart/form-data">
<div class="row">
<!-- Colonna sinistra: logo -->
<div class="col-md-4 text-center">
<div class="mb-3">
<img src="<?php echo $school['logo'] ? htmlspecialchars($school['logo']) : 'photoschool/ndphoto.png'; ?>"
alt="Logo Scuola" class="img-fluid rounded-circle" style="width: 150px; height: 150px; object-fit: cover;">
alt="Logo" class="img-fluid rounded-circle"
style="width:150px;height:150px;object-fit:cover;">
</div>
<div class="mb-3">
<label for="logo" class="form-label">Carica nuovo logo</label>
<input type="file" class="form-control" id="logo" name="logo" accept="image/*">
</div>
</div>
<!-- Colonna destra: tutti i campi -->
<div class="col-md-8">
<!-- Nome, slug, ecc... (tutto invariato fino all'indirizzo) -->
<div class="mb-3">
<label for="name" class="form-label">Nome Scuola</label>
<input type="text" class="form-control" id="name" name="name" value="<?php echo htmlspecialchars($school['name'] ?? ''); ?>" required>
<input type="text" class="form-control" id="name" name="name"
value="<?php echo htmlspecialchars($school['name'] ?? ''); ?>" required>
</div>
<div class="mb-3">
<label for="slug" class="form-label">Slug (URL personalizzato, es. yogiboook.com/slug)</label>
<input type="text" class="form-control" id="slug" name="slug" value="<?php echo htmlspecialchars($school['slug'] ?? ''); ?>" required>
<small class="form-text text-muted">Usa solo lettere minuscole, numeri e trattini (es. yoga-milano).</small>
<label for="slug" class="form-label">Slug (URL personalizzato)</label>
<input type="text" class="form-control" id="slug" name="slug"
value="<?php echo htmlspecialchars($school['slug'] ?? ''); ?>" required>
<small class="text-muted">es. yoga-milano</small>
</div>
<div class="mb-3">
<label for="website" class="form-label">Sito Web</label>
<input type="url" class="form-control" id="website" name="website" value="<?php echo htmlspecialchars($school['website'] ?? ''); ?>">
<input type="url" class="form-control" id="website" name="website"
value="<?php echo htmlspecialchars($school['website'] ?? ''); ?>">
</div>
<div class="mb-3">
<label for="email" class="form-label">Email Scuola</label>
<input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($school['email'] ?? ''); ?>" required>
<input type="email" class="form-control" id="email" name="email"
value="<?php echo htmlspecialchars($school['email'] ?? ''); ?>" required>
</div>
<div class="mb-3">
<label for="phone" class="form-label">Telefono</label>
<input type="text" class="form-control" id="phone" name="phone" value="<?php echo htmlspecialchars($school['phone'] ?? ''); ?>">
<input type="text" class="form-control" id="phone" name="phone"
value="<?php echo htmlspecialchars($school['phone'] ?? ''); ?>">
</div>
<div class="mb-3">
<label for="description" class="form-label">Descrizione</label>
<textarea class="form-control" id="description" name="description" rows="3"><?php echo htmlspecialchars($school['description'] ?? ''); ?></textarea>
</div>
<!-- ==================== INIZIO INDIRIZZO + MAPPA ==================== -->
<div class="mb-3">
<label for="address_street" class="form-label">Via</label>
<input type="text" class="form-control" id="address_street" name="address_street" value="<?php echo htmlspecialchars($school['address_street'] ?? ''); ?>">
<label for="address_street" class="form-label">Via / Numero civico</label>
<input type="text" class="form-control" id="address_street" name="address_street"
value="<?php echo htmlspecialchars($school['address_street'] ?? ''); ?>">
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="address_city" class="form-label">Città</label>
<input type="text" class="form-control" id="address_city" name="address_city" value="<?php echo htmlspecialchars($school['address_city'] ?? ''); ?>">
<input type="text" class="form-control" id="address_city" name="address_city"
value="<?php echo htmlspecialchars($school['address_city'] ?? ''); ?>">
</div>
<div class="col-md-6 mb-3">
<label for="address_postal_code" class="form-label">CAP</label>
<input type="text" class="form-control" id="address_postal_code" name="address_postal_code" value="<?php echo htmlspecialchars($school['address_postal_code'] ?? ''); ?>">
<input type="text" class="form-control" id="address_postal_code" name="address_postal_code"
value="<?php echo htmlspecialchars($school['address_postal_code'] ?? ''); ?>">
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="address_province" class="form-label">Provincia</label>
<input type="text" class="form-control" id="address_province" name="address_province" value="<?php echo htmlspecialchars($school['address_province'] ?? ''); ?>">
<input type="text" class="form-control" id="address_province" name="address_province"
value="<?php echo htmlspecialchars($school['address_province'] ?? ''); ?>">
</div>
<div class="col-md-6 mb-3">
<label for="address_country" class="form-label">Nazione</label>
<input type="text" class="form-control" id="address_country" name="address_country" value="<?php echo htmlspecialchars($school['address_country'] ?? ''); ?>">
<input type="text" class="form-control" id="address_country" name="address_country"
value="<?php echo htmlspecialchars($school['address_country'] ?? 'Italia'); ?>">
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<!-- Pulsante geocoding -->
<div class="mb-3">
<button type="button" class="btn btn-outline-primary geocode-btn" id="geocode-btn">
Cerca sulla mappa
</button>
<small class="text-muted d-block">Compila via + città + CAP clicca qui</small>
</div>
<!-- Mappa -->
<div id="map"></div>
<!-- Latitudine e Longitudine (readonly ma modificabili manualmente se serve) -->
<div class="row mt-3">
<div class="col-md-6">
<label for="latitude" class="form-label">Latitudine</label>
<input type="number" step="any" class="form-control" id="latitude" name="latitude" value="<?php echo htmlspecialchars($school['latitude'] ?? ''); ?>">
<input type="text" class="form-control" id="latitude" name="latitude"
value="<?php echo htmlspecialchars($school['latitude'] ?? ''); ?>" readonly>
</div>
<div class="col-md-6 mb-3">
<div class="col-md-6">
<label for="longitude" class="form-label">Longitudine</label>
<input type="number" step="any" class="form-control" id="longitude" name="longitude" value="<?php echo htmlspecialchars($school['longitude'] ?? ''); ?>">
<input type="text" class="form-control" id="longitude" name="longitude"
value="<?php echo htmlspecialchars($school['longitude'] ?? ''); ?>" readonly>
</div>
</div>
<!-- ==================== FINE INDIRIZZO + MAPPA ==================== -->
<hr class="my-4">
<div class="mb-3">
<label for="owner_name" class="form-label">Nome Proprietario</label>
<input type="text" class="form-control" id="owner_name" name="owner_name" value="<?php echo htmlspecialchars($school['owner_name'] ?? ''); ?>">
<input type="text" class="form-control" id="owner_name" name="owner_name"
value="<?php echo htmlspecialchars($school['owner_name'] ?? ''); ?>">
</div>
<div class="mb-3">
<label for="vat_number" class="form-label">Partita IVA</label>
<input type="text" class="form-control" id="vat_number" name="vat_number" value="<?php echo htmlspecialchars($school['vat_number'] ?? ''); ?>">
<input type="text" class="form-control" id="vat_number" name="vat_number"
value="<?php echo htmlspecialchars($school['vat_number'] ?? ''); ?>">
</div>
<div class="mb-3">
<label for="status" class="form-label">Stato</label>
<select class="form-control" id="status" name="status">
<option value="active" <?php echo $school['status'] === 'active' ? 'selected' : ''; ?>>Attivo</option>
<option value="inactive" <?php echo $school['status'] === 'inactive' ? 'selected' : ''; ?>>Inattivo</option>
<option value="suspended" <?php echo $school['status'] === 'suspended' ? 'selected' : ''; ?>>Sospeso</option>
<option value="active" <?php echo ($school['status'] ?? '') === 'active' ? 'selected' : ''; ?>>Attivo</option>
<option value="inactive" <?php echo ($school['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inattivo</option>
<option value="suspended" <?php echo ($school['status'] ?? '') === 'suspended' ? 'selected' : ''; ?>>Sospeso</option>
</select>
</div>
<?php if (!$is_new): ?>
<div class="mb-3">
<label class="form-label">Data Creazione</label>
<input type="text" class="form-control" value="<?php echo htmlspecialchars($school['created_at']); ?>" readonly>
<label class="form-label">Creato il</label>
<input type="text" class="form-control" value="<?php echo htmlspecialchars($school['created_at'] ?? ''); ?>" readonly>
</div>
<div class="mb-3">
<label class="form-label">Ultimo Aggiornamento</label>
<input type="text" class="form-control" value="<?php echo htmlspecialchars($school['updated_at']); ?>" readonly>
<label class="form-label">Ultimo aggiornamento</label>
<input type="text" class="form-control" value="<?php echo htmlspecialchars($school['updated_at'] ?? ''); ?>" readonly>
</div>
<?php endif; ?>
<button type="submit" class="btn btn-primary"><?php echo $is_new ? 'Crea Profilo' : 'Salva Modifiche'; ?></button>
<button type="submit" class="btn btn-primary btn-lg">
<?php echo $is_new ? 'Crea Profilo' : 'Salva Modifiche'; ?>
</button>
</div>
</div>
</form>
@ -358,49 +425,113 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
</div>
</div>
</div>
<div class="overlay toggle-icon"></div>
<a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
<?php include('include/footer.php'); ?>
</div>
<?php include('jsinclude.php'); ?>
<!-- Script per validazione e suggerimento dello slug -->
<!-- Leaflet JS -->
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
integrity="sha256-o9N1j3Z3B9n0nN2V3H7N7X8z0z1k6p3c1F0L5g0B6p8=" crossorigin=""></script>
<script>
// Funzione per generare uno slug valido
function generateSlug(string) {
return string
.toLowerCase() // Converti in minuscolo
.replace(/[^a-z0-9-]+/g, '-') // Sostituisci caratteri non validi con trattini
.replace(/-+/g, '-') // Rimuovi trattini multipli
.replace(/^-|-$/g, ''); // Rimuovi trattini all'inizio e alla fine
let map, marker;
// Inizializza la mappa
function initMap(lat = 41.9028, lng = 12.4964, zoom = 5) {
if (map) map.remove();
map = L.map('map').setView([lat, lng], zoom);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; OpenStreetMap contributors'
}).addTo(map);
marker = L.marker([lat, lng], {
draggable: true
}).addTo(map);
marker.on('dragend', function() {
const pos = marker.getLatLng();
document.getElementById('latitude').value = pos.lat.toFixed(8);
document.getElementById('longitude').value = pos.lng.toFixed(8);
});
}
// Riferimenti ai campi
// Aggiorna mappa e campi
function updateMap(lat, lng) {
document.getElementById('latitude').value = lat.toFixed(8);
document.getElementById('longitude').value = lng.toFixed(8);
map.setView([lat, lng], 16);
if (marker) marker.setLatLng([lat, lng]);
}
// Geocoding con Nominatim
document.getElementById('geocode-btn').addEventListener('click', function() {
const street = document.getElementById('address_street').value.trim();
const city = document.getElementById('address_city').value.trim();
const cap = document.getElementById('address_postal_code').value.trim();
const country = document.getElementById('address_country').value.trim() || 'Italia';
if (!street || !city) {
alert('Inserisci almeno Via e Città');
return;
}
const query = `${street}, ${city}${cap ? ' ' + cap : ''}, ${country}`;
const url = `https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(query)}&limit=1`;
fetch(url)
.then(r => r.json())
.then(data => {
if (data && data.length > 0) {
const r = data[0];
updateMap(parseFloat(r.lat), parseFloat(r.lon));
} else {
alert('Indirizzo non trovato. Controlla i dati.');
}
})
.catch(() => alert('Errore di rete. Riprova.'));
});
// Al caricamento della pagina
document.addEventListener('DOMContentLoaded', function() {
const lat = document.getElementById('latitude').value;
const lng = document.getElementById('longitude').value;
if (lat && lng) {
initMap(parseFloat(lat), parseFloat(lng), 16);
} else {
initMap(); // Italia centrata
}
});
/* Slug automatico (il tuo codice originale invariato) */
const nameInput = document.getElementById('name');
const slugInput = document.getElementById('slug');
let isUserTypingSlug = false; // Flag per tracciare se l'utente sta modificando lo slug manualmente
let isUserTypingSlug = false;
// Suggerimento dello slug basato sul nome
nameInput.addEventListener('input', function(e) {
if (!isUserTypingSlug) { // Aggiorna lo slug solo se l'utente non lo sta modificando manualmente
const name = e.target.value;
const generatedSlug = generateSlug(name);
slugInput.value = generatedSlug;
function generateSlug(str) {
return str.toLowerCase()
.replace(/[^a-z0-9-]+/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '');
}
nameInput?.addEventListener('input', function() {
if (!isUserTypingSlug) {
slugInput.value = generateSlug(this.value);
}
});
// Validazione dello slug in tempo reale
slugInput.addEventListener('input', function(e) {
isUserTypingSlug = true; // L'utente sta modificando lo slug manualmente
let value = e.target.value;
value = generateSlug(value); // Applica le regole di validazione
e.target.value = value; // Aggiorna il campo con il valore validato
slugInput?.addEventListener('input', function(e) {
isUserTypingSlug = true;
this.value = generateSlug(this.value);
});
// Ripristina il flag quando l'utente smette di modificare lo slug
slugInput.addEventListener('blur', function() {
isUserTypingSlug = false; // L'utente ha finito di modificare lo slug
});
slugInput?.addEventListener('blur', () => isUserTypingSlug = false);
</script>
</body>