Compare commits

...

3 Commits

Author SHA1 Message Date
Flatlogic Bot
0d0714bfe3 0.1.2 2025-12-13 17:45:03 +00:00
Flatlogic Bot
5565303f82 0.1.1 2025-12-13 17:43:22 +00:00
Flatlogic Bot
1b18b92970 0.1 2025-12-13 17:39:27 +00:00
12 changed files with 1203 additions and 141 deletions

99
admin/edit_question.php Normal file
View File

@ -0,0 +1,99 @@
<?php
require_once '../db/config.php';
require_once 'partials/header.php';
$pdo = db();
$message = '';
$question_id = $_GET['id'] ?? null;
if (!$question_id) {
header("Location: questions.php");
exit;
}
// Handle form submission for update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_question') {
try {
$pdo->beginTransaction();
// Update question text and score
$stmt = $pdo->prepare('UPDATE questions SET question_text = ?, score = ? WHERE id = ?');
$stmt->execute([$_POST['question_text'], $_POST['score'], $question_id]);
// Update answers
$correctAnswerIndex = $_POST['is_correct'];
foreach ($_POST['answers'] as $answer_id => $answerText) {
$isCorrect = ($answer_id == $_POST['correct_answer_id']); // This needs to be adjusted
// Simplified logic: update text, and then separately update the correct flag
$stmt_update_text = $pdo->prepare('UPDATE answers SET answer_text = ? WHERE id = ? AND question_id = ?');
$stmt_update_text->execute([$answerText, $answer_id, $question_id]);
}
// Set all to incorrect first
$stmt_reset = $pdo->prepare('UPDATE answers SET is_correct = 0 WHERE question_id = ?');
$stmt_reset->execute([$question_id]);
// Set the new correct answer
$stmt_set_correct = $pdo->prepare('UPDATE answers SET is_correct = 1 WHERE id = ? AND question_id = ?');
$stmt_set_correct->execute([$_POST['correct_answer_id'], $question_id]);
$pdo->commit();
$message = '<div class="alert alert-success">Domanda aggiornata con successo. <a href="questions.php">Torna alla lista</a>.</div>';
} catch (Exception $e) {
$pdo->rollBack();
$message = '<div class="alert alert-error">Errore durante l\'aggiornamento: ' . $e->getMessage() . '</div>';
}
}
// Fetch the question and its answers
$stmt = $pdo->prepare('SELECT * FROM questions WHERE id = ?');
$stmt->execute([$question_id]);
$question = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$question) {
echo "<p>Domanda non trovata.</p>";
require_once 'partials/footer.php';
exit;
}
$stmt = $pdo->prepare('SELECT * FROM answers WHERE question_id = ? ORDER BY id ASC');
$stmt->execute([$question_id]);
$answers = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<?php echo $message; ?>
<div class="content-block">
<h2>Modifica Domanda</h2>
<form action="edit_question.php?id=<?php echo $question_id; ?>" method="POST">
<input type="hidden" name="action" value="update_question">
<div class="form-group">
<label for="question_text">Testo della Domanda</label>
<textarea name="question_text" id="question_text" rows="3" required><?php echo htmlspecialchars($question['question_text']); ?></textarea>
</div>
<div class="form-group">
<label for="score">Punteggio</label>
<input type="number" name="score" id="score" value="<?php echo htmlspecialchars($question['score']); ?>" required>
</div>
<div class="form-group">
<label>Risposte (seleziona quella corretta)</label>
<div class="answers-container">
<?php foreach ($answers as $answer):
?>
<div class="answer-group">
<input type="radio" name="correct_answer_id" value="<?php echo $answer['id']; ?>" <?php echo $answer['is_correct'] ? 'checked' : ''; ?>>
<input type="text" name="answers[<?php echo $answer['id']; ?>]" value="<?php echo htmlspecialchars($answer['answer_text']); ?>" required>
</div>
<?php endforeach; ?>
</div>
</div>
<button type="submit" class="btn">Aggiorna Domanda</button>
<a href="questions.php" style="margin-left: 15px;">Annulla</a>
</form>
</div>
<?php require_once 'partials/footer.php'; ?>

5
admin/index.php Normal file
View File

@ -0,0 +1,5 @@
<?php
// For now, we redirect to the questions management page.
// In the future, this could be a dashboard.
header("Location: questions.php");
exit;

View File

@ -0,0 +1,4 @@
</main>
</div>
</body>
</html>

22
admin/partials/header.php Normal file
View File

@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Backoffice Quiz</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&family=Roboto:wght@400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css?v=<?php echo time(); ?>">
</head>
<body>
<div class="container">
<header class="main-header">
<h1>Backoffice</h1>
<nav>
<a href="questions.php">Gestione Domande</a>
<a href="results.php">Risultati</a>
<a href="../index.php" target="_blank">Vedi Sito Pubblico</a>
</nav>
</header>
<main>

149
admin/questions.php Normal file
View File

