<?php

namespace App\Http\Controllers;

use App\Models\ChurchProfile;
use App\Models\Jumuiya;
use App\Models\Member;
use App\Models\MemberPosition;
use App\Models\Setting;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;

class AuthController extends Controller
{
    public function showLogin(): View
    {
        return view('auth.login', [
            'profile' => ChurchProfile::first(),
            'registrationOpen' => $this->publicRegistrationOpen(),
        ]);
    }

    public function showRegister(): View|RedirectResponse
    {
        if (! $this->publicRegistrationOpen()) {
            return redirect()->route('login')->with('error', 'Registration imefungwa kwa sasa.');
        }

        return view('auth.register', [
            'profile' => ChurchProfile::first(),
            'jumuiyas' => Jumuiya::where('status', 'active')->orderBy('name')->get(),
            'positions' => MemberPosition::where('status', 'active')->orderBy('name')->get(),
        ]);
    }

    public function registerMember(Request $request): RedirectResponse
    {
        if (! $this->publicRegistrationOpen()) {
            return redirect()->route('login')->with('error', 'Registration imefungwa kwa sasa.');
        }

        $data = $request->validate([
            'first_name' => ['required', 'string', 'max:255'],
            'middle_name' => ['nullable', 'string', 'max:255'],
            'last_name' => ['required', 'string', 'max:255'],
            'gender' => ['nullable', 'in:Male,Female'],
            'date_of_birth' => ['nullable', 'date'],
            'phone' => ['required', 'string', 'max:50'],
            'email' => ['nullable', 'email', 'max:255'],
            'address' => ['nullable', 'string'],
            'jumuiya_id' => ['nullable', 'exists:jumuiyas,id'],
            'member_position_id' => ['nullable', 'exists:member_positions,id'],
        ]);

        $defaultStatus = Setting::where('group', 'registration')
            ->where('key', 'default_member_status')
            ->value('value') ?: 'active';

        if (! in_array($defaultStatus, ['active', 'inactive'], true)) {
            $defaultStatus = 'active';
        }

        $member = Member::create($data + [
            'status' => $defaultStatus,
            'is_baptized' => false,
            'is_confirmed' => false,
            'is_allowed_sacrament' => false,
            'notes' => 'Self-registered from public registration form.',
        ]);

        $this->logActivity('created', 'members', "Self registration submitted for {$member->full_name}");

        return redirect()->route('login')->with('success', 'Registration yako imepokelewa. Ofisi ya kanisa itathibitisha taarifa zako.');
    }

    public function login(Request $request): RedirectResponse
    {
        $credentials = $request->validate([
            'login' => ['required', 'string'],
            'password' => ['required', 'string'],
        ]);

        $remember = $request->boolean('remember');
        $loginField = filter_var($credentials['login'], FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

        if (! Auth::attempt([$loginField => $credentials['login'], 'password' => $credentials['password'], 'status' => 'active'], $remember)) {
            throw ValidationException::withMessages([
                'login' => 'Taarifa za kuingia si sahihi au user hayupo active.',
            ]);
        }

        $request->session()->regenerate();
        $request->user()->update(['last_login_at' => now()]);

        return redirect()->intended(route('dashboard'))->with('success', 'Karibu kwenye church office dashboard.');
    }

    public function logout(Request $request): RedirectResponse
    {
        Auth::logout();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('login')->with('success', 'Umetoka kwenye mfumo.');
    }

    private function publicRegistrationOpen(): bool
    {
        return Setting::where('group', 'registration')
            ->where('key', 'is_open')
            ->value('value') === 'Yes';
    }
}
