<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Subscription;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;

class AuthController extends Controller
{
    /**
     * Show register form
     */
    public function showRegistrationForm(): View|RedirectResponse
    {
        if (Auth::guard('web')->check()) {
            return redirect()->route('user.dashboard');
        }

        return view('user.auth.register');
    }

    /**
     * Register new user
     */
    public function register(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'name'     => ['required', 'string', 'max:255'],
            'username' => ['required', 'string', 'min:3', 'max:50', 'alpha_dash', 'unique:users,username'],
            'phone'    => ['required', 'string', 'min:11', 'max:20', 'unique:users,phone'],
            'email'    => ['required', 'email', 'max:255', 'unique:users,email'],
            'password' => ['required', 'string', 'min:6', 'confirmed'],
        ]);

        do {
            $uid = strtoupper(Str::random(6));
        } while (User::where('uid', $uid)->exists());

        $user = User::create([
            'uid'      => $uid,
            'name'     => $validated['name'],
            'username' => $validated['username'],
            'phone'    => $validated['phone'],
            'email'    => $validated['email'],
            'password' => Hash::make($validated['password']),
            'status'   => 'active',
        ]);

        Subscription::create([
            'user_id'    => $user->id,
            'plan_id'    => 1,
            'start_date' => Carbon::now(),
            'end_date'   => Carbon::now()->addDays(30),
            'status'     => 'active',
            'is_trial'   => true,
        ]);

        return redirect()
            ->route('user.login')
            ->with('register_success', __('User_Auth_Controller.messages.register_success'))
            ->with('swal', [
                'icon'  => 'success',
                'title' => __('User_Auth_Controller.swal.registration_successful_title'),
                'text'  => __('User_Auth_Controller.swal.account_created_successfully'),
            ]);
    }

    /**
     * Show login form
     */
    public function showLoginForm(): View|RedirectResponse
    {
        if (Auth::guard('web')->check()) {
            return redirect()->route('user.dashboard');
        }

        return view('user.auth.login');
    }

    /**
     * Login user with email / phone / username
     */
    public function login(Request $request): RedirectResponse
    {
        $request->validate([
            'login'    => ['required', 'string'],
            'password' => ['required', 'string'],
        ]);

        $loginValue = trim($request->input('login'));

        $loginType = filter_var($loginValue, FILTER_VALIDATE_EMAIL)
            ? 'email'
            : (is_numeric($loginValue) ? 'phone' : 'username');

        $credentials = [
            $loginType => $loginValue,
            'password' => $request->input('password'),
        ];

        $remember = $request->boolean('remember');

        if (!Auth::guard('web')->attempt($credentials, $remember)) {
            throw ValidationException::withMessages([
                'login' => [__('User_Auth_Controller.validation.invalid_credentials')],
            ]);
        }

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

        /** @var \App\Models\User|null $user */
        $user = Auth::guard('web')->user();

        if (!$user) {
            Auth::guard('web')->logout();

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

            throw ValidationException::withMessages([
                'login' => [__('User_Auth_Controller.validation.login_failed_try_again')],
            ]);
        }

        if (($user->status ?? 'inactive') !== 'active') {
            Auth::guard('web')->logout();

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

            throw ValidationException::withMessages([
                'login' => [__('User_Auth_Controller.validation.account_inactive_or_blocked')],
            ]);
        }

        $user->update([
            'last_login_at'    => now(),
            'last_activity_at' => now(),
        ]);

        return redirect()->route('user.dashboard');
    }

    /**
     * Logout user
     */
    public function logout(Request $request): RedirectResponse
    {
        $user = Auth::guard('web')->user();

        if ($user) {
            $user->update([
                'last_logout_at'   => now(),
                'last_activity_at' => now(),
            ]);
        }

        Auth::guard('web')->logout();

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

        return redirect()
            ->route('login')
            ->with('swal', [
                'icon'  => 'success',
                'title' => __('User_Auth_Controller.swal.logged_out_title'),
                'text'  => __('User_Auth_Controller.swal.logged_out_successfully'),
            ]);
    }

    /**
     * AJAX username availability check
     */
    public function checkUsername(Request $request): JsonResponse
    {
        $request->validate([
            'username' => ['required', 'string', 'min:3', 'max:50', 'alpha_dash'],
        ]);

        $username = trim($request->username);

        $exists = User::where('username', $username)->exists();

        return response()->json([
            'available' => !$exists,
            'message'   => $exists
                ? __('User_Auth_Controller.username.this_username_is_already_taken')
                : __('User_Auth_Controller.username.this_username_is_available'),
        ]);
    }
}