post = new Post(); $this->like = new Like(); $this->comment = new Comment(); } public function index(): void { $page = max(1, (int) ($_GET['page'] ?? 1)); $offset = ($page - 1) * self::POSTS_PER_PAGE; $posts = $this->post->findAllPaginated(self::POSTS_PER_PAGE, $offset); $totalPosts = $this->post->countAll(); $totalPages = max(1, (int) ceil($totalPosts / self::POSTS_PER_PAGE)); $userId = $_SESSION['user_id'] ?? null; foreach ($posts as &$post) { $post['like_count'] = $this->like->countByPost($post['id']); $post['user_liked'] = $userId ? $this->like->hasUserLiked($userId, $post['id']) : false; $post['comments'] = $this->comment->findByPostId($post['id']); } unset($post); $content = __DIR__ . '/../Views/gallery/index.php'; include __DIR__ . '/../Views/layouts/main.php'; } public function like(string $id): void { if (!isset($_SESSION['user_id'])) { header('Location: /login'); return; } if (!Csrf::validate($_POST['csrf_token'] ?? '')) { Flash::set('error', 'Invalid CSRF token.'); header('Location: /gallery'); return; } $this->like->toggle($_SESSION['user_id'], (int) $id); $page = (int) ($_POST['page'] ?? 1); header('Location: /gallery?page=' . $page . '#post-' . $id); } public function comment(string $id): void { if (!isset($_SESSION['user_id'])) { header('Location: /login'); return; } if (!Csrf::validate($_POST['csrf_token'] ?? '')) { Flash::set('error', 'Invalid CSRF token.'); header('Location: /gallery'); return; } $content = trim($_POST['content'] ?? ''); if ($content === '') { Flash::set('error', 'Comment cannot be empty.'); $page = (int) ($_POST['page'] ?? 1); header('Location: /gallery?page=' . $page . '#post-' . $id); return; } if (\strlen($content) > 500) { Flash::set('error', 'Comment is too long (max 500 characters).'); $page = (int) ($_POST['page'] ?? 1); header('Location: /gallery?page=' . $page . '#post-' . $id); return; } $this->comment->create($_SESSION['user_id'], (int) $id, $content); // Notify the post owner if they have comment notifications enabled $post = $this->post->findById((int) $id); if ($post && $post['user_id'] !== $_SESSION['user_id']) { $user = new User(); $owner = $user->findById($post['user_id']); if ($owner && $owner['notify_comments']) { Mail::sendCommentNotification( $owner['email'], $_SESSION['username'], (int) $id ); } } $page = (int) ($_POST['page'] ?? 1); header('Location: /gallery?page=' . $page . '#post-' . $id); } }