<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
class AuthController extends Controller {
    public function showLogin() {
        if (Auth::check()) return redirect()->route('command');
        return view('auth.login');
    }
    public function login(Request $r) {
        $data = $r->validate(['login' => 'required', 'password' => 'required']);
        $field = filter_var($data['login'], FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
        $user = \App\Models\User::where($field, $data['login'])->where('is_active', true)->first();
        if ($user && Hash::check($data['password'], $user->password)) {
            Auth::login($user, $r->boolean('remember'));
            $user->update(['last_login_at' => now()]);
            \App\Models\LoginHistory::create(['user_id' => $user->id, 'login' => $data['login'],
                'ip' => $r->ip(), 'user_agent' => substr((string) $r->userAgent(), 0, 255), 'success' => true]);
            $r->session()->regenerate();
            return redirect()->intended(route('command'))->with('success', 'Welcome back, '.$user->name.'!');
        }
        \App\Models\LoginHistory::create(['user_id' => $user?->id, 'login' => $data['login'],
            'ip' => $r->ip(), 'user_agent' => substr((string) $r->userAgent(), 0, 255), 'success' => false]);
        return back()->withErrors(['login' => 'Invalid credentials or inactive account.'])->onlyInput('login');
    }
    public function logout(Request $r) {
        Auth::logout();
        $r->session()->invalidate();
        $r->session()->regenerateToken();
        return redirect()->route('login')->with('success', 'Signed out.');
    }
    public function profile() { return view('auth.profile', ['user' => Auth::user()]); }
    public function updateProfile(Request $r) {
        $u = Auth::user();
        $data = $r->validate(['name' => 'required|max:100', 'phone' => 'nullable|max:30', 'password' => ['nullable', 'confirmed', Password::min(8)->letters()->mixedCase()->numbers()->symbols()]]);
        $u->name = $data['name']; $u->phone = $data['phone'] ?? $u->phone;
        if (!empty($data['password'])) $u->password = $data['password'];
        $u->save();
        return back()->with('success', 'Profile updated.');
    }
}
