<?php
$_page_title = "Role Permission";
$_main_root = '../';
require_once $_main_root . 'db/model.php';

$db = new Model();
$roles = $db->GetUserRole(1, true);
$menus = $db->GetMenu();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (isset($_POST['type']) && $_POST['type'] === 'rp') {
        $role_id = intval($_POST['id']);
        $permissions = $db->GetMenuPermissions($role_id);
        echo json_encode($permissions);
        exit;
    }

    if (isset($_POST['role_id'])) {
        $role_id = intval($_POST['role_id']);
        $menus = $db->GetMenu();

        if ($db->DeleteRolePermissions($role_id)) {
            $values = [];
            foreach ($menus as $menu) {
                $menu_id = $menu['id'];
                $view = isset($_POST["view_$menu_id"]) ? 1 : 0;
                $add = isset($_POST["add_$menu_id"]) ? 1 : 0;
                $edit = isset($_POST["edit_$menu_id"]) ? 1 : 0;
                $delete = isset($_POST["delete_$menu_id"]) ? 1 : 0;

                $values[] = "($role_id, $menu_id, $view, $add, $edit, $delete)";
            }

            if (!empty($values)) {
                $flag = $db->SetRolePermissions($values);
                echo json_encode(['success' => $flag, 'message' => 'Permissions updated successfully.']);
            } else {
                echo json_encode(['success' => false, 'message' => 'No permissions found to save.']);
            }
        }
        exit;
    }
}

function BuildMenuTree($menus, $parent_id = 0)
{
    $menuList = [];
    foreach ($menus as $menu) {
        if ($menu['parent_id'] == $parent_id) {
            $subMenu = BuildMenuTree($menus, $menu['id']);
            if ($subMenu) {
                $menu['subMenu'] = $subMenu;
            }
            $menuList[] = $menu;
        }
    }
    // sort by 'order'
    usort($menuList, function ($a, $b) {
        return $a['order'] <=> $b['order'];
    });
    return $menuList;
}

function RenderMenuRows($menuTree, $level = 0)
{
    foreach ($menuTree as $m) {
        $indent = str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $level);
        $bold = $m['parent_id'] == 0 ? 'fw-bold' : '';

        echo "<tr>";
        echo "<td class='$bold'>{$indent}" . htmlspecialchars($m['name']) . "</td>";

        foreach (['view', 'add', 'edit', 'delete'] as $action) {
            echo '<td><div class="form-check d-flex justify-content-center">';
            echo "<input type='checkbox' name='{$action}_{$m['id']}' class='form-check-input action-check'>";
            echo '</div></td>';
        }

        echo "</tr>";

        if (isset($m['subMenu'])) {
            RenderMenuRows($m['subMenu'], $level + 1);
        }
    }
}

$menuTree = BuildMenuTree($menus);

include($_main_root . 'content/shared/header.php');
?>

<!-- modal -->
<div id="modalDiv"></div>

<div class="container container-fluid">
    <div class="my-4 d-flex justify-content-between align-items-center">
        <h2 style="color:var(--s-text-color);">Role Base Permission</h2>
        <div id="custom-form-dark">
            <select name="role_id" id="role_id" class="form-select">
                <?php foreach ($roles as $r) { ?>
                    <option value="<?= $r['id']; ?>"><?= $r['name']; ?></option>
                <?php } ?>
            </select>
        </div>
    </div>

    <form id="permissionForm" method="POST">
        <input type="hidden" name="role_id" id="selected_role_id" value="">
        <div class="row my-4 table-responsive">
            <table class="table table-sm table-dark table-hover table-bordered" id="custom-form-dark">
                <thead style="color:var(--s-text-color);">
                    <tr class="">
                        <th>Menu</th>
                        <th class="col-1">View</th>
                        <th class="col-1">Add</th>
                        <th class="col-1">Edit</th>
                        <th class="col-1">Delete</th>
                    </tr>
                </thead>
                <tbody>
                    <?php RenderMenuRows($menuTree); ?>
                </tbody>
            </table>
            <div class="text-center text-md-end">
                <button class="btn btn-sm action-btn-1 px-5" type="submit">Update</button>
            </div>
        </div>
    </form>

</div>
<?php $s_scripts = ['role_permission']; ?>
<?php include($_main_root . 'content/shared/footer.php'); ?>