<?php

namespace App\Http\Controllers\Backend;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Helpers\AuditTrailHelper;

class MenuRoleController extends Controller
{
    public function index($roleId)
    {
        // Ambil semua data dari tabel menus
        $menus = DB::table('menus')
            ->orderBy('parent_id', 'ASC')
            ->orderBy('order', 'ASC')
            ->get();

        $savedMenuIds = DB::table('role_menu')
            ->where('role_id', $roleId)
            ->pluck('menu_id')
            ->toArray();


        // Jika $savedMenuIds null, set ke array kosong
        if (is_null($savedMenuIds)) {
            $savedMenuIds = [];
        }

        // Membentuk struktur tree
        $menuTree = $this->buildTree($menus, $savedMenuIds);

        $pageInfo = [
            'title' => 'Assign Role Menu',
            'sub_title' => 'Assign Role in Menu',
            'path' => url()->current()
        ];

        return view('backend.pages.menurole.index', [
            'menuTree' => $menuTree,
            'pageInfo' => $pageInfo,
            'role_id' => $roleId
        ]);
    }

    private function buildTree($menus, $savedMenuIds, $parentId = 0)
    {
        $tree = [];
        foreach ($menus as $menu) {
            if ($menu->parent_id == $parentId) {
                $children = $this->buildTree($menus, $savedMenuIds, $menu->id);
              
                $node = [
                    'id' => $menu->id,
                    'text' => $menu->title,
                    'attributes' => ['url' => $menu->url],
                    'checked' => in_array($menu->id, $savedMenuIds) 
                ];

                if ($children) {
                    $node['children'] = $children;
                }

                $tree[] = $node;
            }
        }
        return $tree;
    }

    public function saveMenu(Request $request)
    {
        $request->validate([
            'menu_ids' => 'required',
            'role_id' => 'required|integer'
        ]);
        $selectedMenuIds = json_decode($request->input('menu_ids', '[]'));
        $roleId = $request->input('role_id');

        DB::beginTransaction(); 
        try {
            DB::table('role_menu')->where('role_id', $roleId)->delete();
            $dataToInsert = [];
            foreach ($selectedMenuIds as $menuId) {
                $results = DB::select('SELECT parent_id FROM menus WHERE id = ?', [$menuId]);
                if($results[0]->parent_id){ //jika memiliki parent_id, insert juga
                    $dataToInsert[] = [
                        'menu_id' => $results[0]->parent_id,
                        'role_id' => $roleId
                    ];
                }
                $dataToInsert[] = [
                    'menu_id' => $menuId,
                    'role_id' => $roleId
                ];
            }

            $dataToInsert = array_unique(array_map('serialize', $dataToInsert));
            $dataToInsert = array_map('unserialize', $dataToInsert);

            DB::table('role_menu')->insert($dataToInsert);
            DB::commit(); 

            AuditTrailHelper::AddAuditTrail('Update', 'Assign Menu (' . $roleId . ') to Role (' . $roleId . ')');
            return response()->json(['success' => true], 200);
        } catch (\Exception $e) {
            DB::rollBack(); 
            return response()->json(['success' => false, 'error' => $e->getMessage()], 500);
        }
    }

}
