<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Notification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class NotificationController extends Controller
{
    /**
     * GET /api/notifications?type=&unread_only=1
     */
    public function index(Request $request)
    {
        $user = Auth::user();
        $perPage = min((int) $request->query('per_page', 30), 100);

        $query = Notification::where('user_id', $user->id);

        if ($request->query('type')) {
            $query->where('type', $request->query('type'));
        }

        if ($request->query('unread_only')) {
            $query->where('is_read', false);
        }

        $items = $query->orderByDesc('created_at')->paginate($perPage);

        return response()->json([
            'success' => true,
            'data' => [
                'unread_count' => Notification::where('user_id', $user->id)
                    ->where('is_read', false)
                    ->count(),
                'items' => $items->items(),
                'pagination' => [
                    'current_page' => $items->currentPage(),
                    'last_page' => $items->lastPage(),
                    'total' => $items->total(),
                ],
            ],
        ]);
    }

    /**
     * POST /api/notifications/{id}/read
     */
    public function markRead($id)
    {
        $user = Auth::user();
        $notif = Notification::where('user_id', $user->id)->where('id', $id)->first();
        if (! $notif) {
            return response()->json(['success' => false, 'message' => 'یافت نشد'], 404);
        }

        $notif->update([
            'is_read' => true,
            'read_at' => now(),
        ]);

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

    /**
     * POST /api/notifications/read-all
     */
    public function markAllRead()
    {
        $user = Auth::user();
        Notification::where('user_id', $user->id)
            ->where('is_read', false)
            ->update(['is_read' => true, 'read_at' => now()]);

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