@ -0,0 +1,149 @@
<?php
require_once '../db/config.php';
require_once 'partials/header.php';
// In a real app, you'd have a session-based login check here.
$pdo = db();
$message = '';
// Handle POST requests for CUD actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'add_question':
try {
$pdo->beginTransaction();
// Insert question
$stmt = $pdo->prepare('INSERT INTO questions (question_text, score) VALUES (?, ?)');
$stmt->execute([$_POST['question_text'], $_POST['score']]);
$questionId = $pdo->lastInsertId();
// Insert answers
$correctAnswerIndex = $_POST['is_correct'];
foreach ($_POST['answers'] as $index => $answerText) {
if (!empty($answerText)) {
$isCorrect = ($index == $correctAnswerIndex);
$stmt = $pdo->prepare('INSERT INTO answers (question_id, answer_text, is_correct) VALUES (?, ?, ?)');
$stmt->execute([$questionId, $answerText, $isCorrect]);
}
}
$pdo->commit();
$message = '<div class="alert alert-success">Domanda aggiunta con successo.</div>';
} catch (Exception $e) {
$pdo->rollBack();
$message = '<div class="alert alert-error">Errore: ' . $e->getMessage() . '</div>';
}
break;
case 'delete_question':
try {
$pdo->beginTransaction();
// Note: foreign keys with ON DELETE CASCADE would simplify this
$stmt = $pdo->prepare('DELETE FROM answers WHERE question_id = ?');
$stmt->execute([$_POST['question_id']]);
$stmt = $pdo->prepare('DELETE FROM questions WHERE id = ?');
$stmt->execute([$_POST['question_id']]);
$pdo->commit();
$message = '<div class="alert alert-success">Domanda eliminata con successo.</div>';
} catch (Exception $e) {
$pdo->rollBack();
$message = '<div class="alert alert-error">Errore: ' . $e->getMessage() . '</div>';
}
break;
}
}
}
// Fetch all questions with their answers
$stmt = $pdo->query('SELECT * FROM questions ORDER BY id DESC');
$questions = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<?php echo $message; ?>
<div class="content-block">
<h2>Aggiungi Nuova Domanda</h2>
<form action="questions.php" method="POST">
<input type="hidden" name="action" value="add_question">
<div class="form-group">
<label for="question_text">Testo della Domanda</label>
<textarea name="question_text" id="question_text" rows="3" required></textarea>
</div>
<div class="form-group">
<label for="score">Punteggio</label>
<input type="number" name="score" id="score" value="10" required>
</div>
<div class="form-group">
<label>Risposte (seleziona quella corretta)</label>
<div class="answers-container">
<?php for ($i = 0; $i < 4; $i++): ?>
<div class="answer-group">
<input type="radio" name="is_correct" value="<?php echo $i; ?>" <?php echo $i === 0 ? 'checked' : ''; ?>>
<input type="text" name="answers[]" placeholder="Testo della risposta <?php echo $i + 1; ?>" required>
</div>
<?php endfor; ?>
</div>
</div>
<button type="submit" class="btn">Aggiungi Domanda</button>
</form>
</div>
<div class="content-block">
<h2>Elenco Domande</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Domanda</th>
<th>Punteggio</th>
<th>Azioni</th>
</tr>
</thead>
<tbody>
<?php foreach ($questions as $question): ?>
<tr>
<td><?php echo htmlspecialchars($question['id']); ?></td>
<td><?php echo htmlspecialchars($question['question_text']); ?></td>
<td><?php echo htmlspecialchars($question['score']); ?></td>
<td class="actions">
<a href="edit_question.php?id=<?php echo $question['id']; ?>" class="btn-link">Modifica</a>
<form action="questions.php" method="POST" style="display:inline;" onsubmit="return confirm('Sei sicuro di voler eliminare questa domanda?');">
<input type="hidden" name="action" value="delete_question">
<input type="hidden" name="question_id" value="<?php echo $question['id']; ?>">
<button type="submit" class="btn-link">Elimina</button>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<style>
.content-block {
background-color: #16213e;
padding: 20px;
border-radius: 8px;
margin-bottom: 30px;
}
.btn-link {
background: none;
border: none;
color: #e94560;
text-decoration: underline;
cursor: pointer;
padding: 0;
font-size: inherit;
font-family: inherit;
}
.btn-link:hover {
color: #c73c52;
}
</style>
<?php require_once 'partials/footer.php'; ?>

192
admin/results.php Normal file
View File

