<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserNotification;
use App\Services\AuditLogService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class NotificationController extends Controller
{
    public function index(Request $request): Response
    {
        $notifications = UserNotification::query()
            ->with('admin:id,name,email')
            ->latest('id')
            ->paginate(20)
            ->withQueryString()
            ->through(function (UserNotification $notification) {
                return [
                    'id' => $notification->id,
                    'title' => $notification->title,
                    'message' => $notification->message,
                    'audience' => $notification->audience,
                    'recipient_count' => count((array) ($notification->recipient_ids_json ?? [])),
                    'show_popup' => (bool) $notification->show_popup,
                    'show_in_inbox' => (bool) $notification->show_in_inbox,
                    'is_active' => (bool) $notification->is_active,
                    'created_at' => optional($notification->created_at)->toDateTimeString(),
                    'admin' => $notification->admin ? [
                        'id' => $notification->admin->id,
                        'name' => $notification->admin->name,
                        'email' => $notification->admin->email,
                    ] : null,
                ];
            });

        return Inertia::render('Admin/Notifications/Index', [
            'notifications' => $notifications,
            'users' => User::query()->orderBy('name')->limit(200)->get(['id', 'name', 'email']),
        ]);
    }

    public function store(Request $request, AuditLogService $auditLogService): RedirectResponse
    {
        $data = $request->validate([
            'title' => ['required', 'string', 'max:191'],
            'message' => ['required', 'string', 'max:5000'],
            'audience' => ['required', 'in:all,selected'],
            'recipient_ids' => ['nullable', 'array'],
            'recipient_ids.*' => ['integer', 'exists:users,id'],
            'show_popup' => ['nullable', 'boolean'],
            'show_in_inbox' => ['nullable', 'boolean'],
            'is_active' => ['nullable', 'boolean'],
        ]);

        $recipientIds = array_values(array_unique(array_map('intval', (array) ($data['recipient_ids'] ?? []))));

        if (($data['audience'] ?? 'all') === 'selected' && count($recipientIds) === 0) {
            return back()->withErrors([
                'recipient_ids' => 'Select at least one recipient when audience is selected users.',
            ]);
        }

        $notification = UserNotification::query()->create([
            'created_by_admin_id' => $request->user()?->id,
            'title' => $data['title'],
            'message' => $data['message'],
            'audience' => $data['audience'],
            'recipient_ids_json' => $data['audience'] === 'selected' ? $recipientIds : null,
            'show_popup' => (bool) ($data['show_popup'] ?? true),
            'show_in_inbox' => (bool) ($data['show_in_inbox'] ?? true),
            'is_active' => (bool) ($data['is_active'] ?? true),
        ]);

        $auditLogService->log(
            admin: $request->user(),
            action: 'admin.notification.created',
            entity: $notification,
            oldValues: null,
            newValues: $notification->toArray(),
            ipAddress: $request->ip(),
            userAgent: $request->userAgent()
        );

        return back()->with('success', 'Notification sent successfully.');
    }

    public function update(Request $request, UserNotification $notification, AuditLogService $auditLogService): RedirectResponse
    {
        $data = $request->validate([
            'is_active' => ['required', 'boolean'],
        ]);

        $old = ['is_active' => $notification->is_active];
        $notification->update(['is_active' => (bool) $data['is_active']]);

        $auditLogService->log(
            admin: $request->user(),
            action: 'admin.notification.updated',
            entity: $notification,
            oldValues: $old,
            newValues: ['is_active' => (bool) $notification->is_active],
            ipAddress: $request->ip(),
            userAgent: $request->userAgent()
        );

        return back()->with('success', 'Notification status updated.');
    }
}
