<?php

namespace App\Http\Controllers;

use App\Models\Notification;
use App\Models\SupportTicket;
use App\Models\User;
use App\Models\Withdrawal;
use Illuminate\Http\Request;

class NotificationsController extends Controller
{
    /**
     * The signed-in user's own notification feed (bell dropdown).
     */
    public function feed(Request $request)
    {
        $user = $request->user();

        $items = Notification::where('user_id', $user->id)
            ->latest()
            ->limit(15)
            ->get()
            ->map(fn (Notification $n) => [
                'id' => 'n-'.$n->id,
                'title' => $n->title,
                'message' => $n->message,
                'time' => optional($n->created_at)->diffForHumans(),
                'ts' => optional($n->created_at)->timestamp ?? 0,
                'read' => (bool) $n->is_read,
            ]);

        return response()->json([
            'unread' => Notification::where('user_id', $user->id)->where('is_read', false)->count(),
            'items' => $items,
        ]);
    }

    public function markRead(Request $request)
    {
        Notification::where('user_id', $request->user()->id)
            ->where('is_read', false)
            ->update(['is_read' => true]);

        return response()->json(['ok' => true]);
    }

    /**
     * Derived admin event feed: things an admin needs to react to. Unread
     * state is tracked client-side (last-seen timestamp in localStorage),
     * so this endpoint stays read-only.
     */
    public function adminFeed()
    {
        $items = collect();

        Withdrawal::with('user')->where('status', 'pending')->latest()->limit(5)->get()
            ->each(function (Withdrawal $w) use ($items) {
                $items->push([
                    'id' => 'wd-'.$w->id,
                    'title' => 'Withdrawal request',
                    'message' => (optional($w->user)->username ?? 'A user').' requested '.$w->amount.' coins via '.$w->method,
                    'time' => optional($w->created_at)->diffForHumans(),
                    'ts' => optional($w->created_at)->timestamp ?? 0,
                    'url' => route('admin.withdrawals'),
                ]);
            });

        SupportTicket::with('user')->whereIn('status', ['open', 'pending'])->latest('updated_at')->limit(5)->get()
            ->each(function (SupportTicket $t) use ($items) {
                $items->push([
                    'id' => 'tk-'.$t->id.'-'.optional($t->updated_at)->timestamp,
                    'title' => 'Support ticket',
                    'message' => (optional($t->user)->username ?? 'A user').': '.\Illuminate\Support\Str::limit($t->subject, 60),
                    'time' => optional($t->updated_at)->diffForHumans(),
                    'ts' => optional($t->updated_at)->timestamp ?? 0,
                    'url' => route('admin.tickets'),
                ]);
            });

        User::where('created_at', '>=', now()->subDays(2))->latest()->limit(5)->get()
            ->each(function (User $u) use ($items) {
                $items->push([
                    'id' => 'usr-'.$u->id,
                    'title' => 'New member',
                    'message' => $u->username.' joined',
                    'time' => optional($u->created_at)->diffForHumans(),
                    'ts' => optional($u->created_at)->timestamp ?? 0,
                    'url' => route('admin.users'),
                ]);
            });

        return response()->json([
            'items' => $items->sortByDesc('ts')->values()->take(15),
        ]);
    }
}
