<?php

namespace App\Models;

use App\Core\Model;

class Notification extends Model
{
    protected string $table = 'notifications';

    public function create(int $userId, string $type, array $data): void
    {
        $stmt = $this->db->prepare(
            "INSERT INTO notifications (user_id, type, data) VALUES (?, ?, ?)"
        );
        $stmt->execute([$userId, $type, json_encode($data)]);
    }

    public function getUnread(int $userId): array
    {
        $stmt = $this->db->prepare(
            "SELECT * FROM notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT 20"
        );
        $stmt->execute([$userId]);
        return $stmt->fetchAll();
    }

    public function countUnread(int $userId): int
    {
        $stmt = $this->db->prepare(
            "SELECT COUNT(*) FROM notifications WHERE user_id = ? AND is_read = 0"
        );
        $stmt->execute([$userId]);
        return (int)$stmt->fetchColumn();
    }

    public function markAsRead(int $id): void
    {
        $this->db->prepare("UPDATE notifications SET is_read = 1 WHERE id = ?")->execute([$id]);
    }

    public function markAllRead(int $userId): void
    {
        $this->db->prepare("UPDATE notifications SET is_read = 1 WHERE user_id = ?")->execute([$userId]);
    }

    public function clearAll(int $userId): void
    {
        $this->db->prepare("DELETE FROM notifications WHERE user_id = ?")->execute([$userId]);
    }
}
