<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AdminNotificationController extends Controller
{
    /**
     * Últimas notificaciones del usuario (panel admin).
     */
    public function index(Request $request)
    {
        $user = $request->user();
        if (! $user || $user->role !== 'admin') {
            return response()->json(['message' => 'No autorizado.'], 403);
        }

        $items = $user->notifications()->orderByDesc('created_at')->limit(40)->get();

        return response()->json([
            'notifications' => $items->map(fn ($n) => [
                'id' => $n->id,
                'type' => $n->type,
                'data' => $n->data,
                'read_at' => $n->read_at?->toIso8601String(),
                'created_at' => $n->created_at->toIso8601String(),
            ]),
        ]);
    }

    public function unreadCount(Request $request)
    {
        $user = $request->user();
        if (! $user || $user->role !== 'admin') {
            return response()->json(['message' => 'No autorizado.'], 403);
        }

        return response()->json([
            'count' => $user->unreadNotifications()->count(),
        ]);
    }

    public function markRead(Request $request, string $id)
    {
        $user = $request->user();
        if (! $user || $user->role !== 'admin') {
            return response()->json(['message' => 'No autorizado.'], 403);
        }

        $n = $user->notifications()->where('id', $id)->first();
        if ($n) {
            $n->markAsRead();
        }

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

    public function markAllRead(Request $request)
    {
        $user = $request->user();
        if (! $user || $user->role !== 'admin') {
            return response()->json(['message' => 'No autorizado.'], 403);
        }

        foreach ($user->unreadNotifications()->get() as $notification) {
            $notification->markAsRead();
        }

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

    /**
     * Marca como leídas todas las notificaciones no leídas cuyo data.phone coincide (misma campana que el panel web).
     */
    public function markReadByPhone(Request $request)
    {
        $user = $request->user();
        if (! $user || $user->role !== 'admin') {
            return response()->json(['message' => 'No autorizado.'], 403);
        }

        $validated = $request->validate([
            'phone' => 'required|string|max:32',
        ]);

        $digits = preg_replace('/\D/', '', (string) $validated['phone']);
        if ($digits === '') {
            return response()->json(['message' => 'Teléfono inválido.'], 422);
        }

        foreach ($user->unreadNotifications()->get() as $notification) {
            $raw = $notification->data['phone'] ?? '';
            $nDigits = preg_replace('/\D/', '', (string) $raw);
            if ($nDigits !== '' && $nDigits === $digits) {
                $notification->markAsRead();
            }
        }

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