<?php

namespace App\Http\Controllers\admin\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class RegisteredUserController extends Controller
{
    public function create()
    {
        return view('auth.register');
    }

    public function store(Request $request)
    {
        // Validate the incoming request
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'phone_number' => 'required|string|max:255|unique:users',
            'password' => 'required|string|confirmed|min:8',
        ]);

        // Generate a unique user_id
        $userIdPrefix = 'admin';
        $latestUser = DB::table('users')->orderBy('id', 'desc')->first();
        $newUserIdSuffix = $latestUser ? str_pad((int)substr($latestUser->user_id, 5) + 1, 6, '0', STR_PAD_LEFT) : '000001';
        $userId = $userIdPrefix . $newUserIdSuffix;

        // Insert user data into the users table
        $userId = DB::table('users')->insertGetId([
            'user_id' => $userId, // Add the new user_id
            'name' => $request->name,
            'email' => $request->email,
            'phone_number' => $request->phone_number,
            'password' => Hash::make($request->password),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        // Log in the newly created user
        Auth::loginUsingId($userId);

        return redirect()->route('dashboard');
    }
}