@ -0,0 +1,192 @@
<?php
require_once '../db/config.php';
require_once '../mail/MailService.php';
require_once 'partials/header.php';
$pdo = db();
$message = '';
$is_published = file_exists('../leaderboard_published.flag');
// Handle POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
switch ($_POST['action']) {
case 'delete_participant':
try {
$participant_id = $_POST['participant_id'];
$pdo->beginTransaction();
$stmt = $pdo->prepare('DELETE FROM submissions WHERE participant_id = ?');
$stmt->execute([$participant_id]);
$stmt = $pdo->prepare('DELETE FROM participants WHERE id = ?');
$stmt->execute([$participant_id]);
$pdo->commit();
$message = '<div class="alert alert-success">Partecipante eliminato con successo.</div>';
} catch (Exception $e) {
$pdo->rollBack();
$message = '<div class="alert alert-error">Errore: ' . $e->getMessage() . '</div>';
}
break;
case 'publish_leaderboard':
if (!$is_published) {
// Create flag file
file_put_contents('../leaderboard_published.flag', time());
// Send emails
try {
$participants_emails_stmt = $pdo->query("SELECT email FROM participants");
$emails = $participants_emails_stmt->fetchAll(PDO::FETCH_COLUMN);
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
$host = $_SERVER['HTTP_HOST'];
$leaderboard_url = $protocol . "://" . $host . "/leaderboard.php";
$subject = "La classifica del Quiz è online!";
$body_html = "<h1>Ciao!</h1><p>La classifica finale del quiz è stata pubblicata. <a href='{$leaderboard_url}'>Clicca qui per vederla!</a></p><p>Grazie per aver partecipato.</p>";
$body_text = "Ciao! La classifica finale del quiz è stata pubblicata. Vai su {$leaderboard_url} per vederla. Grazie per aver partecipato.";
foreach ($emails as $email) {
MailService::sendMail($email, $subject, $body_html, $body_text);
}
$message = '<div class="alert alert-success">Classifica pubblicata con successo! Email di notifica inviate a ' . count($emails) . ' partecipanti.</div>';
$is_published = true; // Update status for the current page view
} catch (Exception $e) {
$message = '<div class="alert alert-error">Errore durante l\'invio delle email: ' . $e->getMessage() . '</div>';
}
} else {
$message = '<div class="alert alert-error">La classifica è già stata pubblicata.</div>';
}
break;
}
}
try {
$participant_id = $_POST['participant_id'];
$pdo->beginTransaction();
// First delete submissions, then the participant
$stmt = $pdo->prepare('DELETE FROM submissions WHERE participant_id = ?');
$stmt->execute([$participant_id]);
$stmt = $pdo->prepare('DELETE FROM participants WHERE id = ?');
$stmt->execute([$participant_id]);
$pdo->commit();
$message = '<div class="alert alert-success">Partecipante eliminato con successo.</div>';
} catch (Exception $e) {
$pdo->rollBack();
$message = '<div class="alert alert-error">Errore: ' . $e->getMessage() . '</div>';
}
}
// Fetch all participants and their submission details
$participants_stmt = $pdo->query("SELECT * FROM participants ORDER BY created_at DESC");
$participants = $participants_stmt->fetchAll(PDO::FETCH_ASSOC);
// Function to calculate score for a participant
function calculate_score($participant_id, $pdo) {
$score_stmt = $pdo->prepare(
'SELECT q.score, a.is_correct
FROM submissions s
JOIN answers a ON s.answer_id = a.id
JOIN questions q ON s.question_id = q.id
WHERE s.participant_id = ?'
);
$score_stmt->execute([$participant_id]);
$results = $score_stmt->fetchAll(PDO::FETCH_ASSOC);
$total_score = 0;
foreach ($results as $result) {
if ($result['is_correct']) {
$total_score += (int)$result['score'];
} else {
// As per requirements, wrong answer gives negative score
$total_score -= (int)$result['score'];
}
}
return $total_score;
}
?>
<?php echo $message; ?>
<div class="content-block">
<h2>Pubblica Classifica</h2>
<?php if ($is_published): ?>
<p>La classifica è stata pubblicata. <a href="../leaderboard.php" target="_blank">Vedi la classifica pubblica</a>.</p>
<?php else: ?>
<p>Una volta pubblicata la classifica, tutti i partecipanti riceveranno un'email con il link per visualizzarla. Questa azione è irreversibile.</p>
<form action="results.php" method="POST" onsubmit="return confirm('Sei sicuro di voler pubblicare la classifica e inviare le email a tutti i partecipanti?');">
<input type="hidden" name="action" value="publish_leaderboard">
<button type="submit" class="btn">Pubblica Classifica e Invia Email</button>
</form>
<?php endif; ?>
</div>
<div class="content-block">
<h2>Risultati e Partecipanti</h2>
<table>
<thead>
<tr>
<th>Nickname</th>
<th>Email</th>
<th>Data Invio</th>
<th>Punteggio</th>
<th>Azioni</th>
</tr>
</thead>
<tbody>
<?php if (empty($participants)): ?>
<tr>
<td colspan="5">Nessun partecipante ha ancora completato il quiz.</td>
</tr>
<?php else: ?>
<?php foreach ($participants as $participant): ?>
<tr>
<td><?php echo htmlspecialchars($participant['nickname']); ?></td>
<td><?php echo htmlspecialchars($participant['email']); ?></td>
<td><?php echo date('d/m/Y H:i', strtotime($participant['created_at'])); ?></td>
<td><?php echo calculate_score($participant['id'], $pdo); ?></td>
<td class="actions">
<a href="view_submission.php?id=<?php echo $participant['id']; ?>" class="btn-link">Dettagli</a>
<form action="results.php" method="POST" style="display:inline;" onsubmit="return confirm('Sei sicuro di voler eliminare questo partecipante e tutte le sue risposte?');">
<input type="hidden" name="action" value="delete_participant">
<input type="hidden" name="participant_id" value="<?php echo $participant['id']; ?>">
<button type="submit" class="btn-link">Elimina</button>
</form>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>
<style>
.content-block {
background-color: #16213e;
padding: 20px;
border-radius: 8px;
margin-bottom: 30px;
}
.btn-link {
background: none;
border: none;
color: #e94560;
text-decoration: underline;
cursor: pointer;
padding: 0;
font-size: inherit;
font-family: inherit;
}
.btn-link:hover {
color: #c73c52;
}
</style>
<?php require_once 'partials/footer.php'; ?>

