<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Model\User;
use App\Model\Client\UserFcmToken;
use App\Helpers\FcmHelper;

class WebPushNotificationController extends Controller
{
    public function store(Request $request)
    {
        // 1. Validate request
        $validator = Validator::make($request->all(), [
            'token' => 'required|string|max:500',
            'device_name' => 'nullable|string|max:255',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors(),
            ], 422);
        }

        $validated = $validator->validated();

        // 2. Identify user and client
        $userId = $request->user()->id ?? $request->header('user-id');
        $clientId = User::where('id', $userId)->value('parent_id');
        if (!$userId) {
            return response()->json([
                'success' => false,
                'message' => 'User ID missing or unauthorized',
            ], 401);
        }

        $token = $request->input('token');
        $deviceName = $request->input('device_name');
        $tokens = UserFcmToken::where('user_id', $userId)
            ->orderByDesc('id')
            ->get();

        // If already exists, skip
        if ($tokens->contains('token', $token)) {
            return response()->json(['success' => true, 'message' => 'Token already exists']);
        }

        // If user already has 3 tokens, replace the oldest one
        if ($tokens->count() >= 3) {
            $oldest = $tokens->last();
            $oldest->update([
                'token' => $token,
                'device_name' => $deviceName,
            ]);
        } else {
            UserFcmToken::create([
                'user_id' => $userId,
                'token' => $token,
                'device_name' => $deviceName,
            ]);
        }

        return response()->json(['success' => true, 'message' => 'Token stored successfully']);
    }

    public function testNotification(Request $request)
    {
        $userId = $request->user()->id ?? $request->header('user-id');

        if (!$userId) {
            return response()->json(['success' => false, 'message' => 'user_id required'], 422);
        }

        $user = User::find($userId);
        if (!$user) {
            return response()->json(['success' => false, 'message' => 'User not found'], 404);
        }

        $title = $request->input('title', 'Test Notification');
        $body  = $request->input('body', 'This is a test message.');

        $sent = FcmHelper::send($userId, $title, $body);

        return response()->json([
            'success' => $sent,
            'message' => $sent ? 'Notification sent successfully.' : 'Failed to send notification.'
        ]);
    }
}
