<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules\Password;
use Laravel\Socialite\Facades\Socialite;
use App\Http\Controllers\Frontend\EmailVerificationController;

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

    public function login(Request $request)
    {
        $request->validate([
            'email'    => 'required|email',
            'password' => 'required',
        ], [
            'email.required'    => 'E-posta zorunludur.',
            'email.email'       => 'Geçerli bir e-posta girin.',
            'password.required' => 'Şifre zorunludur.',
        ]);

        $credentials = $request->only('email', 'password');
        $remember    = $request->boolean('remember');

        if (Auth::attempt($credentials, $remember)) {
            $user = Auth::user();
            if ($user->is_banned) {
                Auth::logout();
                return back()->withErrors(['email' => 'Hesabınız yasaklanmıştır: ' . ($user->ban_reason ?: 'İhlal.')]);
            }
            $request->session()->regenerate();
            \App\Support\ActivityLogger::log('login', $user->id, null, null, null, $request);
            return redirect()->intended(route('home'));
        }

        return back()->withErrors(['email' => 'E-posta veya şifre hatalı.'])->withInput($request->only('email'));
    }

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

    public function register(Request $request)
    {
        $request->validate([
            'name'     => 'required|string|min:2|max:60',
            'email'    => 'required|email|unique:users,email',
            'password' => ['required', 'confirmed', Password::min(6)],
        ], [
            'name.required'      => 'İsim zorunludur.',
            'name.min'           => 'İsim en az 2 karakter olmalıdır.',
            'email.required'     => 'E-posta zorunludur.',
            'email.unique'       => 'Bu e-posta zaten kayıtlı.',
            'password.required'  => 'Şifre zorunludur.',
            'password.confirmed' => 'Şifreler eşleşmiyor.',
            'password.min'       => 'Şifre en az 6 karakter olmalıdır.',
        ]);

        $user = User::create([
            'name'       => $request->name,
            'email'      => $request->email,
            'password'   => Hash::make($request->password),
            'role'       => 'user',
            'membership' => 'free',
        ]);

        Auth::login($user);
        $request->session()->regenerate();
        \App\Support\ActivityLogger::log('register', $user->id, null, null, null, $request);

        // Doğrulama e-postası gönder (SMTP ayarlıysa)
        try {
            EmailVerificationController::sendVerificationMail($user);
        } catch (\Throwable) {}

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

    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect(route('home'));
    }

    // ── Social Auth ───────────────────────────────────────────────────────────

    private const ALLOWED_PROVIDERS = ['google', 'discord'];

    public function socialRedirect(string $provider)
    {
        if (!in_array($provider, self::ALLOWED_PROVIDERS)) {
            abort(404);
        }

        return Socialite::driver($provider)->redirect();
    }

    public function socialCallback(string $provider, Request $request)
    {
        if (!in_array($provider, self::ALLOWED_PROVIDERS)) {
            abort(404);
        }

        try {
            $socialUser = Socialite::driver($provider)->user();
        } catch (\Throwable $e) {
            return redirect()->route('frontend.login')
                ->withErrors(['email' => 'Sosyal giriş başarısız, lütfen tekrar deneyin.']);
        }

        $email    = $socialUser->getEmail();
        $name     = $socialUser->getName() ?: $socialUser->getNickname() ?: 'Kullanıcı';
        $avatar   = $socialUser->getAvatar();
        $socialId = $socialUser->getId();

        // Aynı provider + social_id ile kayıtlı kullanıcı var mı?
        $user = User::where('social_provider', $provider)
            ->where('social_id', $socialId)
            ->first();

        if (!$user && $email) {
            // Aynı e-posta ile kayıtlı normal hesap var mı?
            $user = User::where('email', $email)->first();
            if ($user) {
                // Mevcut hesaba sosyal giriş bilgisini bağla
                $user->update([
                    'social_provider' => $provider,
                    'social_id'       => $socialId,
                    'avatar'          => $user->avatar ?: $avatar,
                ]);
            }
        }

        if (!$user) {
            // Yeni kullanıcı oluştur
            $user = User::create([
                'name'            => $name,
                'email'           => $email,
                'avatar'          => $avatar,
                'social_provider' => $provider,
                'social_id'       => $socialId,
                'password'        => null,
                'role'            => 'user',
                'membership'      => 'free',
            ]);
            \App\Support\ActivityLogger::log('register', $user->id, null, null, null, $request);
        }

        if ($user->is_banned) {
            return redirect()->route('frontend.login')
                ->withErrors(['email' => 'Hesabınız yasaklanmıştır: ' . ($user->ban_reason ?: 'İhlal.')]);
        }

        Auth::login($user, true);
        $request->session()->regenerate();
        \App\Support\ActivityLogger::log('login', $user->id, null, null, null, $request);

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