<?php

namespace App\Http\Controllers;

use App\Models\MarketingRequest;
use Carbon\Carbon;
use Illuminate\Http\Request;

class NotificationController extends Controller
{
    public function index()
    {
        $user = auth()->user();
        $notifications = $user->notifications()->paginate(20);
        return view('notifications.index', compact('notifications'));
    }

    public function poll(Request $request)
    {
        $user = auth()->user();
        $since = $request->get('since') ? Carbon::parse($request->get('since')) : Carbon::now()->subMinutes(10);

        $unreadNotifications = $user->unreadNotifications()
            ->latest()
            ->take(5)
            ->get()
            ->map(function ($n) {
                return [
                    'id' => $n->id,
                    'title' => $n->data['title'] ?? 'Notification',
                    'message' => $n->data['message'] ?? '',
                    'url' => $n->data['url'] ?? '#',
                    'created_at' => $n->created_at->diffForHumans(),
                ];
            });

        // Compute role-based summary counts for live status updates
        $dashboardCounts = [];
        if ($user->isHarcourtsAdmin()) {
            $base = MarketingRequest::where('submitted_by', $user->id);
            $dashboardCounts = [
                'awaiting_review' => (clone $base)->where('status', 'AWAITING_ADMIN_REVIEW')->count(),
                'changes_requested' => (clone $base)->where('status', 'CHANGES_REQUESTED')->count(),
                'approved' => (clone $base)->where('status', 'APPROVED')->count(),
                'completed' => (clone $base)->where('status', 'COMPLETED')->count(),
            ];
        } else {
            $dashboardCounts = [
                'new' => MarketingRequest::where('status', 'NEW')->count(),
                'in_progress' => MarketingRequest::where('status', 'IN_PROGRESS')->count(),
                'awaiting_admin' => MarketingRequest::where('status', 'AWAITING_ADMIN_REVIEW')->count(),
                'changes_requested' => MarketingRequest::where('status', 'CHANGES_REQUESTED')->count(),
                'approved' => MarketingRequest::where('status', 'APPROVED')->count(),
            ];
        }

        // Return request IDs modified since last poll for live list refreshes
        $updatedRequestIds = MarketingRequest::where('updated_at', '>=', $since)
            ->pluck('id')
            ->toArray();

        return response()->json([
            'unread_count' => $user->unreadNotifications()->count(),
            'notifications' => $unreadNotifications,
            'dashboard_counts' => $dashboardCounts,
            'updated_request_ids' => $updatedRequestIds,
            'timestamp' => now()->toIso8601String(),
        ]);
    }

    public function markAsRead(string $id)
    {
        $user = auth()->user();
        $notification = $user->notifications()->where('id', $id)->first();
        if ($notification) {
            $notification->markAsRead();
        }

        return back();
    }

    public function markAllAsRead()
    {
        auth()->user()->unreadNotifications->markAsRead();
        return back()->with('success', 'All notifications marked as read.');
    }
}
