<?php

namespace App\Http\Controllers;

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


class AuthController extends Controller
{    
   
    public function loginPage() {
        return view('auth.login');
    }

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

public function register(Request $r)
{
    $r->validate([
        'name' => 'required',
        'email' => 'required|email|unique:users',
        'password' => 'required|min:6',
        'role' => 'required|in:admin,operation,supervisor,sales'
    ]);

    User::create([
        'name' => $r->name,
        'email' => $r->email,
        'password' => Hash::make($r->password),
        'role' => $r->role
    ]);

    return redirect('/login')->with('success','Account created successfully');
}

public function login(Request $r)
{
    if (Auth::attempt($r->only('email','password'))) {
        return redirect()->route('dashboard');
    }

    return back()->with('error','Invalid login');
}



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




// 🔹 LIST USERS (ADMIN ONLY)
public function users()
{
    $users = User::orderBy('id','desc')->paginate(15);
    return view('admin.users', compact('users'));
}

public function resetPassword(Request $r, $id)
{
   

    $r->validate([
        'password' => 'required|min:6'
    ]);

    $user = User::findOrFail($id);
    $user->password = Hash::make($r->password);
    $user->save();

    return back()->with('success', 'Password reset successfully');
}
public function changeRole(Request $r, $id)
{
   
    $r->validate([
        'role' => 'required|in:admin,operation,supervisor,sales'
    ]);

    User::where('id',$id)->update([
        'role' => $r->role
    ]);

    return back()->with('success', 'Role updated');
}
public function deleteUser($id)
{
  

    User::where('id',$id)->delete();
    return back()->with('success', 'User deleted');
}
public function adminCreateUser(Request $r)
{

    $r->validate([
        'name' => 'required',
        'email' => 'required|email|unique:users',
        'password' => 'required|min:6',
        'role' => 'required|in:admin,operation,supervisor,sales'
    ]);

    User::create([
        'name' => $r->name,
        'email' => $r->email,
        'password' => Hash::make($r->password),
        'role' => $r->role
    ]);

    return back()->with('success', 'User created successfully');
}



}
