<?php

declare(strict_types=1);

namespace App\Models;

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

    public function createNotification(array $data): int
    {
        return $this->create($data);
    }

    public function getUserNotifications(int $userId, int $page = 1, int $perPage = 20): array
    {
        $perPage = max(1, $perPage);
        $offset = ($page - 1) * $perPage;

        $total = (int) $this->queryOne(
            "SELECT COUNT(*) as cnt FROM {$this->table} WHERE user_id = :uid",
            ['uid' => $userId]
        )['cnt'];

        $items = $this->query(
            "SELECT * FROM {$this->table}
             WHERE user_id = :uid
             ORDER BY created_at DESC
             LIMIT {$perPage} OFFSET {$offset}",
            ['uid' => $userId]
        );

        $unread = (int) $this->queryOne(
            "SELECT COUNT(*) as cnt FROM {$this->table} WHERE user_id = :uid AND is_read = 0",
            ['uid' => $userId]
        )['cnt'];

        return ['items' => $items, 'total' => $total, 'unread' => $unread, 'page' => $page, 'per_page' => $perPage, 'total_pages' => (int) ceil($total / max(1, $perPage))];
    }

    public function markAsRead(int $id): void
    {
        $this->update($id, ['is_read' => 1]);
    }

    public function markAllAsRead(int $userId): void
    {
        $this->execute(
            "UPDATE {$this->table} SET is_read = 1 WHERE user_id = :uid AND is_read = 0",
            ['uid' => $userId]
        );
    }
}
