<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Users;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

// php artisan make:controller RoleController --model=Role --resource
// php artisan make:controller BarcodeDetailsController --model=BarcodeDetails --resource
// php artisan cache:clear
// php artisan optimize:clear
// php artisan config:clear
// php artisan route:clear
// php artisan view:clear
// php artisan event:clear

class UsersController extends Controller
{

    // Show login page
    public function showLogin()
    {
        return view('login');
    }

    // Login check
    public function login(Request $request)
    {
        // validate requested data
        $request->validate([
            'username' => 'required',
            'password' => 'required',
        ]);

        // assign inputs
        $credentials = [
            'username' => $request->username,
            'password' => $request->password,
            // 'status'   => 'Active',
        ];

        if (Auth::attempt($credentials)) {
            $auth_status = auth()->user()->status;
            $auth_role = auth()->user()->role;
            $auth_role_name = $auth_role?->name;

            if ($auth_status === 'Active') {
                $request->session()->regenerate();
                if ($auth_role_name == "Admin") {
                    return redirect()->intended('/dashboard');
                } else {
                    return redirect()->intended('/barcode/list');
                }
            }

            Auth::logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();

            return back()->withErrors(['username' => 'Permission denied.'])->withInput();
        }
        return back()->withErrors(['username' => 'Invalid credentials.'])->withInput();
    }

    // Dashboard
    public function dashboard()
    {
        return view('dashboard');
    }

    // Logout
    public function logout()
    {
        Auth::logout();
        return redirect('/login');
    }
}
