<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Notification;
use App\Models\User;
use Illuminate\Http\Request;

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

    public function create()
    {
        return view('admin.notifications.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'body' => 'required|string',
            'type' => 'required|in:info,warning,success,promotion',
            'target_audience' => 'required|in:all,specific_user',
            'user_id' => 'required_if:target_audience,specific_user|exists:users,id',
            'image' => 'nullable|url', // Assuming simple URL for now or file upload logic later
            'link' => 'nullable|url',
        ]);

        if ($validated['target_audience'] == 'all') {
            // Logic to send to all.
            // Since we are storing in DB, we might want to create records for all users OR use a 'null' user_id to represent Global.
            // Schema: user_id is nullable. So user_id=null can mean Global/All.
            Notification::create([
                'user_id' => null,
                'title' => $validated['title'],
                'body' => $validated['body'],
                'type' => $validated['type'],
                'image' => $validated['image'],
                'link' => $validated['link'],
                'sent_at' => now(),
            ]);

            // NOTE: In a real push notification system (Firebase), we would trigger the job here.
        } else {
             Notification::create([
                'user_id' => $validated['user_id'],
                'title' => $validated['title'],
                'body' => $validated['body'],
                'type' => $validated['type'],
                'image' => $validated['image'],
                'link' => $validated['link'],
                'sent_at' => now(),
            ]);

            // NOTE: Trigger individual push here.
        }

        return redirect()->route('admin.notifications.index')->with('success', 'اعلان با موفقیت ارسال شد.');
    }

    public function show(Notification $notification)
    {
        return view('admin.notifications.show', compact('notification'));
    }

    public function destroy(Notification $notification)
    {
        $notification->delete();
        return redirect()->route('admin.notifications.index')->with('success', 'اعلان حذف شد.');
    }
}
