<?php

namespace App\Http\Controllers;

use App\Models\Ordine;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class RigaOrdineNotificaController extends Controller
{
    public function salva_fcm_token(Request $request)
    {
        $request->validate([
            'ordine_id' => 'required|integer',
            'fcm_token' => 'required|string',
        ]);

        $ordine = Ordine::query()
            ->where('id', $request->input('ordine_id'))
            ->where('stato', Ordine::PAGATO)
            ->first();

        if (! $ordine) {
            return response()->json(['success' => false, 'message' => 'Ordine non trovato'], 404);
        }

        $ordine->fcm_token = $request->input('fcm_token');
        $ordine->save();

        Log::info('[FCM] Token registrato dal cliente', [
            'ordine_id' => $ordine->id,
            'codice' => $ordine->codice,
            'token_preview' => substr($ordine->fcm_token, 0, 16).'...',
        ]);

        return response()->json(['success' => true, 'message' => 'FCM token salvato']);
    }
}
