<?php

namespace App\Http\Controllers;

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

class AdminController extends Controller
{
    public function dashboard()
    {
        return view('admin.dashboard');
    }

    public function users(Request $request)
    {
    $query = User::query();

    if ($request->filled('search')) {
        $s = $request->search;
        $query->where(function ($q) use ($s) {
            $q->where('name', 'like', "%$s%")
              ->orWhere('no_pekerja', 'like', "%$s%")
              ->orWhere('jabatan', 'like', "%$s%");
        });
    }

    $users = $query->get();
    return view('admin.users.index', compact('users'));
    }

    public function storeUser(Request $request)
    {
        $request->validate([
            'name'=>'required|string|max:255',
            'password'=>'required|string|min:6',
            'role'=>'required|in:admin,staff',
            'no_pekerja'=>'required|string|unique:users,no_pekerja',
            'jabatan'=>'required|string|max:255',
        ]);

        User::create([
            'name'=>$request->name,
            'password'=>Hash::make($request->password),
            'role'=>$request->role,
            'no_pekerja'=>$request->no_pekerja,
            'jabatan' => $request->jabatan,
        ]);

        return redirect()->back()->with('success','Pengguna telah ditambah');
    }

    public function updateUser(Request $request, $id)
    {
        $user = User::findOrFail($id);

        $request->validate([
            'name'=>'required|string|max:255',
            'role'=>'required|in:admin,staff',
            'no_pekerja'=>'required|unique:users,no_pekerja,'.$user->id,
            'jabatan'=>'required|string|max:255',
        ]);

        $user->update([
            'name'=>$request->name,
            'role'=>$request->role,
            'no_pekerja'=>$request->no_pekerja,
            'jabatan' => $request->jabatan,
        ]);

        if($request->password){
            $request->validate(['password' => 'string|min:3']);
            $user->update(['password'=>Hash::make($request->password)]);
        }

        return redirect()->back()->with('success','Pengguna telah dikemaskini');
    }

    public function deleteUser($id)
    {
        $user = User::findOrFail($id);
        $user->delete();

        return redirect()->back()->with('success','Pengguna telah dihapuskan');
    }


}
