Im creating an website for a school project.
The website consists of a platform where clients can mark classes. Different clients can mark classes on the same day but the same client can only mark one class per day.
I’m using javascript and php to do this with json. I normally use sql for this but my teacher made me use json. I’m having some difficulties with the project.
I want to make it so if a class is Marked it updates to the json file. The json has this structure
[
{
"username": "mario",
"password": "$2y$10$.iAaXdxRMYxGZcn3j8MLL.2orggPOGM8BITHLLf0kNvpTYpRkWkPi"
},
{
"username": "pedro",
"password": "$2y$10$QjPT67i8I4hTtyGYTzh1V.9LKWbAgqK4M1pLETKDSgG6P8aP2.N1e"
},
{
"username": "alvaro",
"password": "$2y$10$BnV1kRYSjbG5Jg26GkYx1OXOb6PW1I4qU3DJHa0lQzN/TExYOWNMe"
}
]
`
My php looks like this
<?php
session_start();
if (!isset($_SESSION['username'])) {
header('Location: sessoes.html');
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['logout'])) {
session_unset();
session_destroy();
header('Location: sessoes.html');
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['new_username'])) {
$newUsername = trim($_POST['new_username']);
if (!empty($newUsername)) {
$dataFile = 'users.json';
$data = file_exists($dataFile) ? json_decode(file_get_contents($dataFile), true) : [];
$usernameExists = false;
foreach ($data as $user) {
if (isset($user['username']) && $user['username'] === $newUsername) {
$usernameExists = true;
break;
}
}
if ($usernameExists) {
echo "<script>alert('O nome de usuário já existe. Escolha outro.');</script>";
}else{
$oldUsername = $_SESSION['username'];
$_SESSION['username'] = $newUsername;
foreach ($data as $key => $user) {
if (isset($user['username']) && $user['username'] === $oldUsername) {
$data[$key]['username'] = $newUsername;
break;
}
}
file_put_contents($dataFile, json_encode($data, JSON_PRETTY_PRINT));
header('Location: ' . $_SERVER['PHP_SELF']);
exit;
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calendário de Aulas</title>
<link rel="stylesheet" href="calendario.css">
</head>
<body>
<div class="logout-container">
<form method="POST">
<button type="submit" id="logoutButton" name="logout">LogOut</button>
</form>
</div>
<button id="voltarButton" onclick="window.location.href='index.html'">Voltar</button>
<h1>Bem-Vindo, <?php echo htmlspecialchars($_SESSION['username']); ?>!
<button id="changeUsernameButton" onclick="document.getElementById('changeUsernameForm').style.display='block'">Alterar Nome</button>
</h1>
<div id="changeUsernameForm" style="display:none;">
<form method="POST">
<input type="text" name="new_username" placeholder="Novo Nome de Usuário" required>
<button type="submit">Salvar</button>
</form>
</div>
<h2>Calendário de Aulas</h2>
<br>
<div id="aulaTipo">
<select id="tipoAula">
<option value="Presencial">Presencial</option>
<option value="Online">Online</option>
</select>
<button id="markClassButton" disabled>Marcar Aula</button>
</div>
<div class="calendar">
<div class="calendar-header">
<button id="prevMonthButton"><<</button>
<span id="calendarMonth"></span>
<button id="nextMonthButton">>></button>
</div>
<div class="calendar-days-header">
<div>Dom</div><div>Seg</div><div>Ter</div><div>Qua</div><div>Qui</div><div>Sex</div><div>Sáb</div>
</div>
<div id="calendarDays" class="calendar-days"></div>
</div>
<div id="message" class="message"></div>
<script src="calendario.js"></script>
</body>
</html>
and my javascript looks like this
let currentMonth = new Date().getMonth();
let currentYear = new Date().getFullYear();
let selectedDay = null;
function renderCalendar() {
const monthNames = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"];
const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
const firstDayOfMonth = new Date(currentYear, currentMonth, 1).getDay();
const today = new Date();
document.getElementById('calendarMonth').innerText = `${monthNames[currentMonth]} ${currentYear}`;
const calendarDays = document.getElementById('calendarDays');
calendarDays.innerHTML = '';
for (let i = 0; i < firstDayOfMonth; i++) {
const emptyDay = document.createElement('div');
calendarDays.appendChild(emptyDay);
}
for (let day = 1; day <= daysInMonth; day++) {
const dayElement = document.createElement('div');
dayElement.classList.add('calendar-day');
dayElement.innerText = day;
const isPast = new Date(currentYear, currentMonth, day) < today.setHours(0, 0, 0, 0);
if (isPast) {
dayElement.classList.add('past');
} else {
dayElement.onclick = function() { selectDay(day, dayElement); };
}
calendarDays.appendChild(dayElement);
}
}
function selectDay(day, element) {
const message = document.getElementById('message');
selectedDay = day;
const allDays = document.querySelectorAll('.calendar-day');
allDays.forEach(dayElement => dayElement.classList.remove('selected'));
element.classList.add('selected');
const markedClassType = getClassType(day);
if (markedClassType) {
message.innerText = `O dia ${day} já tem uma aula marcada: ${markedClassType}`;
document.getElementById('markClassButton').disabled = true;
} else {
message.innerText = `Você selecionou o dia ${day}. Escolha o tipo de aula e clique em "Marcar Aula"`;
document.getElementById('markClassButton').disabled = false;
}
}
function isClassMarked(day) {
const markedClasses = JSON.parse(localStorage.getItem('markedClasses')) || [];
return markedClasses.some(item => item.day === day);
}
function getClassType(day) {
const markedClasses = JSON.parse(localStorage.getItem('markedClasses')) || [];
const classData = markedClasses.find(item => item.day === day);
return classData ? classData.tipoAula : null;
}
document.getElementById('prevMonthButton').onclick = function() {
if (currentMonth === 0) {
currentMonth = 11;
currentYear--;
} else {
currentMonth--;
}
renderCalendar();
};
document.getElementById('nextMonthButton').onclick = function() {
if (currentMonth === 11) {
currentMonth = 0;
currentYear++;
} else {
currentMonth++;
}
renderCalendar();
};
document.getElementById('markClassButton').onclick = function() {
const tipoAula = document.getElementById('tipoAula').value;
const markedClasses = JSON.parse(localStorage.getItem('markedClasses')) || [];
markedClasses.push({ day: selectedDay, tipoAula: tipoAula });
localStorage.setItem('markedClasses', JSON.stringify(markedClasses));
document.getElementById('message').innerText = `Aula ${tipoAula} marcada para o dia ${selectedDay}!`;
document.getElementById('markClassButton').disabled = true;
renderCalendar();
};
renderCalendar();
css also if u want
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
header {
background-color: #333;
color: white;
padding: 10px 0;
text-align: center;
}
header nav a {
color: white;
margin: 0 15px;
text-decoration: none;
font-size: 18px;
}
header nav a:hover {
text-decoration: underline;
}
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
text-align: center;
padding: 20px;
position: relative;
}
h1 {
margin-bottom: 20px;
}
#voltarButton, #logoutButton {
position: fixed;
top: 20px;
padding: 10px 20px;
background-color: #2196F3;
color: white;
font-size: 1rem;
border: none;
border-radius: 5px;
cursor: pointer;
margin-bottom: 20px;
z-index: 10;
}
#voltarButton {
left: 20px;
}
#logoutButton {
right: 20px;
}
#voltarButton:hover, #logoutButton:hover {
background-color: #0b7dda;
}
#aulaTipo {
margin-bottom: 20px;
}
#tipoAula {
padding: 10px;
font-size: 1rem;
}
button {
padding: 10px;
font-size: 1rem;
cursor: pointer;
background-color: #333;
color: white;
border: none;
border-radius: 5px;
}
button:hover {
background-color: #555;
}
.calendar {
display: inline-block;
border: 1px solid #ccc;
padding: 20px;
background-color: #fff;
border-radius: 10px;
width: 100%;
max-width: 450px;
box-sizing: border-box;
}
.calendar-header {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
align-items: center;
}
#calendarMonth {
font-size: 1.5rem;
font-weight: bold;
}
.calendar-days-header {
display: grid;
grid-template-columns: repeat(7, 1fr);
text-align: center;
margin-bottom: 10px;
}
.calendar-days {
display: grid;
grid-template-columns: repeat(7, 1fr);
grid-gap: 10px;
}
.calendar-day {
padding: 15px;
cursor: pointer;
background-color: #e1edf2;
border-radius: 5px;
transition: background-color 0.3s ease;
text-align: center;
font-size: 1.1rem;
height: 50px;
width: 50px;
margin: auto;
box-sizing: border-box;
}
.calendar-day:hover {
background-color: #3D3D3D;
color: white;
}
.calendar-day.selected {
background-color: #000;
color: white;
font-weight: bold;
}
.calendar-day.presencial {
background-color: #4CAF50;
color: white;
}
.calendar-day.online {
background-color: #2196F3;
color: white;
}
.message {
margin-top: 20px;
font-size: 1.2rem;
color: #3D3D3D;
}
@media (max-width: 768px) {
.calendar {
width: 90%;
}
.calendar-day {
padding: 10px;
font-size: 1rem;
height: 45px;
width: 45px;
}
}
.past {
color: #ccc;
pointer-events: none;
}
I also want to make it so if the user is mario instead of showing the callender it shows the names of the people that have a class already and the day.
I know the code is terrible and has both portuguese and english but this isnt the final version and i will translate it all. It’s just hard for me to code in Portuguese. I prefer english. Im sorry if the question im asking is really eazy or stupid but i could really use some help.
I tried a lot of different ways to update the json file but none were successful