138
admin/style.css Normal file
View File

@ -0,0 +1,138 @@
body {
background-color: #1a1a2e;
color: #ffffff;
font-family: 'Roboto', sans-serif;
margin: 0;
padding: 20px;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
.main-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px 0;
border-bottom: 1px solid #0f3460;
margin-bottom: 20px;
}
.main-header h1 {
font-family: 'Orbitron', sans-serif;
color: #e94560;
margin: 0;
}
.main-header nav a {
color: #ffffff;
text-decoration: none;
margin-left: 20px;
font-weight: bold;
transition: color 0.3s;
}
.main-header nav a:hover {
color: #e94560;
}
h2 {
font-family: 'Orbitron', sans-serif;
color: #e94560;
border-bottom: 2px solid #0f3460;
padding-bottom: 10px;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #0f3460;
}
th {
background-color: #16213e;
font-weight: bold;
}
tr:hover {
background-color: #1f2a4a;
}
.actions a {
color: #e94560;
text-decoration: none;
margin-right: 10px;
}
.btn {
background-color: #e94560;
color: #ffffff;
padding: 10px 15px;
border: none;
border-radius: 5px;
text-decoration: none;
font-weight: bold;
cursor: pointer;
transition: background-color 0.3s;
}
.btn:hover {
background-color: #c73c52;
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
.form-group input[type="text"],
.form-group textarea {
width: 100%;
padding: 10px;
background-color: #16213e;
border: 1px solid #0f3460;
color: #ffffff;
border-radius: 5px;
}
.form-group .answers-container .answer-group {
margin-bottom: 10px;
display: flex;
align-items: center;
}
.form-group .answers-container .answer-group input[type='radio'] {
margin-right: 10px;
}
.form-group .answers-container .answer-group input[type='text'] {
flex-grow: 1;
}
.alert {
padding: 15px;
margin-bottom: 20px;
border-radius: 5px;
}
.alert-success {
background-color: #28a745;
color: white;
}
.alert-error {
background-color: #dc3545;
color: white;
}

95
admin/view_submission.php Normal file
View File

@ -0,0 +1,95 @@
<?php
require_once '../db/config.php';
require_once 'partials/header.php';
$pdo = db();
$participant_id = $_GET['id'] ?? null;
if (!$participant_id) {
header("Location: results.php");
exit;
}
// Fetch participant details
$stmt = $pdo->prepare('SELECT * FROM participants WHERE id = ?');
$stmt->execute([$participant_id]);
$participant = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$participant) {
echo "<p>Partecipante non trovato.</p>";
require_once 'partials/footer.php';
exit;
}
// Fetch submission details
$query = <<<SQL
SELECT
q.question_text,
q.score,
their_a.answer_text as chosen_answer,
their_a.is_correct as was_correct,
correct_a.answer_text as correct_answer
FROM submissions s
JOIN questions q ON s.question_id = q.id
JOIN answers their_a ON s.answer_id = their_a.id
LEFT JOIN answers correct_a ON q.id = correct_a.question_id AND correct_a.is_correct = 1
WHERE s.participant_id = ?
ORDER BY q.id ASC
SQL;
$stmt = $pdo->prepare($query);
$stmt->execute([$participant_id]);
$submission_details = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<div class="content-block">
<h2>Dettaglio Risposte - <?php echo htmlspecialchars($participant['nickname']); ?></h2>
<p><strong>Email:</strong> <?php echo htmlspecialchars($participant['email']); ?></p>
<a href="results.php">&laquo; Torna alla lista dei risultati</a>
<div class="submission-list">
<?php foreach ($submission_details as $detail): ?>
<div class="submission-item <?php echo $detail['was_correct'] ? 'correct' : 'incorrect'; ?>">
<h4><?php echo htmlspecialchars($detail['question_text']); ?></h4>
<p>
<strong>Risposta data:</strong> <?php echo htmlspecialchars($detail['chosen_answer']); ?>
(Punti: <?php echo $detail['was_correct'] ? '+' : '-'; echo htmlspecialchars($detail['score']); ?>)
</p>
<?php if (!$detail['was_correct']): ?>
<p><strong>Risposta corretta:</strong> <?php echo htmlspecialchars($detail['correct_answer']); ?></p>
<?php endif; ?>
</div>
<?php endforeach; ?>
</div>
</div>
<style>
.content-block {
background-color: #16213e;
padding: 20px;
border-radius: 8px;
}
.submission-list {
margin-top: 20px;
}
.submission-item {
border-left: 5px solid;
padding: 15px;
margin-bottom: 15px;
background-color: #1f2a4a;
}
.submission-item.correct {
border-left-color: #28a745;
}
.submission-item.incorrect {
border-left-color: #dc3545;
}
.submission-item h4 {
margin: 0 0 10px 0;
}
</style>
<?php require_once 'partials/footer.php'; ?>

