<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserPreference;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Carbon\Carbon;

class RegisterController extends Controller
{
    /**
     * Show the registration form.
     */
    public function showRegistrationForm()
    {
        return view('auth.register');
    }

    /**
     * Handle a registration request.
     */
    public function register(Request $request)
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        // Create user with 14-day trial
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'subscription_status' => 'trial',
            'trial_start_date' => Carbon::now(),
            'trial_expiry_date' => Carbon::now()->addDays(14),
        ]);

        // Create default preferences
        UserPreference::create([
            'user_id' => $user->id,
            'quiet_hours_start' => Carbon::now()->setTime(18, 0),
            'quiet_hours_end' => Carbon::now()->setTime(8, 0),
            'onboarding_completed' => false,
        ]);

        event(new Registered($user));

        Auth::login($user);

        // Redirect to onboarding if not completed
        if (!$user->preferences->onboarding_completed) {
            return redirect()->route('onboarding.start');
        }

        return redirect()->route('weekly-planner');
    }
}
