<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use App\Mail\WelcomeMail;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Auth;


class RegisterController extends Controller
{



    public function store(Request $request)
    {
        $validated = $request->validate([
            'email' => 'required|email|unique:users,email',
            'password' => 'required|min:6',
            'confirmpassword' => 'required|same:password',
            'terms' => 'accepted',
        ]);

        $user = User::create([
            'email' => $validated['email'],
            'password' => Hash::make($validated['password']),
        ]);

        // 🔐 Auto-login user
        // 🔐 Auto-login user
        // Auth::login($user, true);


        // 📧 Send email verification
        $user->sendEmailVerificationNotification();

        // ✅ Send welcome email (optional)
        // Mail::to($user->email)->send(new WelcomeMail($user));

        // 📤 AJAX response
        if ($request->wantsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Account created successfully! Please verify your email.',
                'redirect' => url('/email/verify'),
            ]);
        }

        // 📥 Redirect to email verification page
        return redirect()->route('verification.notice')->with('toast', [
            'type' => 'success',
            'message' => 'Account created successfully! Please verify your email.',
        ]);
    }
}
