<?php

namespace App\Http\Controllers;

use App\Models\Setting;
use App\Models\SecurityLog;
use App\Models\User;
use App\Models\AgencyNotification;
use App\Models\NotificationSetting;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\View\View;

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

    public function showRegister(): View
    {
        abort_unless($this->registrationEnabled(), 404);

        return view('auth.register');
    }

    public function register(Request $request): RedirectResponse
    {
        abort_unless($this->registrationEnabled(), 404);

        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'business_name' => ['nullable', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255', 'unique:users,email'],
            'phone' => ['nullable', 'string', 'max:50'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);

        $user = User::create([
            'name' => $data['name'],
            'business_name' => $data['business_name'] ?? null,
            'email' => $data['email'],
            'phone' => $data['phone'] ?? null,
            'password' => Hash::make($data['password']),
            'role' => 'client',
            'client_type' => 'plan',
            'status' => 'active',
        ]);

        Auth::login($user);
        $request->session()->regenerate();
        $this->logLogin($request);
        $this->notifyAdmin('new_client_registered', 'New client registered', $user->name.' created a client portal account.');

        return redirect()->route('client.dashboard')->with('status', 'Client portal account created.');
    }

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

        if (! Auth::attempt($credentials, $request->boolean('remember'))) {
            SecurityLog::create(['ip_address' => $request->ip(), 'device' => substr((string) $request->userAgent(), 0, 255), 'login_time' => now(), 'status' => 'failed']);
            return back()->withErrors(['email' => 'Invalid login details.'])->onlyInput('email');
        }

        $request->session()->regenerate();
        $this->logLogin($request);

        return $this->redirectToPortal($request);
    }

    public function demoLogin(Request $request, string $role): RedirectResponse
    {
        abort_unless($this->demoLoginEnabled(), 404);

        $email = match ($role) {
            'admin' => 'admin@mgg.test',
            'client' => 'client@mgg.test',
            'designer' => 'designer@mgg.test',
            'gts-client' => 'gts-client@mgg.test',
            default => abort(404),
        };

        if (! Auth::attempt(['email' => $email, 'password' => 'password'])) {
            return back()->withErrors(['email' => ucfirst($role).' demo login is not available.']);
        }

        $request->session()->regenerate();
        $this->logLogin($request);

        return $this->redirectToPortal($request);
    }

    private function redirectToPortal(Request $request): RedirectResponse
    {
        if ($request->user()->isAdminRole()) {
            return redirect()->route('admin.portal');
        }

        return redirect()->intended(match ($request->user()->portalRole()) {
            'designer' => route('designer.dashboard'),
            'gts-client' => route('gts-client.dashboard'),
            default => route('client.dashboard'),
        });
    }

    public function logout(Request $request): RedirectResponse
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('home');
    }

    private function demoLoginEnabled(): bool
    {
        return Setting::where('key', 'demo_login_enabled')->value('value') !== '0';
    }

    private function registrationEnabled(): bool
    {
        return Setting::enabled('client_registration_enabled', false);
    }

    private function logLogin(Request $request): void
    {
        SecurityLog::create([
            'user_id' => $request->user()->id,
            'ip_address' => $request->ip(),
            'device' => substr((string) $request->userAgent(), 0, 255),
            'location' => 'Unknown',
            'login_time' => now(),
            'status' => 'success',
        ]);
    }

    private function notifyAdmin(string $type, string $title, string $body): void
    {
        if (NotificationSetting::where('notification_type', $type)->value('dashboard_enabled') ?? true) {
            AgencyNotification::create(['title' => $title, 'body' => $body, 'audience' => 'admin', 'status' => 'unread']);
        }
    }
}
