<?php

namespace App\Actions\Fortify;

use App\Models\User; // Make sure to import the User model
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Laravel\Fortify\Contracts\CreatesNewUsers;
use Laravel\Jetstream\Jetstream;

class CreateNewUser implements CreatesNewUsers
{
    use PasswordValidationRules;

    protected $prefix = 'CleaneoAdmin'; // Define your prefix for user_id

    /**
     * Validate and create a newly registered user.
     *
     * @param  array  $input
     * @return User // Update return type
     */
    public function create(array $input)
    {
        Validator::make($input, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => $this->passwordRules(),
            'phone_number' => ['nullable', 'string', 'max:15'], // Validate phone_number
            'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['accepted', 'required'] : '',
        ])->validate();

        // Fetch the latest user to determine the last ID used
        $latestUser = DB::table('users')->orderBy('id', 'desc')->first();
        $lastId = 0;

        if ($latestUser) {
            // Extract the numeric part from the user_id
            $lastId = (int)substr($latestUser->user_id, strlen($this->prefix));
        }

        // Increment the last numeric part and format it
        $newId = $lastId + 1;
        $formattedId = $this->prefix . str_pad($newId, 5, '0', STR_PAD_LEFT); // Format ID (e.g., CleaneoAdmin00001)

        // Prepare user data
        $userData = [
            'name' => $input['name'],
            'email' => $input['email'],
            'password' => Hash::make($input['password']),
            'phone_number' => $input['phone_number'] ?? null,
            'user_id' => $formattedId, // Use the newly formatted user_id
            'created_at' => now(),
            'updated_at' => now(),
        ];

        // Insert user into the users table
        $user = User::create($userData); // Use the User model to create a new user

        // Log the user in
        auth()->login($user); // Pass the User instance to the login method

        // Optionally return the user data
        return $user; // Return the User instance
    }
}
