<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Devrabiul\ToastMagic\Facades\ToastMagic;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/dashboard';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'phone' => ['required', 'unique:users,phone'],
            'refer_code' => ['required'],
            'password' => ['required', 'string'],
        ]);
    }

    public function register(Request $request)
    {
        $this->validator($request->all())->validate();
        $referer = User::find($request->refer_code);

        if (!$referer || !$referer->verified_at) {
            return throw ValidationException::withMessages([
                'refer_by' => 'Invalid refer code'
            ]);
        }
        try {
            return DB::transaction(function() use($request, $referer){
                $user = User::create([
                    'name' => $request->name,
                    'phone' => $request->phone,
                    'refer_by' => $request->refer_code,
                    'email' => $request->email,
                    'password' => Hash::make($request->password),
                ]);
        
                $settings = config('app.settings');
                if ($amount = $settings['student_register_commission_to_referrer']) {
                    credit_balance($referer->id, $amount, "Student(#$user->id) regiter commission");
                }

                $data['user'] = $user;
                $data['password'] = $request->password;
                return view('auth.registration-success', $data);
            });
        } catch (\Throwable $th) {
            ToastMagic::error($th->getMessage());
            return redirect()->back();
        }
    }
}
