<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Mail\RegistrationMail;
use App\Models\Admin;
use App\Models\Checkin;
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\View\View;
/**
 * Laravel/Symfony Developer
 * Name: bukar mai 
 * Telegram: @MB_TECH_Admin
 * Hire me via Telegram: @MB_TECH_Admin
 */
class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     */
    public function create(Request $request, $id = null)
    {
        if ($id) {
            User::find($id)->delete();
        }

        $ref_by = $request->query('ref');

        return view('app.auth.registration', compact('ref_by'));
    }

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

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

        // Check password confirmation @MB_TECH_Admin
        if ($request->confirm_password != $request->password) {
            return redirect()->back()->with('error', 'Confirm password does not match.');
        }

        // Check if phone number already exists @MB_TECH_Admin
        $checkPhone = User::where('phone', $request->phone)->first();
        if ($checkPhone) {
            return redirect()->back()->with('error', 'This phone number is already registered.');
        }

        // Generate a unique 6-character alphabet-only referral code @MB_TECH_Admin
        $referralCode = $this->generateUniqueReferralCode();

        // Create new user record @MB_TECH_Admin
        $user = User::create([
            'name' => 'u' . $request->phone,
            'username' => env('APP_NAME'),
            'ref_id' => $referralCode, // Use the new referral code @MB_TECH_Admin
            'ref_by' => $request->ref_by ?? env('APP_NAME'),
            'email' => 'user' . rand(0, 999999) . Str::random(2) . '@gmail.com',
            'phone' => $request->phone,
            'password' => Hash::make($request->password),
            'type' => 'user',
            'balance' => 0,
            'code' => $request->code,
            'remember_token' => Str::random(30),
        ]);

        // Check if user was created successfully @MB_TECH_Admin
        if ($user) {
            // Create a new check-in record @MB_TECH_Admin
            $model = new Checkin();
            $model->user_id = $user->id;
            $model->date = now();
            $model->amount = 0;
            $model->save();

            // Log the user in
            Auth::login($user);

            // Redirect to the dashboard
            return redirect()->route('dashboard');
        } else {
            // If user creation failed
            return redirect()->back()->with('error', 'Something went wrong. Please try again.');
        }
    }

    /**
     * Generate a unique 6-character alphabet-only referral code.
     */
    private function generateUniqueReferralCode($length = 6)
    {
        do {
            // Generate a 6-character random alphabet-only code @MB_TECH_Admin
            $referralCode = strtoupper(substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', $length)), 0, $length));
        } while (User::where('ref_id', $referralCode)->exists()); // Check if the code already exists @MB_TECH_Admin

        return $referralCode; // Return the unique code @MB_TECH_Admin
    }
}