<?php

namespace App\Http\Controllers;

use App\Models\Currency;
use App\Models\User;
use App\Services\ReferralService;
use App\Services\WalletService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules\Password;

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

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

        if (! Auth::attempt($credentials, $request->boolean('remember'))) {
            return back()->withErrors(['email' => 'بيانات الدخول غير صحيحة.'])->onlyInput('email');
        }

        $request->session()->regenerate();
        $request->user()->forceFill([
            'last_login_at' => now(),
            'last_login_ip' => $request->ip(),
        ])->save();

        return redirect()->intended($request->user()->isAdmin() ? route('admin.dashboard') : route('account.dashboard'));
    }

    public function showRegister()
    {
        return view('auth.register');
    }

    public function register(Request $request, WalletService $walletService, ReferralService $referrals)
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:120'],
            'email' => ['required', 'email', 'max:190', 'unique:users,email'],
            'phone' => ['nullable', 'string', 'max:30'],
            'referral_code' => ['nullable', 'string', 'max:16'],
            'password' => ['required', 'confirmed', Password::min(10)->mixedCase()->numbers()],
        ]);

        $referrer = $referrals->findReferrer($data['referral_code'] ?? null);

        if (($data['referral_code'] ?? null) && ! $referrer) {
            return back()->withErrors(['referral_code' => 'كود الإحالة غير صحيح.'])->withInput();
        }

        $user = User::create([
            'uuid' => (string) Str::uuid(),
            'public_id' => $this->generatePublicId(),
            'referral_code' => $referrals->generateCode(),
            'referred_by_user_id' => $referrer?->id,
            'referred_at' => $referrer ? now() : null,
            'name' => $data['name'],
            'display_name' => $data['name'],
            'email' => $data['email'],
            'phone' => $data['phone'] ?? null,
            'locale' => 'ar',
            'timezone' => 'Africa/Cairo',
            'status' => 'active',
            'role' => 'customer',
            'currency_id' => Currency::where('code', 'EGP')->value('id'),
            'password' => Hash::make($data['password']),
        ]);

        $walletService->ensureWallet($user);
        Auth::login($user);

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

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

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

    private function generatePublicId(): string
    {
        do {
            $id = (string) random_int(10000, 99999);
        } while (User::where('public_id', $id)->exists());

        return $id;
    }
}
