<?php

namespace App\Http\Controllers\Api;

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

class UtrApplicationsController extends Controller
{
    public function apply(Request $request)
    {
        $request->validate([
            'your_name' => 'required|string|max:255',
            'contact_number' => 'required|string|max:20',
            'your_message' => 'required|string',
        ]);

        $application = UtrApplication::create([
            'user_id' => auth()->user()->id,
            'your_name' => $request->your_name,
            'contact_number' => $request->contact_number,
            'your_message' => $request->your_message,
            'status' => 0,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Your application has been successfully submitted, stay tuned.',
            'data' => $application
        ]);
    }

    // Get logged-in user's UTR details
    public function show()
    {
        $utr = NiUtr::where('user_id', Auth::id())->first();

        return response()->json([
            'success' => (bool) $utr,
            'data' => $utr,
        ]);
    }

    // Save or update logged-in user's UTR details
    public function store(Request $request)
    {
        $request->validate([
            'national_insurance' => 'required|string|max:20',
            'unique_tax_reference' => 'required|string|max:20',
        ]);

        $utr = NiUtr::updateOrCreate(
            ['user_id' => Auth::id()],
            [
                'national_insurance' => strtoupper($request->national_insurance),
                'unique_tax_reference' => strtoupper($request->unique_tax_reference),
            ]
        );

        return response()->json([
            'success' => true,
            'message' => 'UTR details saved successfully',
            'data' => $utr,
        ]);
    }
}
