<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Mail\RegistrationMail;
use App\Models\Admin;
use App\Models\Package;
use App\Models\Purchase;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Carbon\Carbon;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules;
use Illuminate\View\View;

class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     */
    public function create(Request $request, $id=null)
    {
        if ($id)
        {
            User::find($id)->delete();
        }
//        http://localhost/crp10/register?ref_by=0000001
        $ref_by = $request->query('inviteCode');
        return view('app.auth.registration', compact('ref_by'));
    }

    /**
     * Handle an incoming registration request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'phone' => ['required', 'unique:users,phone'],
            'password' => ['required'],
            'ref_id' => ['required'],
        ]);

        if ($validate->fails()){
            return redirect()->back()->withErrors($validate->errors());
        }

        $checkPhone = User::where('phone', $request->phone)->first();
        if ($checkPhone){
            return redirect()->back()->with('error', 'ইতিমধ্যে একটি অ্যাকাউন্ট আছে.');
        }

        $user = User::create([
            'name' => $request->name,
            'username' => 'u'.$request->phone,
            'ref_id' => date('d').rand(9999999,1111111),
            'ref_by' => $request->ref_id ?? User::first()->ref_id,
            'email' => date('d').rand(999999,111911).'@gmail.com',
            'pcode' => $request->phoneCode,
            'phone' => $request->phone,
            'password' => Hash::make($request->password),
            'type' => 'user',
            'balance' => 0,
            'sign_every_day' => now(),
            'code' => $request->code,
            'remember_token' => Str::random(30),
        ]);

        if ($user){
            Auth::login($user);
            return redirect()->route('dashboard');
        }else{
            return redirect()->back()->with('error', 'Something wrong.');
        }
    }
}
