<?php

namespace App\Http\Controllers\auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\User;

class AuthController extends Controller
{
    public function index()
    {
        return view('auth.login'); 
    }
     public function login(Request $request) {
        $request->validate([
            'login'    => 'required|string',
            'password' => 'required|string',
        ]);

        $login = $request->input('login');
        $password = $request->input('password');
        $user = User::where('username', $login)
                    ->orWhere('email', $login)
                    ->orWhere('phone', $login)
                    ->first();

        if (!$user) {
            return back()->withErrors(['login' => 'Invalid credentials.'])->withInput();
        }

        // Check if password matches
        if (!Hash::check($password, $user->password)) {
            return back()->withErrors(['password' => 'Invalid credentials.'])->withInput();
        }

        // Check if user is active
        if (!$user->is_active) {
            return back()->withErrors(['login' => 'Account is inactive.'])->withInput();
        }

        // Login the user
        Auth::login($user);

        // Redirect based on role
        if ($user->role == 'customer') {
            return redirect()->route('customer.dashboard');
        } elseif ($user->role == 'staff') {
            return redirect()->route('staff.dashboard');
        } elseif ($user->role == 'admin') {
            return redirect()->route('admin.dashboard');
        }

        // Default redirect
        return redirect('/');
    }

    // Handle logout
    public function logout(Request $request) {
        Auth::logout();
        return redirect()->route('login')->with('status', 'Logged out successfully.');
    }
}
