<?php

namespace App\Http\Controllers\Frontend\Auth;

use App\Models\Customer;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Providers\RouteServiceProvider;

class RegisterController extends Controller
{
    public function index()
    {
        return view('frontend.pages.auth.register');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['nullable', 'string', 'email', 'max:255', 'unique:' . Customer::class],
            'phone' => ['required', 'string', 'max:11', 'unique:' . Customer::class],
            'password' => ['required', 'min:4'],
        ]);

        $data['password'] = Hash::make($data['password']);
        $customer = Customer::create($data);
        $first_name = explode(' ', trim(strtolower($customer->name)))[0];
        
        $username = $first_name;
        $counter = 1;
        while (Customer::where('username', $username)->exists()) {
            $username = $first_name . $counter;
            $counter++;
        }
        
        $customer->username = $username;
        $customer->save();

        Auth::guard('customer')->login($customer);
        return redirect(RouteServiceProvider::HOME);
    }
}