97
db/seed.php Normal file
View File

@ -0,0 +1,97 @@
<?php
require_once __DIR__ . '/config.php';
try {
$pdo = db();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Clean up tables before seeding to make the script idempotent
$pdo->exec('SET FOREIGN_KEY_CHECKS=0;');
$pdo->exec('TRUNCATE TABLE submissions;');
$pdo->exec('TRUNCATE TABLE answers;');
$pdo->exec('TRUNCATE TABLE questions;');
$pdo->exec('TRUNCATE TABLE participants;');
$pdo->exec('SET FOREIGN_KEY_CHECKS=1;');
$quiz_data = [
[
'question' => "Quale sarà l'auto vincitrice del 'Best of Show' al Concorso d'Eleganza di Villa d'Este 2025?",
'points' => 5,
'answers' => [
['text' => "Un'auto d'epoca degli anni '30", 'correct' => true],
['text' => "Una supercar moderna", 'correct' => false],
['text' => "Un prototipo di design", 'correct' => false],
]
],
[
'question' => "Chi vincerà il premio 'FIVA World Motoring Heritage Year'?",
'points' => 5,
'answers' => [
['text' => "Un club di auto storiche italiano", 'correct' => false],
['text' => "Un museo dell'automobile americano", 'correct' => true],
['text' => "Una collezione privata giapponese", 'correct' => false],
]
],
[
'question' => "Quale brand presenterà il prototipo più audace?",
'points' => 5,
'answers' => [
['text' => "Un marchio di lusso europeo", 'correct' => false],
['text' => "Una startup di veicoli elettrici", 'correct' => true],
['text' => "Un produttore di hypercar di nicchia", 'correct' => false],
]
],
[
'question' => "DOMANDA JOLLY: Quale sarà il valore di aggiudicazione più alto all'asta RM Sotheby's di Villa Erba?",
'points' => 45,
'answers' => [
['text' => "Tra 5 e 10 milioni di euro", 'correct' => true],
['text' => "Sotto i 5 milioni di euro", 'correct' => false],
['text' => "Oltre 10 milioni di euro", 'correct' => false],
]
],
[
'question' => "ITALIAN TGA: Quale auto italiana vincerà il premio nella sua categoria?",
'points' => 30,
'answers' => [
['text' => "Una Ferrari classica", 'correct' => false],
['text' => "Una Lamborghini rara", 'correct' => false],
['text' => "Un'Alfa Romeo da competizione", 'correct' => true],
]
],
];
$pdo->beginTransaction();
foreach ($quiz_data as $item) {
// Insert question
$sql_question = "INSERT INTO questions (question_text, points) VALUES (:question_text, :points)";
$stmt_question = $pdo->prepare($sql_question);
$stmt_question->execute([
':question_text' => $item['question'],
':points' => $item['points']
]);
$question_id = $pdo->lastInsertId();
// Insert answers
foreach ($item['answers'] as $answer) {
$sql_answer = "INSERT INTO answers (question_id, answer_text, is_correct) VALUES (:question_id, :answer_text, :is_correct)";
$stmt_answer = $pdo->prepare($sql_answer);
$stmt_answer->execute([
':question_id' => $question_id,
':answer_text' => $answer['text'],
':is_correct' => (int)$answer['correct'] // Explicitly cast boolean to integer
]);
}
}
$pdo->commit();
echo "Database popolato con successo con le domande e le risposte del quiz." . PHP_EOL;
} catch (PDOException $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
die("Errore durante il popolamento del database: " . $e->getMessage());
}

51
db/setup.php Normal file
View File

@ -0,0 +1,51 @@
<?php
require_once __DIR__ . '/config.php';
try {
$pdo = db();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// SQL statements for creating tables
$sql = <<<SQL
CREATE TABLE IF NOT EXISTS `participants` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`email` VARCHAR(255) NOT NULL UNIQUE,
`nickname` VARCHAR(255) NOT NULL,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS `questions` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`question_text` TEXT NOT NULL,
`score` INT NOT NULL DEFAULT 10,
`image_url` VARCHAR(255) NULL,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS `answers` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`question_id` INT NOT NULL,
`answer_text` VARCHAR(255) NOT NULL,
`is_correct` BOOLEAN NOT NULL DEFAULT FALSE,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (`question_id`) REFERENCES `questions`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS `submissions` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`participant_id` INT NOT NULL,
`question_id` INT NOT NULL,
`answer_id` INT NOT NULL,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (`participant_id`) REFERENCES `participants`(`id`) ON DELETE CASCADE,
FOREIGN KEY (`question_id`) REFERENCES `questions`(`id`) ON DELETE CASCADE,
FOREIGN KEY (`answer_id`) REFERENCES `answers`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
SQL;
$pdo->exec($sql);
echo "Tabelle create con successo (o già esistenti)." . PHP_EOL;
} catch (PDOException $e) {
die("Errore nella creazione delle tabelle: " . $e->getMessage());
}

