<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Mail\RegistrationReceivedMail;
use App\Models\User;
use App\Services\MailService;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Validation\Rules;
use Inertia\Inertia;
use Inertia\Response;

class RegisteredUserController extends Controller
{
    public function create(): Response
    {
        return Inertia::render('Auth/Register');
    }

    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name'     => 'required|string|max:255',
            'email'    => 'required|string|lowercase|email|max:255|unique:'.User::class,
            'phone'    => 'required|digits:11|unique:'.User::class,
            'church'   => 'required|string|max:255',
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $autoApprove = DB::table('settings')
            ->where('key', 'auto_approve_registrations')
            ->value('value') === '1';

        $user = User::create([
            'name'     => $request->name,
            'email'    => $request->email,
            'phone'    => $request->phone,
            'church'   => $request->church,
            'password' => Hash::make($request->password),
            'role'     => 'user',
            'status'   => $autoApprove ? 'approved' : 'pending',
        ]);

        event(new Registered($user));

        // Admin notification for new registration (only when not auto-approved)
        if (!$autoApprove) {
            DB::table('admin_notifications')->insert([
                'type'       => 'new_registration',
                'data'       => json_encode(['user_name' => $user->name, 'user_id' => $user->id, 'email' => $user->email]),
                'is_read'    => false,
                'created_at' => now(),
            ]);
        }

        // Email to user confirming registration received
        if (!$autoApprove && MailService::isEnabled('registration')) {
            try {
                MailService::configure();
                Mail::to($user->email)->send(new RegistrationReceivedMail(userName: $user->name));
            } catch (\Exception) {}
        }

        Auth::login($user);

        return redirect()->route('account.index');
    }
}
