<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class NotificationController extends Controller
{
    public function index()
    {
        return response()->json([
            'notifications' => auth()->user()->unreadNotifications
        ]);
    }

    public function markAsRead($id)
    {
        $notification = auth()->user()->notifications()->where('id', $id)->first();
        if ($notification) {
            $notification->markAsRead();
        }
        return response()->json(['success' => true]);
    }

    public function create()
    {
        $staff = \App\Models\User::whereHas('roles', function($q) { $q->where('name', '!=', 'Customer'); })->get();
        $customers = \App\Models\User::whereHas('roles', function($q) { $q->where('name', 'Customer'); })->get();
        return view('notifications.create', compact('staff', 'customers'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'message' => 'required|string',
            'target_group' => 'required|in:all,staff,customers,specific',
            'user_ids' => 'required_if:target_group,specific|array',
        ]);

        $recipients = collect();

        if ($request->target_group === 'all') {
            $recipients = \App\Models\User::all();
        } elseif ($request->target_group === 'staff') {
            $recipients = \App\Models\User::whereHas('roles', function($q) { $q->where('name', '!=', 'Customer'); })->get();
        } elseif ($request->target_group === 'customers') {
            $recipients = \App\Models\User::whereHas('roles', function($q) { $q->where('name', 'Customer'); })->get();
        } elseif ($request->target_group === 'specific') {
            $recipients = \App\Models\User::whereIn('id', $request->user_ids)->get();
        }

        foreach ($recipients as $recipient) {
            $recipient->notify(new \App\Notifications\SystemNotification($request->title, $request->message));
        }

        return back()->with('success', 'Notification sent successfully to ' . $recipients->count() . ' user(s)!');
    }
}
