<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\BusinessUser;
use App\Models\User;
use App\Models\Business;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Mail;
use App\Mail\EmailVerificationMail;

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 = '/index';

    /**
     * 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, [
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'name' => ['required', 'string', 'max:255'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    /**
     * Show the registration form
     */
    public function showRegisterForm()
    {
        return view('authentication.register');
    }

    /**
     * Handle registration request
     */
    public function register(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ]);

        // Create user but don't verify email yet
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'email_verified_at' => null, // Make sure email is not verified
        ]);

        // Send verification email
        $verificationUrl = $this->sendVerificationEmail($user);

        return redirect()->route('verification.notice')
                        ->with('success', 'Registration successful! Please check your email for verification link.')
                        ->with('verification_url', $verificationUrl);
    }

    /**
     * Send verification email to user
     */
    protected function sendVerificationEmail(User $user)
    {
        $verificationUrl = URL::temporarySignedRoute(
            'verification.verify',
            now()->addMinutes(60), // Link expires in 1 hour
            [
                'id' => $user->getKey(),
                'hash' => sha1($user->getEmailForVerification()),
            ]
        );

        Mail::to($user->email)->send(new EmailVerificationMail($user, $verificationUrl));

        return $verificationUrl;
    }

    /**
     * Show email verification notice
     */
    public function showVerificationNotice()
    {
        return view('authentication.verify-email');
    }

    /**
     * Handle email verification
     */
    public function verify(Request $request)
    {
        $user = User::find($request->route('id'));

        if (!$user) {
            return redirect()->route('register')->with('error', 'Invalid verification link.');
        }

        if ($user->hasVerifiedEmail()) {
            // Check if user already has business setup
            if ($user->business_id) {
                return redirect()->route('login')->with('info', 'Email already verified and business setup completed. Please login.');
            }
            return redirect()->route('business.index')->with('info', 'Email already verified. Please setup your business.');
        }

        if (hash_equals((string) $request->route('hash'), sha1($user->getEmailForVerification()))) {
            $user->markEmailAsVerified();
            
            // Log in the user automatically after verification
            Auth::login($user);
            
            return redirect()->route('business.index')->with('success', 'Email verified successfully! Please setup your business.');
        }

        return redirect()->route('register')->with('error', 'Invalid verification link.');
    }

    /**
     * Resend verification email
     */
    public function resendVerificationEmail(Request $request)
    {
        $request->validate(['email' => 'required|email']);

        $user = User::where('email', $request->email)->first();

        if (!$user) {
            return back()->with('error', 'User not found.');
        }

        if ($user->hasVerifiedEmail()) {
            return redirect()->route('business.index');
        }

        $verificationUrl = $this->sendVerificationEmail($user);

        return back()
            ->with('success', config('mail.default') === 'log'
                ? 'Verification link generated for local development.'
                : 'Verification email sent!')
            ->with('verification_url', $verificationUrl);
    }
}
