<?php

namespace Artemis\Loyalty\Http\Actions;

use App\Models\User;
use Illuminate\Support\Str;
use Illuminate\Routing\Controller;
use Artemis\Loyalty\Models\Referral;
use Illuminate\Http\Request;

class GenerateReferralCodesAction extends Controller
{
    public function __invoke(Request $request)
    {

        $users = User::whereNull('referral_code')->get();

        $users->each(function ($user) {
            $user->update([
                'referral_code' => $this->generateUniqueReferralCode()
            ]);
        });

        if ($request->ajax() || $request->wantsJson() || (isset($request->ajax) && $request->ajax == true)) {
            return response()->json([
                'message' => 'Referral codes generated for ' . $users->count() . ' users',
                'success' => true
            ]);
        }

        return redirect()->back()->with('success', 'Referral codes generated for ' . $users->count() . ' users');
    }

    protected function generateUniqueReferralCode()
    {
        do {
            $code = Str::upper(Str::random(8));
        } while (User::where('referral_code', $code)->exists());

        return $code;
    }
}