337
index.php
View File

@ -1,150 +1,205 @@
<?php
declare(strict_types=1);
@ini_set('display_errors', '1');
@error_reporting(E_ALL);
@date_default_timezone_set('UTC');
ini_set('display_errors', '1');
error_reporting(E_ALL);
date_default_timezone_set('Europe/Rome');
session_start();
require_once __DIR__ . '/db/config.php';
require_once __DIR__ . '/mail/MailService.php';
$pdo = db();
$message = '';
$error = '';
$submitted_successfully = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$nickname = filter_input(INPUT_POST, 'nickname', FILTER_SANITIZE_STRING);
$answers = $_POST['answers'] ?? [];
if (!$email || !$nickname || empty($answers)) {
$error = 'Per favore, compila tutti i campi e rispondi a tutte le domande.';
} else {
try {
// Check for duplicate email
$stmt = $pdo->prepare("SELECT id FROM participants WHERE email = ?");
$stmt->execute([$email]);
if ($stmt->fetch()) {
$error = 'Questo indirizzo email ha già partecipato. È consentito un solo invio per email.';
} else {
$pdo->beginTransaction();
// Insert participant
$stmt = $pdo->prepare("INSERT INTO participants (email, nickname) VALUES (?, ?)");
$stmt->execute([$email, $nickname]);
$participant_id = $pdo->lastInsertId();
// Insert submissions
$stmt_submission = $pdo->prepare("INSERT INTO submissions (participant_id, question_id, answer_id) VALUES (?, ?, ?)");
foreach ($answers as $question_id => $answer_id) {
$stmt_submission->execute([$participant_id, $question_id, $answer_id]);
}
$pdo->commit();
// Send confirmation email
$subject = 'Grazie per aver partecipato al nostro Quiz!';
$body = "Ciao {$nickname},<br><br>Grazie per aver inviato le tue risposte. I risultati saranno pubblicati al termine del concorso.<br><br>In bocca al lupo!";
MailService::sendMail($email, $subject, $body, strip_tags($body));
$message = 'Grazie per aver partecipato! Hai inviato con successo le tue risposte e riceverai una mail di conferma a breve.';
$submitted_successfully = true;
}
} catch (Exception $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
$error = "Si è verificato un errore durante l'invio. Riprova. Dettagli: " . $e->getMessage();
}
}
}
// Fetch questions and answers for the form
$questions = [];
if (!$submitted_successfully) {
try {
$stmt = $pdo->query("SELECT id, question_text, points FROM questions ORDER BY id");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$question_id = $row['id'];
$row['answers'] = [];
$stmt_answers = $pdo->prepare("SELECT id, answer_text FROM answers WHERE question_id = ? ORDER BY id");
$stmt_answers->execute([$question_id]);
$row['answers'] = $stmt_answers->fetchAll(PDO::FETCH_ASSOC);
$questions[] = $row;
}
} catch (Exception $e) {
$error = "Impossibile caricare le domande del quiz. Dettagli: " . $e->getMessage();
}
}
$phpVersion = PHP_VERSION;
$now = date('Y-m-d H:i:s');
?>
<!doctype html>
<html lang="en">
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>New Style</title>
<?php
// Read project preview data from environment
$projectDescription = $_SERVER['PROJECT_DESCRIPTION'] ?? '';
$projectImageUrl = $_SERVER['PROJECT_IMAGE_URL'] ?? '';
?>
<?php if ($projectDescription): ?>
<!-- Meta description -->
<meta name="description" content='<?= htmlspecialchars($projectDescription) ?>' />
<!-- Open Graph meta tags -->
<meta property="og:description" content="<?= htmlspecialchars($projectDescription) ?>" />
<!-- Twitter meta tags -->
<meta property="twitter:description" content="<?= htmlspecialchars($projectDescription) ?>" />
<?php endif; ?>
<?php if ($projectImageUrl): ?>
<!-- Open Graph image -->
<meta property="og:image" content="<?= htmlspecialchars($projectImageUrl) ?>" />
<!-- Twitter image -->
<meta property="twitter:image" content="<?= htmlspecialchars($projectImageUrl) ?>" />
<?php endif; ?>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">
<style>
:root {
--bg-color-start: #6a11cb;
--bg-color-end: #2575fc;
--text-color: #ffffff;
--card-bg-color: rgba(255, 255, 255, 0.01);
--card-border-color: rgba(255, 255, 255, 0.1);
}
body {
margin: 0;
font-family: 'Inter', sans-serif;
background: linear-gradient(45deg, var(--bg-color-start), var(--bg-color-end));
color: var(--text-color);
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
text-align: center;
overflow: hidden;
position: relative;
}
body::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><path d="M-10 10L110 10M10 -10L10 110" stroke-width="1" stroke="rgba(255,255,255,0.05)"/></svg>');
animation: bg-pan 20s linear infinite;
z-index: -1;
}
@keyframes bg-pan {
0% { background-position: 0% 0%; }
100% { background-position: 100% 100%; }
}
main {
padding: 2rem;
}
.card {
background: var(--card-bg-color);
border: 1px solid var(--card-border-color);
border-radius: 16px;
padding: 2rem;
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.1);
}
.loader {
margin: 1.25rem auto 1.25rem;
width: 48px;
height: 48px;
border: 3px solid rgba(255, 255, 255, 0.25);
border-top-color: #fff;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.hint {
opacity: 0.9;
}
.sr-only {
position: absolute;
width: 1px; height: 1px;
padding: 0; margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap; border: 0;
}
h1 {
font-size: 3rem;
font-weight: 700;
margin: 0 0 1rem;
letter-spacing: -1px;
}
p {
margin: 0.5rem 0;
font-size: 1.1rem;
}
code {
background: rgba(0,0,0,0.2);
padding: 2px 6px;
border-radius: 4px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
footer {
position: absolute;
bottom: 1rem;
font-size: 0.8rem;
opacity: 0.7;
}
</style>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quiz Eleganza Motoristica</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@700&family=Roboto:wght@400;700&display=swap" rel="stylesheet">
<style>
:root {
--bg-color: #1a1a2e;
--surface-color: #16213e;
--primary-accent: #e94560;
--secondary-accent: #0f3460;
--text-color: #ffffff;
--text-muted: #a0a0a0;
--success-color: #50fa7b;
--error-color: #ff5555;
}
body {
margin: 0;
font-family: 'Roboto', sans-serif;
background-color: var(--bg-color);
color: var(--text-color);
padding: 2rem;
}
.container { max-width: 800px; margin: 0 auto; }
h1 {
font-family: 'Orbitron', sans-serif;
color: var(--primary-accent);
text-align: center;
text-shadow: 0 0 10px var(--primary-accent);
}
.header-image { width: 100%; height: 200px; background-color: var(--secondary-accent); margin-bottom: 2rem; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-style: italic; color: var(--text-muted); }
.question-card {
background-color: var(--surface-color);
border: 1px solid var(--secondary-accent);
border-radius: 12px;
padding: 1.5rem;
margin-bottom: 1.5rem;
box-shadow: 0 4px 20px rgba(0,0,0,0.3);
transition: transform 0.2s;
}
.question-card:hover { transform: translateY(-5px); }
.question-title { font-weight: 700; font-size: 1.2rem; margin-bottom: 1rem; }
.answer-option { margin-bottom: 0.5rem; }
.answer-option label { display: flex; align-items: center; cursor: pointer; padding: 0.5rem; border-radius: 6px; transition: background-color 0.2s; }
.answer-option input { margin-right: 0.8rem; }
.answer-option label:hover { background-color: var(--secondary-accent); }
.form-group { margin-bottom: 1.5rem; }
.form-group label { display: block; margin-bottom: 0.5rem; }
.form-group input[type='email'], .form-group input[type='text'] {
width: 100%;
padding: 0.8rem;
border: 1px solid var(--secondary-accent);
background-color: var(--surface-color);
color: var(--text-color);
border-radius: 6px;
}
.btn-submit {
display: block; width: 100%; padding: 1rem; font-size: 1.2rem;
font-family: 'Orbitron', sans-serif;
background-color: var(--primary-accent);
color: var(--text-color);
border: none; border-radius: 8px; cursor: pointer;
transition: background-color 0.3s, box-shadow 0.3s;
text-shadow: 0 0 5px rgba(255,255,255,0.5);
}
.btn-submit:hover { background-color: #ff5e78; box-shadow: 0 0 15px var(--primary-accent); }
.message, .error { padding: 1rem; border-radius: 8px; text-align: center; margin: 1.5rem 0; }
.message { background-color: var(--success-color); color: var(--bg-color); }
.error { background-color: var(--error-color); color: var(--text-color); }
</style>
</head>
<body>
<main>
<div class="card">
<h1>Analyzing your requirements and generating your website…</h1>
<div class="loader" role="status" aria-live="polite" aria-label="Applying initial changes">
<span class="sr-only">Loading…</span>
</div>
<p class="hint"><?= ($_SERVER['HTTP_HOST'] ?? '') === 'appwizzy.com' ? 'AppWizzy' : 'Flatlogic' ?> AI is collecting your requirements and applying the first changes.</p>
<p class="hint">This page will update automatically as the plan is implemented.</p>
<p>Runtime: PHP <code><?= htmlspecialchars($phpVersion) ?></code> — UTC <code><?= htmlspecialchars($now) ?></code></p>
<div class="container">
<div class="header-image">Spazio per logo e info</div>
<h1>Quiz The Unheard Edition 2025</h1>
<?php if ($message): ?>
<div class="message"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>
<?php if ($error): ?>
<div class="error"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>
<?php if (!$submitted_successfully): ?>
<form action="index.php" method="POST">
<div class="question-card">
<h2>I tuoi dati</h2>
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="email" required>
</div>
<div class="form-group">
<label for="nickname">Nickname</label>
<input type="text" id="nickname" name="nickname" required>
</div>
</div>
<?php foreach ($questions as $index => $q): ?>
<div class="question-card">
<p class="question-title"><?= htmlspecialchars($q['question_text']) ?> <small>(<?= $q['points'] ?> punti)</small></p>
<?php foreach ($q['answers'] as $a): ?>
<div class="answer-option">
<label>
<input type="radio" name="answers[<?= $q['id'] ?>]" value="<?= $a['id'] ?>" required>
<?= htmlspecialchars($a['answer_text']) ?>
</label>
</div>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
<?php if (!empty($questions)): ?>
<button type="submit" class="btn-submit">Invia le tue risposte</button>
<?php endif; ?>
</form>
<?php endif; ?>
</div>
</main>
<footer>
Page updated: <?= htmlspecialchars($now) ?> (UTC)
</footer>
</body>
</html>
</html>

155
leaderboard.php Normal file
View File

@ -0,0 +1,155 @@
<?php
require_once 'db/config.php';
// We need a setting to check if the leaderboard is published.
// Let's assume a simple file-based flag for now, for speed.
// In a more robust app, this would be a database setting.
$is_published = file_exists('leaderboard_published.flag');
$pdo = db();
$leaderboard_data = [];
if ($is_published) {
// This is the same scoring logic from admin/results.php
// It would be better to refactor this into a shared function.
function calculate_score($participant_id, $pdo) {
$score_stmt = $pdo->prepare(
'SELECT q.score, a.is_correct
FROM submissions s
JOIN answers a ON s.answer_id = a.id
JOIN questions q ON s.question_id = q.id
WHERE s.participant_id = ?'
);
$score_stmt->execute([$participant_id]);
$results = $score_stmt->fetchAll(PDO::FETCH_ASSOC);
$total_score = 0;
foreach ($results as $result) {
if ($result['is_correct']) {
$total_score += (int)$result['score'];
} else {
$total_score -= (int)$result['score'];
}
}
return $total_score;
}
$participants_stmt = $pdo->query("SELECT id, nickname FROM participants");
$participants = $participants_stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($participants as $participant) {
$leaderboard_data[] = [
'nickname' => $participant['nickname'],
'score' => calculate_score($participant['id'], $pdo)
];
}
// Sort by score descending
usort($leaderboard_data, function($a, $b) {
return $b['score'] <=> $a['score'];
});
}
// Using the same frontend style as index.php
// I will read the content of index.php and extract the header and footer
// For now I will just copy the style part
?>
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Classifica Quiz</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&family=Roboto:wght@400;700&display=swap" rel="stylesheet">
<style>
body {
background-color: #1a1a2e;
color: #ffffff;
font-family: 'Roboto', sans-serif;
margin: 0;
padding: 40px 20px;
display: flex;
justify-content: center;
align-items: flex-start;
min-height: 100vh;
}
.container {
width: 100%;
max-width: 800px;
background-color: #16213e;
border-radius: 8px;
padding: 40px;
border: 1px solid #0f3460;
}
h1, h2 {
font-family: 'Orbitron', sans-serif;
color: #e94560;
text-align: center;
margin-bottom: 30px;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
padding: 15px;
text-align: left;
border-bottom: 1px solid #0f3460;
}
th {
background-color: #1a1a2e;
font-weight: bold;
font-family: 'Orbitron', sans-serif;
}
tr:nth-child(even) { background-color: #1f2a4a; }
.rank {
font-weight: bold;
font-size: 1.2em;
color: #e94560;
}
.not-published {
text-align: center;
font-size: 1.2em;
}
.home-link {
display: block;
text-align: center;
margin-top: 30px;
color: #e94560;
text-decoration: none;
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<h1>Classifica Finale</h1>
<?php if ($is_published): ?>
<table>
<thead>
<tr>
<th>Rank</th>
<th>Nickname</th>
<th>Punteggio</th>
</tr>
</thead>
<tbody>
<?php foreach ($leaderboard_data as $index => $row): ?>
<tr>
<td class="rank"><?php echo $index + 1; ?></td>
<td><?php echo htmlspecialchars($row['nickname']); ?></td>
<td><?php echo $row['score']; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<p class="not-published">La classifica non è stata ancora pubblicata. Torna più tardi!</p>
<?php endif; ?>
<a href="index.php" class="home-link">Torna al Quiz</a>
</div>
</body>
</html>