Files
cmspro.it/app/models/Note.php
2026-01-29 21:07:02 +01:00

104 lines
3.2 KiB
PHP

<?php
require_once __DIR__ . '/Database.php';
class Note
{
public static function ensureTable(): void
{
$db = Database::getInstance();
$db->exec('
CREATE TABLE IF NOT EXISTS notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
title VARCHAR(255) NOT NULL,
content TEXT,
color VARCHAR(20) DEFAULT "primary",
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
)
');
}
public static function getAllByUser(int $userId): array
{
self::ensureTable();
$db = Database::getInstance();
$stmt = $db->prepare('
SELECT * FROM notes
WHERE user_id = :user_id
ORDER BY updated_at DESC
');
$stmt->execute(['user_id' => $userId]);
return $stmt->fetchAll();
}
public static function getById(int $id, int $userId): ?array
{
self::ensureTable();
$db = Database::getInstance();
$stmt = $db->prepare('
SELECT * FROM notes
WHERE id = :id AND user_id = :user_id
');
$stmt->execute(['id' => $id, 'user_id' => $userId]);
$note = $stmt->fetch();
return $note ?: null;
}
public static function create(int $userId, string $title, string $content, string $color = 'primary'): int
{
self::ensureTable();
$db = Database::getInstance();
$stmt = $db->prepare('
INSERT INTO notes (user_id, title, content, color, created_at, updated_at)
VALUES (:user_id, :title, :content, :color, datetime("now"), datetime("now"))
');
$stmt->execute([
'user_id' => $userId,
'title' => $title,
'content' => $content,
'color' => $color
]);
return (int) $db->lastInsertId();
}
public static function update(int $id, int $userId, string $title, string $content, string $color): bool
{
self::ensureTable();
$db = Database::getInstance();
$stmt = $db->prepare('
UPDATE notes
SET title = :title, content = :content, color = :color, updated_at = datetime("now")
WHERE id = :id AND user_id = :user_id
');
return $stmt->execute([
'id' => $id,
'user_id' => $userId,
'title' => $title,
'content' => $content,
'color' => $color
]);
}
public static function delete(int $id, int $userId): bool
{
$db = Database::getInstance();
$stmt = $db->prepare('
DELETE FROM notes
WHERE id = :id AND user_id = :user_id
');
return $stmt->execute(['id' => $id, 'user_id' => $userId]);
}
public static function countByUser(int $userId): int
{
self::ensureTable();
$db = Database::getInstance();
$stmt = $db->prepare('SELECT COUNT(*) as count FROM notes WHERE user_id = :user_id');
$stmt->execute(['user_id' => $userId]);
return (int) $stmt->fetch()['count'];
}
}