<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use App\Models\User;
use App\Mail\WelcomeMail;
use App\Mail\PasswordResetMail;

class AuthController extends Controller
{
    public function login()
    {
        if (Auth::check()) {
            $user = Auth::user();
            if ($user->is_admin || $user->hasRole('admin')) {
                return redirect()->route('admin.dashboard');
            }
            return redirect()->route('user.dashboard');
        }
        
        return view('auth.login');
    }

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

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

        if (Auth::attempt($credentials, $remember)) {
            $request->session()->regenerate();
            
            $user = Auth::user();
            
            // Redirect based on user role (support both is_admin flag and Spatie role)
            $isAdmin = $user->is_admin || $user->hasRole('admin');

            if ($isAdmin) {
                return redirect()->intended(route('admin.dashboard'))
                    ->with('success', __('Welcome back, Admin!'));
            }
            
            return redirect()->intended(route('user.dashboard'))
                ->with('success', __('Welcome back!'));
        }

        return back()->withErrors([
            'email' => __('The provided credentials do not match our records.'),
        ])->withInput($request->except('password'));
    }

    public function register()
    {
        if (Auth::check()) {
            return redirect()->route('user.dashboard');
        }
        
        return view('auth.register');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'phone' => 'nullable|string|max:20',
            'country' => 'nullable|string|max:100',
            'password' => 'required|string|min:8|confirmed',
            'terms' => 'required|accepted',
        ]);

        try {
            $user = User::create([
                'name' => $validated['name'],
                'email' => $validated['email'],
                'phone' => $validated['phone'] ?? null,
                'country' => $validated['country'] ?? null,
                'password' => Hash::make($validated['password']),
                'is_admin' => false,
            ]);

            // Send welcome email
            try {
                Mail::to($user->email)->send(new WelcomeMail($user));
            } catch (\Exception $e) {
                \Log::error('Welcome email failed: ' . $e->getMessage());
            }

            // Auto login after registration
            Auth::login($user);

            return redirect()->route('user.dashboard')
                ->with('success', __('Registration successful! Welcome to our tourism platform.'));

        } catch (\Exception $e) {
            \Log::error('Registration error: ' . $e->getMessage());
            return back()->with('error', __('Registration failed. Please try again.'))
                ->withInput($request->except('password', 'password_confirmation'));
        }
    }

    public function logout(Request $request)
    {
        Auth::logout();
        
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        
        return redirect()->route('home')
            ->with('success', __('You have been logged out successfully.'));
    }

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

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

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

        // Store token in database (you might want to create a password_resets table)
        \DB::table('password_resets')->insert([
            'email' => $user->email,
            'token' => Hash::make($token),
            'created_at' => now(),
        ]);

        try {
            Mail::to($user->email)->send(new PasswordResetMail($user, $token));
            
            return back()->with('success', __('Password reset link has been sent to your email.'));

        } catch (\Exception $e) {
            \Log::error('Password reset email failed: ' . $e->getMessage());
            return back()->with('error', __('Failed to send password reset link. Please try again.'));
        }
    }

    public function resetPassword($token)
    {
        return view('auth.reset-password', ['token' => $token]);
    }

    public function updatePassword(Request $request)
    {
        $request->validate([
            'email' => 'required|email|exists:users,email',
            'token' => 'required',
            'password' => 'required|string|min:8|confirmed',
        ]);

        // Verify token
        $reset = \DB::table('password_resets')
            ->where('email', $request->email)
            ->first();

        if (!$reset || !Hash::check($request->token, $reset->token)) {
            return back()->with('error', __('Invalid or expired password reset token.'));
        }

        // Check if token is not expired (24 hours)
        if (now()->diffInHours($reset->created_at) > 24) {
            \DB::table('password_resets')->where('email', $request->email)->delete();
            return back()->with('error', __('Password reset token has expired.'));
        }

        try {
            $user = User::where('email', $request->email)->first();
            $user->update([
                'password' => Hash::make($request->password),
            ]);

            // Delete the reset token
            \DB::table('password_resets')->where('email', $request->email)->delete();

            return redirect()->route('login')
                ->with('success', __('Password has been reset successfully. Please login with your new password.'));

        } catch (\Exception $e) {
            \Log::error('Password reset error: ' . $e->getMessage());
            return back()->with('error', __('Failed to reset password. Please try again.'));
        }
    }

    public function verifyEmail($token)
    {
        $user = User::where('email_verification_token', $token)->first();

        if (!$user) {
            return redirect()->route('login')
                ->with('error', __('Invalid verification token.'));
        }

        $user->update([
            'email_verified_at' => now(),
            'email_verification_token' => null,
        ]);

        return redirect()->route('login')
            ->with('success', __('Email verified successfully. You can now login.'));
    }

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

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

        if ($user->email_verified_at) {
            return back()->with('info', __('Email is already verified.'));
        }

        try {
            $token = Str::random(60);
            $user->update(['email_verification_token' => $token]);
            
            Mail::to($user->email)->send(new \App\Mail\EmailVerificationMail($user, $token));
            
            return back()->with('success', __('Verification email has been sent again.'));

        } catch (\Exception $e) {
            \Log::error('Verification email failed: ' . $e->getMessage());
            return back()->with('error', __('Failed to send verification email. Please try again.'));
        }
    }
}
