<?php

declare(strict_types=1);

namespace PpPhp\Modules\Notifications\Controllers;

use PpPhp\Core\Config;
use PpPhp\Core\DB;
use PpPhp\Core\Notification;
use PpPhp\Core\Security;

/**
 * Feeds the notification bell in the PPphp console.
 *
 * Notifications are addressed per-user (or to everyone when `user_id` is NULL),
 * so each signed-in person only ever sees their own.
 */
class NotificationsController
{
    public function __construct(private Config $config) {}

    public function list(): void
    {
        header('Content-Type: application/json');
        Security::RequireAuth();

        $userId = (int) (Security::CurrentUserData()['id'] ?? 0);

        try {
            DB::Init();
            DB::SetConnection();
            Notification::SetTableName('notifications');

            $rows = Notification::Get($userId, 15);
            $items = array_map(static fn(array $n): array => [
                'id'      => (int) $n['id'],
                'title'   => (string) ($n['title'] ?? ''),
                'message' => (string) ($n['message'] ?? ''),
                'icon'    => (string) ($n['icon'] ?? 'bell'),
                'url'     => (string) ($n['url'] ?? ''),
                'type'    => (string) ($n['type'] ?? 'info'),
                'unread'  => (int) ($n['is_read'] ?? 0) === 0,
                'ts'      => strtotime((string) ($n['created_at'] ?? 'now')) ?: time(),
            ], $rows);

            echo json_encode([
                'success' => true,
                'unread'  => Notification::Count($userId),
                'items'   => $items,
            ]);
        } catch (\Throwable $e) {
            // The bell is ambient — never let it break a page.
            echo json_encode(['success' => true, 'unread' => 0, 'items' => []]);
        }
        exit;
    }

    public function markRead(): void
    {
        header('Content-Type: application/json');
        Security::RequireAuth();

        $userId = (int) (Security::CurrentUserData()['id'] ?? 0);
        $input  = json_decode((string) file_get_contents('php://input'), true) ?: [];
        $id     = (int) ($input['id'] ?? 0);

        try {
            DB::Init();
            DB::SetConnection();
            Notification::SetTableName('notifications');

            if ($id > 0) {
                Notification::MarkRead($id);
            } else {
                Notification::MarkAllRead($userId);
            }
            echo json_encode(['success' => true, 'unread' => Notification::Count($userId)]);
        } catch (\Throwable $e) {
            echo json_encode(['success' => false, 'message' => 'Could not update notifications.']);
        }
        exit;
    }
}
