<?php

namespace App\Http\Controllers\Api\Mobile\Rider;

use App\Http\Controllers\Controller;
use App\Models\AppNotification;
use Illuminate\Http\Request;

class NotificationController extends Controller
{
    public function index(Request $request)
    {
        $rider = $request->user();

        $items = AppNotification::where('recipient_type', 'rider')
            ->where('recipient_id', $rider->id)
            ->latest()
            ->limit(50)
            ->get()
            ->map(fn ($n) => $this->format($n));

        $unread = AppNotification::where('recipient_type', 'rider')
            ->where('recipient_id', $rider->id)
            ->whereNull('read_at')
            ->count();

        return response()->json([
            'status' => 'success',
            'data' => [
                'unread_count' => $unread,
                'notifications' => $items,
            ],
        ]);
    }

    public function markRead(Request $request, $id)
    {
        $rider = $request->user();

        $n = AppNotification::where('recipient_type', 'rider')
            ->where('recipient_id', $rider->id)
            ->where('id', $id)
            ->first();

        if ($n) {
            $n->read_at = now();
            $n->save();
        }

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

    public function markAllRead(Request $request)
    {
        $rider = $request->user();

        AppNotification::where('recipient_type', 'rider')
            ->where('recipient_id', $rider->id)
            ->whereNull('read_at')
            ->update(['read_at' => now()]);

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

    protected function format(AppNotification $n): array
    {
        return [
            'id' => $n->id,
            'title' => $n->title,
            'body' => $n->body,
            'type' => $n->type,
            'order_id' => $n->order_id,
            'data' => $n->data ?? [],
            'read' => $n->read_at !== null,
            'created_at' => $n->created_at?->format('Y-m-d H:i'),
        ];
    }
}
