Files
pagedev.pl/controllers/NotesController.php
2026-01-29 21:08:01 +01:00

115 lines
3.1 KiB
PHP

<?php
class NotesController
{
private $notesModel;
public function __construct()
{
$this->notesModel = new Notes();
// Sprawdzenie czy użytkownik jest zalogowany
if (!isset($_SESSION['user_id'])) {
header('Location: /logowanie');
exit;
}
}
public function index()
{
$userId = $_SESSION['user_id'];
$notes = $this->notesModel->getAllByUser($userId);
$notesCount = $this->notesModel->getCount($userId);
require_once __DIR__ . '/../views/notes/index.php';
}
public function create()
{
$note = null; // Pusty formularz dla nowej notatki
require_once __DIR__ . '/../views/notes/form.php';
}
public function edit()
{
$noteId = $_GET['id'] ?? null;
if (!$noteId) {
$_SESSION['error'] = 'Nie podano ID notatki';
header('Location: /notatnik');
exit;
}
$userId = $_SESSION['user_id'];
$note = $this->notesModel->getById($noteId, $userId);
if (!$note) {
$_SESSION['error'] = 'Notatka nie została znaleziona';
header('Location: /notatnik');
exit;
}
require_once __DIR__ . '/../views/notes/form.php';
}
public function save()
{
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header('Location: /notatnik');
exit;
}
$userId = $_SESSION['user_id'];
$noteId = $_POST['note_id'] ?? null;
$title = trim($_POST['title'] ?? '');
$content = trim($_POST['content'] ?? '');
if (empty($title)) {
$_SESSION['error'] = 'Tytuł notatki jest wymagany';
header('Location: ' . ($noteId ? "/notatka/edytuj?id=$noteId" : '/notatka/nowa'));
exit;
}
if ($noteId) {
// Aktualizacja istniejącej notatki
$result = $this->notesModel->update($noteId, $userId, $title, $content);
$_SESSION['success'] = 'Notatka została zaktualizowana';
} else {
// Tworzenie nowej notatki
$result = $this->notesModel->create($userId, $title, $content);
$_SESSION['success'] = 'Notatka została utworzona';
}
header('Location: /notatnik');
exit;
}
public function delete()
{
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header('Location: /notatnik');
exit;
}
$noteId = $_POST['note_id'] ?? null;
if (!$noteId) {
$_SESSION['error'] = 'Nie podano ID notatki';
header('Location: /notatnik');
exit;
}
$userId = $_SESSION['user_id'];
$result = $this->notesModel->delete($noteId, $userId);
if ($result) {
$_SESSION['success'] = 'Notatka została usunięta';
} else {
$_SESSION['error'] = 'Nie udało się usunąć notatki';
}
header('Location: /notatnik');
exit;
}
}