<?php

namespace App\Http\Controllers\User;

use Auth;
use App\Models\User;
use App\Models\Wallet;
use App\Models\Country;
use App\Models\LoginLogs;
use Illuminate\Http\Request;
use App\Models\Generalsetting;
use App\Traits\RespondsWithHttp;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Str;

class AuthController extends Controller
{
    use RespondsWithHttp;

    public function __construct()
    {
        $this->middleware('guest:web', ['except' => ['logout']]);
    }

    public function registerForm(Request $request, $ref = null)
    {
        $gs = Generalsetting::first();
        if ($gs->registration == 0) {
            return $this->respondWithError($request, 'Registration is currently off.');
        }

        if ($this->expectsJson($request)) {
            return $this->respond($request, [], 'Registration form not available via API.');
        }

        $countries = Country::get();
        $info = @loginIp();
        $refer = $ref;
        return view('user.register', compact('countries', 'info', 'refer'));
    }

    public function register(Request $request)
    {
        $gs = Generalsetting::first();
        if ($gs->registration == 0) {
            return $this->respondWithError($request, 'Registration is currently off.');
        }

        $countries = Country::query();
        $name = $countries->pluck('name')->toArray();

        $rules = [
            'surname' => 'required',
            'first_name' => 'required',
            'email' => [
                'required',
                'email',
                'unique:users',
                $gs->allowed_email != null ? 'email_domain:' . $request->email : '',
            ],
            'phone' => 'required',
            'dial_code' => 'required',
            'country' => 'required|in:' . implode(',', $name),
            'password' => 'required|min:6|confirmed',
        ];

        if (!$this->expectsJson($request)) {
            $rules['captcha'] = 'required|captcha';
        }

        $data = $request->validate($rules, [
            'email.email_domain' => 'Allowed emails are only within : ' . $gs->allowed_email,
            'captcha.required' => 'Please verify that you are not a robot.',
            'captcha.captcha' => 'The CAPTCHA verification failed. Please try again.',
        ]);

        $currency = $countries->where('name', $request->country)->value('currency_id');
        $data['phone'] = $request->dial_code . $request->phone;
        $data['password'] = bcrypt($request->password);
        $data['email_verified'] = 0;
        $data['name'] = $request['surname'] . ' ' . $request['first_name'];
        $cAccount = getCryptoAccountNumber();
        $data['crypto_account_number'] = $cAccount;
        $data['crypto_account_code'] = 'R2T' . $cAccount;
        $data['crypto_customer_id'] = 'R2TCUS' . $cAccount;

        if (!empty($request->referer_code)) {
            $data['refer_by'] = User::getRefererId($request->referer_code);
        }

        $user = User::create($data);

        Wallet::create([
            'user_id' => $user->id,
            'user_type' => 1,
            'currency_id' => $currency,
            'registration_bonus' => '10000',
            'balance' => 0,
        ]);

        Auth::guard('web')->attempt(['email' => $request->email, 'password' => $request->password]);

        $token = $this->expectsJson($request) ? $user->createToken('api-token')->plainTextToken : null;

        if ($user->email_verified != 1) {
            $user->verify_code = randNum();
            $user->save();
            try {
                @email([
                    'email' => $user->email,
                    'name' => $user->name,
                    'subject' => __('Email Verification Code'),
                    'message' => __('Email Verification Code is : ') . $user->verify_code,
                ]);
            } catch (\Exception $e) {
                \Log::error('Email sending failed: ' . $e->getMessage());
            }
            return $this->respond(
                $request,
                $this->expectsJson($request) ? ['success' => true, 'token' => $token] : ['token' => $token],
                'Registration successful, please verify your email.',
                'user.verify.email'
            );
        }

        return $this->respond(
            $request,
            $this->expectsJson($request) ? ['success' => true, 'token' => $token] : ['token' => $token],
            'Registration successful.',
            'user.dashboard'
        );
    }

    public function showLoginForm(Request $request)
    {
        if ($this->expectsJson($request)) {
            return $this->respond($request, [], 'Login form not available via API.');
        }
        return view('user.login');
    }

    public function login(Request $request)
    {
        $rules = [
            'email' => 'required|string|max:250|email',
            'password' => 'required|max:255',
        ];

        if (!$this->expectsJson($request)) {
            $rules['captcha'] = 'required|captcha';
        }

        $data = $request->validate($rules, [
            'captcha.required' => 'Please verify that you are not a robot.',
            'captcha.captcha' => 'The CAPTCHA verification failed. Please try again.',
        ]);

        if (Auth::guard('web')->attempt(['email' => $request->email, 'password' => $request->password])) {
            $user = Auth::user();

            LoginLogs::create([
                'user_id' => $user->id,
                'ip' => @loginIp()->geoplugin_request,
                'country' => @loginIp()->geoplugin_countryName,
                'city' => @loginIp()->geoplugin_city,
            ]);

            $token = $this->expectsJson($request) ? $user->createToken('api-token')->plainTextToken : null;

            // Prepare user details for API response
            $userDetails = $this->expectsJson($request) ? [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'phone' => $user->phone,
                'country' => $user->country,
                'email_verified' => (bool) $user->email_verified,
                'twostep_enabled' => (bool) $user->twostep_enabled,
                'created_at' => $user->created_at->toISOString(),
                'updated_at' => $user->updated_at->toISOString()
            ] : [];

            if ($user->email_verified != 1) {
                return $this->respond(
                    $request,
                    ['token' => $token, 'user' => $userDetails],
                    'Login successful, please verify your email.',
                    'user.verify.email'
                );
            }

            if ($user->twostep_enabled && !$request->session()->has('twostep_verified')) {
                $user->two_step_code = randNum();
                $user->save();
                try {
                    @email([
                        'email' => $user->email,
                        'name' => $user->name,
                        'subject' => __('Two-Step Verification Code'),
                        'message' => __('Two-Step Verification Code is: ') . $user->two_step_code,
                    ]);
                } catch (\Exception $e) {
                    \Log::error('Two-step email failed: ' . $e->getMessage());
                }

                return $this->respond(
                    $request,
                    ['token' => $token, 'user' => $userDetails],
                    'Please complete two-step verification.',
                    'user.two.step.verification'
                );
            }

            return $this->respond(
                $request,
                ['token' => $token, 'user' => $userDetails],
                'Login successful.',
                'user.dashboard'
            );
        }

        return $this->respondWithError($request, "Credentials don't match!");
    }

