<?php
class NotificationController {
    private $db;
    public function __construct() { $this->db = Database::getInstance(); }

    public function index() {
        $page = max(1, intval($_GET['pg'] ?? 1)); $perPage = 20; $uid = Auth::user()['id'];
        $filter = $_GET['filter'] ?? '';
        $where = "WHERE user_id = ?"; $params = [$uid];
        if ($filter === 'unread') { $where .= " AND read_at IS NULL"; }
        $total = $this->db->fetchColumn("SELECT COUNT(*) FROM notifications $where", $params);
        $offset = ($page - 1) * $perPage;
        $notifications = $this->db->fetchAll("SELECT * FROM notifications $where ORDER BY created_at DESC LIMIT $perPage OFFSET $offset", $params);
        $unreadCount = $this->db->fetchColumn("SELECT COUNT(*) FROM notifications WHERE user_id=? AND read_at IS NULL", [$uid]);
        $pagination = paginationHtml($total, $page, $perPage, '?page=notifications' . ($filter ? "&filter=$filter" : ''));
        require 'app/views/notifications/index.php';
    }

    public function markRead($id) {
        $this->db->update('notifications', ['read_at' => date('Y-m-d H:i:s')], 'id = ? AND user_id = ?', [$id, Auth::user()['id']]);
        // Redirect to linked page if any
        $notif = $this->db->fetch("SELECT * FROM notifications WHERE id=? AND user_id=?", [$id, Auth::user()['id']]);
        if ($notif && !empty($notif['link'])) { redirect($notif['link']); }
        redirect('?page=notifications');
    }

    public function markAllRead() {
        CSRF::verify();
        $this->db->query("UPDATE notifications SET read_at = NOW() WHERE user_id = ? AND read_at IS NULL", [Auth::user()['id']]);
        flash('success', 'All notifications marked as read.'); redirect('?page=notifications');
    }

    public function delete($id) {
        CSRF::verify();
        $this->db->query("DELETE FROM notifications WHERE id = ? AND user_id = ?", [$id, Auth::user()['id']]);
        flash('success', 'Notification deleted.'); redirect('?page=notifications');
    }
}
