<?php

namespace App\Http\Controllers;

use App\Models\Menu;
use App\Models\Role;
use App\Models\RoleMenu;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

class RolesController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return view("roles.index");
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view("roles.create");
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try{
            $request->validate([
                "name" => "required|unique:roles,name",
                "description" => "nullable",
            ]);

            DB::beginTransaction();
            Role::create($request->all());
            DB::commit();
            return response()->json(['message' => 'Role created successfully'], 201);
        }
        catch(\Exception $e){
            DB::rollBack();
            return response()->json(['message' => $e->getMessage()], 500);
        }
    }

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

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        $role = Role::findOrFail($id);
        return view("roles.edit", compact('role'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        try{
            $role = Role::findOrFail($id);
            // Validate request data
            $validatedData = $request->validate([
                'name' => 'required|string|max:255|unique:roles,name,' . $id, // Ensure name is unique except for the current role
                'description' => 'nullable|string|max:500',
            ]);

            DB::beginTransaction();
            $role->update($validatedData);
            DB::commit();
            return response()->json(['message' => 'Role updated successfully'], 200);
        }catch(\Exception $e){
            DB::rollBack();
            return response()->json(['message' => $e->getMessage()], 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        try{
            DB::beginTransaction();
            $deleted = Role::findOrFail($id)->delete();
            DB::commit();
            return response()->json(['success' => true, "message" => "Successfully deleted"]);
        }catch(\Exception $e){
            DB::rollBack();
            return response()->json(['success' => false, "message" => $e->getMessage()]);
        }
    }

    public function menu_permission(string $role_id){
        try{
            $role = Role::findOrFail($role_id);
            $menus = Menu::all();
            $role_menus = RoleMenu::where('role_id', $role_id)->get() ?? collect();
            return view('roles.role_menu', compact('role', 'menus', 'role_menus'));
        }catch(\Exception $e){
            return redirect()->back()->with("error", $e->getMessage());
        }
    }

    public function update_menu_permission(Request $request, string $role_id){
        try{
            $validateData = $request->validate([
                "permissions" => "array",
                "permissions.*.allow_show" => "nullable|boolean",
                "permissions.*.allow_create" => "nullable|boolean",
                "permissions.*.allow_update" => "nullable|boolean",
                "permissions.*.allow_destroy" => "nullable|boolean"
            ]);

            $role = Role::find($role_id);

            $permissionsArray = [];
            foreach ($validateData['permissions'] as $menu_id => $permission) {
                $permissionsArray[$menu_id] = [
                    "allow_show" => (int) ($permission["allow_show"] ?? 0),
                    "allow_create" => (int) ($permission["allow_create"] ?? 0),
                    "allow_update" => (int) ($permission["allow_update"] ?? 0),
                    "allow_destroy" => (int) ($permission["allow_destroy"] ?? 0),
                    "updated_at" => now(),
                ];
            }

            // Sync will update existing records and insert new ones
            $role->menus()->sync($permissionsArray);

            return redirect()->route("role-menu.permission", $role_id)->with('success','Menu Permission updated successfully');
        }catch(\Exception $e){
            Log::error("Error updating role_menu:", ["error" => $e->getMessage()]);
            return redirect()->route("role-menu.permission", $role_id)->with("error", $e->getMessage());
        }
    }
}