    public function logout(Request $request)
    {
        if (auth()->check()) {
            $auth = Auth::guard('web');
            if ($auth->user()->two_fa_status == 1) {
                $auth->user()->two_fa = 1;
                $auth->user()->save();
            }
            if ($this->expectsJson($request)) {
                $auth->user()->tokens()->delete();
            }
            Auth::guard('web')->logout();
        }

        return $this->respond($request, [], 'Logout successful.', 'user.login');
    }

    public function forgotPassword(Request $request)
    {
        if (auth()->check()) {
            return $this->respondWithError($request, 'You are already logged in.');
        }

        if ($this->expectsJson($request)) {
            return $this->respond($request, [], 'Forgot password form not available via API.');
        }

        return view('user.forgot_password');
    }

    public function forgotPasswordSubmit(Request $request)
    {
        $rules = [
            'email' => 'required|email',
        ];

        if (!$this->expectsJson($request)) {
            $rules['captcha'] = 'required|captcha';
        }

        $data = $request->validate($rules, [
            'captcha.required' => 'Please verify that you are not a robot.',
            'captcha.captcha' => 'The CAPTCHA verification failed. Please try again.',
        ]);

        $user = User::where('email', $request->email)->first();

        if (!$user) {
            return $this->respondWithError($request, "Sorry! Email doesn't exist.");
        }

        $user->verify_code = randNum();
        $user->save();

        $resetToken = Str::random(32);
        cache()->put('password_reset:' . $resetToken, $user->email, now()->addHours(1));

        try {
            @email([
                'email' => $user->email,
                'name' => $user->name,
                'subject' => __('Password Reset Code'),
                'message' => __('Password reset code is: ') . $user->verify_code,
            ]);
        } catch (\Exception $e) {
            \Log::error('Password reset email failed: ' . $e->getMessage());
        }

        return $this->respond(
            $request,
            $this->expectsJson($request) ? ['reset_token' => $resetToken] : [],
            'A password reset code has been sent to your email.',
            'user.verify.code'
        );
    }

    public function verifyCode(Request $request)
    {
        if ($this->expectsJson($request)) {
            return $this->respond($request, [], 'Verification code form not available via API.');
        }
        return view('user.verify_code');
    }

    public function verifyCodeSubmit(Request $request)
    {
        $rules = [
            'code' => 'required|integer',
        ];

        if ($this->expectsJson($request)) {
            $rules['reset_token'] = 'required|string';
        } else {
            $rules['captcha'] = 'required|captcha';
        }

        $data = $request->validate($rules, [
            'captcha.required' => 'Please verify that you are not a robot.',
            'captcha.captcha' => 'The CAPTCHA verification failed. Please try again.',
        ]);

        $email = $this->expectsJson($request) ? cache()->get('password_reset:' . $request->reset_token) : session('email');

        if (!$email) {
            return $this->respondWithError($request, 'Invalid or expired reset token.');
        }

        $user = User::where('email', $email)->first();

        if (!$user) {
            return $this->respondWithError($request, "User doesn't exist.");
        }

        if ($user->verify_code != $request->code) {
            return $this->respondWithError($request, 'Invalid verification code.');
        }

        if ($this->expectsJson($request)) {
            cache()->put('reset_verified:' . $request->reset_token, $user->email, now()->addHours(1));
            return $this->respond($request, ['reset_token' => $request->reset_token], 'Verification successful.', null);
        }

        session()->put('reset', true);
        return $this->respond($request, [], 'Verification successful.', 'user.reset.password');
    }

    public function resetPassword(Request $request)
    {
        if ($this->expectsJson($request)) {
            return $this->respond($request, [], 'Reset password form not available via API.');
        }

        if (!session('reset')) {
            return $this->respond($request, [], 'Session expired.', 'user.verify.code');
        }

        return view('user.reset_password');
    }

    public function resetPasswordSubmit(Request $request)
    {
        $rules = [
            'password' => 'required|confirmed|min:6',
        ];

        if ($this->expectsJson($request)) {
            $rules['reset_token'] = 'required|string';
        } else {
            $rules['captcha'] = 'required|captcha';
        }

        $data = $request->validate($rules, [
            'captcha.required' => 'Please verify that you are not a robot.',
            'captcha.captcha' => 'The CAPTCHA verification failed. Please try again.',
        ]);

        $email = $this->expectsJson($request) ? cache()->get('reset_verified:' . $request->reset_token) : session('email');

        if (!$email) {
            return $this->respondWithError($request, 'Invalid or expired reset token.');
        }

        $user = User::where('email', $email)->first();
        if (!$user) {
            return $this->respondWithError($request, "User doesn't exist.");
        }

        $user->password = bcrypt($request->password);
        $user->verify_code = null;
        $user->update();

        if ($this->expectsJson($request)) {
            cache()->forget('reset_verified:' . $request->reset_token);
            cache()->forget('password_reset:' . $request->reset_token);
        } else {
            session()->forget('reset');
            session()->forget('email');
        }

        return $this->respond($request, [], 'Password reset successful.', 'user.login');
    }
}