<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\MobileVerification;
use App\Models\User;
use App\Services\PayamMatni;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class RegisterController extends Controller
{
    use RegistersUsers;

    protected $redirectTo = '/';

    public function __construct()
    {
        $this->middleware('guest');
    }

    protected function validator(array $data)
    {
        return Validator::make($data, [
            'first_name' => ['required', 'string', 'max:255', 'regex:/^[\x{0600}-\x{06FF}\x{200C}\s]+$/u'],
            'last_name'  => ['required', 'string', 'max:255', 'regex:/^[\x{0600}-\x{06FF}\x{200C}\s]+$/u'],
            'mobile'     => ['required', 'bail', 'numeric', 'digits:11', 'unique:users'],
            'password'   => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    protected function create(array $data)
    {
        return User::create([
            'first_name' => $data['first_name'],
            'last_name'  => $data['last_name'],
            'mobile'     => $data['mobile'],
            'password'   => Hash::make($data['password']),
        ]);
    }

    protected function registered(Request $request, $user)
    {
        $now  = now();
        $code = str_pad(random_int(10000, 99999), 5, '0', STR_PAD_LEFT);

        MobileVerification::updateOrCreate(
            ['mobile' => $user->mobile],
            [
                'code'          => $code,
                'expires_at'    => $now->copy()->addMinutes(5),
                'last_sent_at'  => $now,
                'sent_count'    => 1,
                'first_sent_at' => $now,
            ]
        );

        PayamMatni::sendOtp($user->mobile, $code);

        return redirect()->route('mobile.verify');
    }
}
