<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\MemberTier;
use App\Models\Tier;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
use App\Notifications\WelcomeNotification;

class RegisterController extends Controller
{
    public function register(Request $request)
    {
        $data = $request->validate([
            'name'                  => ['required', 'string', 'max:100'],
            'email'                 => ['required', 'email', 'unique:users,email'],
            'phone'                 => ['required', 'string', 'max:20'],
            'password'              => ['required', 'confirmed', Password::min(8)],
        ]);

        $enrolledAt = now();
        $user = User::create([
            'membership_number' => $this->generateMembershipNumber(),
            'first_name'        => $data['name'],
            'last_name'         => '',
            'email'             => $data['email'],
            'phone'             => $data['phone'],
            'password'          => Hash::make($data['password']),
            'status'            => 'active',
            'enrolled_at'       => $enrolledAt,
            'points_expiry_date' => $enrolledAt->copy()->addYear()->toDateString(),
            'points_balance'    => 0,
        ]);

        // Assign Invited tier on registration
        $invitedTier = Tier::where('slug', 'invited')->first();
        if ($invitedTier) {
            MemberTier::create([
                'user_id'         => $user->id,
                'tier_id'         => $invitedTier->id,
                'is_current'      => true,
                'assignment_type' => 'initial',
                'assigned_at'     => now(),
            ]);
        }

        event(new Registered($user));
        Auth::guard('web')->login($user);

        // Queue welcome email
        $user->notify(new WelcomeNotification());

        return redirect()->route('verification.notice');
    }

    private function generateMembershipNumber(): string
    {
        do {
            $number = 'JAM' . strtoupper(substr(uniqid(), -6));
        } while (User::where('membership_number', $number)->exists());

        return $number;
    }
}
