<?php

namespace App\Http\Controllers;

use App\Models\ActivityLog;
use App\Services\AuthService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{
    protected $authService;

    public function __construct(AuthService $authService)
    {
        $this->authService = $authService;
    }

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

    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        try {
            if ($this->authService->login($credentials)) {
                ActivityLog::create([
                    'user_id' => auth()->id(),
                    'action' => 'login',
                    'description' => 'User logged in successfully.',
                    'ip_address' => $request->ip(),
                    'user_agent' => $request->userAgent(),
                ]);

                if(auth()->user()->role == 'admin'){
                    return redirect()->route('admin.root');
                }else{
                    return redirect()->route('staff.root');
                }
            }
            return back()->withErrors(['email' => 'Invalid credentials']);
        } catch (\Exception $e) {
            return back()->withErrors(['email' => $e->getMessage()]);
        }
    }

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

    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ]);

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

        $this->authService->register($request->all());

        return redirect()->route('login')->with('success', 'Registration successful. Please login.');
    }

    public function logout(Request $request)
    {
        if (auth()->check()) {
            ActivityLog::create([
                'user_id' => auth()->id(),
                'action' => 'logout',
                'description' => 'User logged out.',
                'ip_address' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ]);
        }
        
        $this->authService->logout();
        return redirect()->route('login');
    }

    public function logoutInactive(Request $request)
    {
        $user = auth()->user();
        if ($user) {
            $user->status = 0;
            $user->save();
            
            ActivityLog::create([
                'user_id' => $user->id,
                'action' => 'logout',
                'description' => 'User account deactivated and logged out due to inactivity/security.',
                'ip_address' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ]);
        }
        $this->authService->logout();
        return redirect()->route('login')->withErrors(['email' => 'Your account has been blocked due to security violations.']);
    }

    public function profile()
    {
        return view('auth.profile', ['user' => auth()->user()]);
    }

    public function updateProfile(Request $request)
    {
        $user = auth()->user();
        
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users,email,'.$user->id,
            'mobile_no' => 'nullable|string|max:20',
            'address' => 'nullable|string',
        ]);

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

        $this->authService->updateProfile($user->id, $request->only('name', 'email', 'mobile_no', 'address'));

        ActivityLog::create([
            'user_id' => $user->id,
            'action' => 'profile_update',
            'description' => 'User updated their profile information.',
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
        ]);

        return back()->with('success_profile', 'Profile details updated successfully');
    }

    public function updatePassword(Request $request)
    {
        $user = auth()->user();

        $validator = Validator::make($request->all(), [
            'old_password' => 'required',
            'new_password' => 'required|string|min:8|confirmed',
        ]);

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

        try {
            $this->authService->updatePassword($user->id, $request->old_password, $request->new_password);
            return back()->with('success_password', 'Password updated successfully');
        } catch (\Exception $e) {
            return back()->withErrors(['old_password' => $e->getMessage()], 'password')->withInput();
        }
    }
}
