<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Setting;
use App\Services\WaSenderService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    public function create()
    {
        return view('auth.login');
    }

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

        $loginType = filter_var($request->login, FILTER_VALIDATE_EMAIL) ? 'email' : 'phone';

        // Find user by email or phone
        $user = User::where($loginType, $request->login)->first();

        if (!$user || !Auth::validate(['email' => $user->email, 'password' => $request->password])) {
            throw ValidationException::withMessages([
                'login' => trans('auth.failed'),
            ]);
        }

        // Check if OTP is enabled
        if (Setting::getValue('security', 'enable_otp', false)) {
            // Generate OTP
            $otp = $user->generateOtp();

            // Send OTP via WaSender
            if ($user->phone) {
                try {
                    $waSender = new WaSenderService();
                    if ($waSender->isConfigured()) {
                        $waSender->sendMessage($user->phone, "Your verification code is: {$otp}");
                    }
                } catch (\Exception $e) {
                    \Log::error("Failed to send OTP: " . $e->getMessage());
                }
            }

            // Store user ID and remember preference in session for OTP verification
            $request->session()->put('auth.otp_user_id', $user->id);
            $request->session()->put('auth.remember', $request->boolean('remember'));

            return redirect()->route('login.otp');
        }

        // Standard Login
        Auth::login($user, $request->boolean('remember'));
        $request->session()->regenerate();

        return redirect()->intended('dashboard');
    }

    public function showOtpForm()
    {
        if (!session()->has('auth.otp_user_id')) {
            return redirect()->route('login');
        }

        return view('auth.otp');
    }

    public function verifyOtp(Request $request)
    {
        $request->validate([
            'otp' => ['required', 'string', 'size:6'],
        ]);

        $userId = session('auth.otp_user_id');
        if (!$userId) {
            return redirect()->route('login');
        }

        $user = User::find($userId);

        if (!$user || $user->otp_code !== $request->otp || $user->otp_expires_at->isPast()) {
            throw ValidationException::withMessages([
                'otp' => __('Invalid or expired verification code.'),
            ]);
        }

        // Clear OTP
        $user->otp_code = null;
        $user->otp_expires_at = null;
        $user->save();

        // Login User
        Auth::login($user, session('auth.remember', false));
        $request->session()->forget(['auth.otp_user_id', 'auth.remember']);
        $request->session()->regenerate();

        return redirect()->intended('dashboard');
    }

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

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

        return redirect('/');
    }
}
