<?php

namespace App\Http\Controllers\Admin;

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

class PengurusanAdminController extends Controller
{
    //
    //
    public function showList(Request $request){
        $admins = User::whereNotIn('role', ['awam'])->get();      

      /*  $awams = User::where('role', 'awam')->where(function ($query) use ($request) {
            $query->where('nokp', 'like', '%'.$request->keyword.'%')
                  ->orWhere('name', 'like', '%'.$request->keyword.'%');
        })->get();*/
        $keyword = '';

        $awams = null;

        return view('admin.lantikan_admin', compact('awams', 'admins', 'keyword'));
    }

    public function showListCarian(Request $request){

        $admins = User::whereNotIn('role', ['awam'])->get();      

        $awams = User::where('role', 'awam')->where(function ($query) use ($request) {
            $query->where('nokp', 'like', '%'.$request->keyword.'%')
                  ->orWhere('name', 'like', '%'.$request->keyword.'%');
        })->get();
        $keyword = $request->keyword;

        return view('admin.lantikan_admin', compact('awams', 'admins', 'keyword'));
    }

    public function updateRole(Request $request, $id){

        if (! Gate::allows('keje-admin')) {
            abort(403);
        }

        $new_admin = User::findOrFail($id);
        if(!is_null($new_admin)){
            $new_admin->role = $request->role;
            $new_admin->save();

            $msg = "Berjaya dikemaskini sebagai Admin.";
        }
        else{
            $msg = "Terdapat masalah dengan No KP";
        }
        

        return redirect(route('admin.lantikan-admin'))->with('success', $msg);
    }

    public function removeAdmin(Request $request, $nokp, $keyword=''){

        if (! Gate::allows('keje-admin')) {
            abort(403);
        }

        $new_admin = User::where('nokp', $nokp)->first();
        if(!is_null($new_admin)){
            $new_admin->role = 'awam';
            $new_admin->save();

            $msg = "Berjaya dikeluarkan dariapda Admin.";
        }
        else{
            $msg = "Terdapat masalah dengan No KP";
        }

        return redirect(route('admin.lantikan-admin'))->with('success', $msg);
    }
}
