<?php

namespace App\Http\Controllers\Page;

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\Facades\Validator;
use Illuminate\Validation\Rules\Password;

class AuthController extends Controller
{
    public function showRegisterForm()
    {
        return view('customer.auth.register');
    }

    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'first_name' => ['required', 'string', 'max:255'],
            'last_name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'phone' => ['required', 'string', 'max:15'],
            'password' => ['required', 'confirmed', Password::min(8)],
            'terms' => ['accepted'],
            'national_id' => ['nullable', 'string', 'max:11'],
            'birth_date' => ['nullable', 'date', 'before:today'],
            'gender' => ['nullable', 'in:male,female,other'],
            'city' => ['nullable', 'string', 'max:255'],
            'address' => ['nullable', 'string'],
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $user = User::create([
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'email' => $request->email,
            'phone' => $request->phone,
            'password' => Hash::make($request->password),
            'national_id' => $request->national_id,
            'birth_date' => $request->birth_date,
            'gender' => $request->gender,
            'city' => $request->city,
            'address' => $request->address,
            'is_active' => true,
            'is_verified' => false,
            'language' => $request->language ?? 'tr',
            'country' => 'TR',
        ]);

        Auth::login($user);

        return redirect()->route('customer.dashboard')
            ->with('success', 'Kayıt işleminiz başarıyla tamamlandı!');
    }

    public function showLoginForm()
    {
        return view('customer.auth.login');
    }

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

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

        if (Auth::attempt($credentials, $remember)) {
            $request->session()->regenerate();

            $user = Auth::user();

            $user->update([
                'last_login_at' => now(),
                'last_login_ip' => $request->ip(),
            ]);

            if ($user) {
                return redirect()->intended(route('customer.dashboard'));
            }

            Auth::logout();
            return back()->withErrors([
                'email' => 'Bu hesap müşteri hesabı değil.',
            ])->onlyInput('email');
        }

        return back()->withErrors([
            'email' => 'Girilen bilgiler hatalı.',
        ])->onlyInput('email');
    }

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

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

        return redirect()->route('customer.login')
            ->with('success', 'Başarıyla çıkış yapıldı.');
    }

    public function showForgotPasswordForm()
    {
        return view('customer.auth.forgot-password');
    }

    public function sendResetLink(Request $request)
    {
        $request->validate([
            'email' => ['required', 'email', 'exists:users,email'],
        ]);

        // Password reset logic burada implement edilecek

        return back()->with('success', 'Şifre sıfırlama bağlantısı e-posta adresinize gönderildi.');
    }

    public function showResetPasswordForm(Request $request, $token)
    {
        return view('customer.auth.reset-password', ['token' => $token, 'email' => $request->email]);
    }

    public function resetPassword(Request $request)
    {
        $request->validate([
            'token' => ['required'],
            'email' => ['required', 'email'],
            'password' => ['required', 'confirmed', Password::min(8)],
        ]);

        // Password reset logic burada implement edilecek

        return redirect()->route('customer.login')
            ->with('success', 'Şifreniz başarıyla sıfırlandı. Giriş yapabilirsiniz.');
    }
}
