<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
// use Spatie\Permission\Models\Role;
// use Spatie\Permission\Models\Permission;
use App\Models\Role;
use App\Models\Permission;
use App\Models\Admin;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;
use DB;

class RoleController extends Controller
{
    public function index(Request $request)
    {
        $superAdminID = env('DEFAULT_SA_ID');
        $query = Role::where('id','!=',$superAdminID)->orderBy('created_at', 'desc');
        
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where('name', 'like', '%' . $search . '%');
        }
        $roles = $query->paginate(10);

        if ($request->ajax()) {
            return view('admin.roles.ajax', compact('roles'))->render();
        }
        return view('admin.roles.list', compact('roles'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('admin.roles.create', ['roles' => Role::all()]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //     // $request->validate(['name' => 'required|unique:roles,name|regex:/^[A-Za-z\s]+$/']);
        //     $request->validate([
        //         'name' => 'required|unique:roles,name|regex:/^[A-Za-z\s]+$/',
        //     ], [
        //         'name.regex' => 'This field accept letters only.',
        //     ]);
        //     Role::create(['name' => $request->name, 'guard_name' => 'admin' , 'description' => $request->description,
        // ]);
        //     return redirect()->back()->with('success', 'Role created successfully.');

          $rules = [
            'name' => 'required|unique:roles,name|regex:/^[A-Za-z\s]+$/',
            
            
        ];

        $messages = [
            'name.required'  => 'Name is required.',
            'name.regex'     => 'name accept character only.',
            'name.unique'    =>'This name already exists.',
           
        ];

         $validation = Validator::make($request->all(), $rules,$messages);
        if ($validation->fails()) {

            return response()->json([
                'success' => false,
                'errors' => $validation->errors()
            ]);
        }

        try{

            $insert_arr = array(
                'name'          =>$request->name,
                'description'   =>$request->description,
                'guard_name'    =>'admin',
                'permission_ids'=>array()
            );

            $insert = Role::insert($insert_arr);
           
            return response()->json([
                'success' => true,
                'message' => 'Subject Inserted successfully.'
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'errors' => ['server' => [$e->getMessage()]]
            ]);
        }


    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Role $role)
    {
        return view('admin.roles.edit', [
            'role' => $role,
            'permissions' => Permission::all()
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        // $id = $request->id;
         $rules = [
             'name' => 'required|unique:roles,name'.$id.'|regex:/^[A-Za-z\s]+$/',
            
        ];

        $messages = [
            'name.required'  => 'Name is required.',
            'name.regex'     => 'name accept character only.',
            'name.unique'    =>'This name already exists.',
           
        ];

         $validation = Validator::make($request->all(), $rules,$messages);
        if ($validation->fails()) {

            return response()->json([
                'success' => false,
                'errors' => $validation->errors()
            ]);
        }


        //  DB::beginTransaction();

        try {
            $role = Role::find($id);
            if($role == null){

                return response()->json([
                    'success' => false,
                    'errors' => $validation->errors()
                ]);

            }

            $role->name         = $request->name;
            $role->description = $request->description;

            
            $role->save();

            // DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'updated successfully.'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'errors' => ['server' => [$e->getMessage()]]
            ]);
        }
        // $request->validate(['name' => 'required|unique:roles,name,' . $role->id]);
        // $role->update(['name' => $request->name]);
        // // return response()->json(['message' => 'Role updated successfully']);
        // return response()->json([
        // 'success' => true,
        // 'message' => 'Role updated successfully',
        // ]);

        // return redirect()->route('admin.roles.index')->with('success', 'Role updated successfully.');
    }

    public function updatePermissions(Request $request, Role $role)
    {

        $rules = [
            'permissions'   => 'required|array|min:1',
            'permissions.*' => 'exists:permissions,id',
        ];

        $messages = [
            'permissions.required'  => 'Atleast one permission required',
            'permissions.array'  => 'Invalid Format.',
            'permissions.min'  => 'Atleast one permission required',
        ];

        $validation = Validator::make($request->all(), $rules,$messages);
        if ($validation->fails()) {

            return response()->json([
                'success' => false,
                'errors' => $validation->errors()
            ],422);
        }

        $update = Role::where('id',$request->role->id)->update(['permission_ids'=>$request->permissions]);
        // $permissions = Permission::find($request->permissions);
        // $role->syncPermissions($permissions);
        return response()->json(['message' => 'Permissions updated successfully']);
      
        // return redirect()->route('admin.roles.index')->with('success', 'Permissions updated successfully.');
    }

    public function destroy1(Role $role)
    {
        $role->delete();
        return redirect()->route('admin.roles.index')->with('success', 'Role deleted successfully.');
    }


    //  public function destroy(Request $request)
    // {
    //     try {
    //         $id = base64_decode($request->id);
    //         $student = Role::findOrFail($id);
    //         $student->delete();
    
    //         return response()->json(['success' => true, 'message' => 'Role deleted successfully']);
    //     } catch (\Exception $e) {
    //         return response()->json(['success' => false, 'message' => $e->getMessage()]);
    //     }
    // }

    public function destroy($id)
    {
    try {
        $id = base64_decode($id);
        $role = Role::findOrFail($id);

        $assigned = Admin::select('role_id', $role->id)->first();
      
        if ($assigned) {
            return response()->json([
                'success' => false,
                'message' => 'This role is assigned to users and cannot be deleted.'
            ]);
        }

        $role->delete();

        return response()->json(['success' => true, 'message' => 'Role deleted successfully']);
    } catch (\Exception $e) {
        return response()->json(['success' => false, 'message' => $e->getMessage()]);
    }
    }
}
