<?php

namespace App\Http\Controllers;

use App\Models\NotificationRead;
use App\Models\UserNotification;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class NotificationController extends Controller
{
    // ── User: full notification page ─────────────────────────
    public function page()
    {
        $userId = Auth::id();

        $notifications = UserNotification::forUser($userId)
            ->latest()
            ->get()
            ->map(function ($n) use ($userId) {
                return [
                    'id'         => $n->id,
                    'title'      => $n->title,
                    'message'    => $n->message,
                    'type'       => $n->type,
                    'icon'       => $n->icon,
                    'is_read'    => $n->isReadBy($userId),
                    'created_at' => $n->created_at->diffForHumans(),
                    'date'       => $n->created_at->format('d M Y, h:i A'),
                ];
            });

        $unread = UserNotification::unreadCountFor($userId);

        return view('notifications.index', compact('notifications', 'unread'));
    }

    // ── User: fetch all visible notifications (JSON) ──────────
    public function index()
    {
        $userId = Auth::id();

        $notifications = UserNotification::forUser($userId)
            ->get()
            ->map(function ($n) use ($userId) {
                return [
                    'id'         => $n->id,
                    'title'      => $n->title,
                    'message'    => $n->message,
                    'type'       => $n->type,
                    'icon'       => $n->icon,
                    'target'     => $n->target,
                    'is_read'    => $n->isReadBy($userId),
                    'created_at' => $n->created_at->diffForHumans(),
                    'date'       => $n->created_at->format('d M Y H:i'),
                ];
            });

        return response()->json([
            'notifications' => $notifications,
            'unread'        => UserNotification::unreadCountFor($userId),
        ]);
    }

    // ── User: unread count only (for polling) ─────────────────
    public function unread()
    {
        return response()->json([
            'count' => UserNotification::unreadCountFor(Auth::id()),
        ]);
    }

    // ── User: mark one as read ────────────────────────────────
    public function markRead($id)
    {
        NotificationRead::firstOrCreate([
            'user_id'         => Auth::id(),
            'notification_id' => $id,
        ]);
        return response()->json(['success' => true]);
    }

    // ── User: mark all as read ────────────────────────────────
    public function markAllRead()
    {
        $userId = Auth::id();
        $ids    = UserNotification::forUser($userId)->pluck('id');

        foreach ($ids as $id) {
            NotificationRead::firstOrCreate([
                'user_id'         => $userId,
                'notification_id' => $id,
            ]);
        }
        return response()->json(['success' => true]);
    }

    // ── Admin: create notification ────────────────────────────
    public function store(Request $request)
    {
        $request->validate([
            'title'   => 'required|string|max:255',
            'message' => 'required|string|max:2000',
            'type'    => 'required|in:info,warning,success,danger',
            'target'  => 'required|in:all,user',
            'user_id' => 'nullable|exists:users,id',
        ]);

        UserNotification::create([
            'user_id' => $request->target === 'user' ? $request->user_id : null,
            'title'   => $request->title,
            'message' => $request->message,
            'type'    => $request->type,
            'icon'    => $request->icon ?? null,
        ]);

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

    // ── Admin: delete notification ────────────────────────────
    public function destroy($id)
    {
        UserNotification::findOrFail($id)->delete();
        return response()->json(['success' => true]);
    }

    // ── Admin: list all notifications ─────────────────────────
    public function adminIndex()
    {
        $notifs = UserNotification::with('user:id,name,email')
            ->latest()
            ->get()
            ->map(fn($n) => [
                'id'         => $n->id,
                'title'      => $n->title,
                'message'    => $n->message,
                'type'       => $n->type,
                'target'     => $n->target,
                'user_name'  => $n->user?->name,
                'user_email' => $n->user?->email,
                'created_at' => $n->created_at->diffForHumans(),
            ]);

        $clients = User::where('role', 'client')->select('id', 'name', 'email')->get();

        return response()->json(['notifications' => $notifs, 'clients' => $clients]);
    }
}
