<link rel="stylesheet" href="../css/sweet-alert.css" /> 

<?php 
include("../connection.php");
include("../user.php");

$id = $_REQUEST['id'];
$role_name = $_REQUEST['role_name'];
$ho_admin = $_REQUEST['ho_admin'];
$menu = $_REQUEST['menu'];
$cnt = count($menu);
$code = $_REQUEST['user_id'];
$user = $_SESSION['user'];

// Update role_master
$update_role = mysqli_query($con, "UPDATE `role_master` SET `role_name`='$role_name', `ho_admin_access`='$ho_admin' WHERE `id`='$id'");

if ($update_role) {
    // Delete old permissions
    mysqli_query($con, "DELETE FROM role_detail WHERE code='$code'");

    // Insert updated permissions
    for ($r = 0; $r < $cnt; $r++) {
        $ra = "new" . ($r + 1);
        $new = $_REQUEST[$ra]; // permission (View/Edit/All)
        $me = explode(":", $menu[$r]);
        $menu_id = $me[0];
        $submenu_id = $me[1];

        $view = $edit = $all = "";

        if ($new == "View") {
            $view = "View";
        } elseif ($new == "Edit") {
            $edit = "Edit";
        } elseif ($new == "All") {
            $all = "All";
        }

        mysqli_query($con, "INSERT INTO role_detail (code, menu_id, submenu_id, view_only, edit_only, all_only, created_by) 
                            VALUES ('$code', '$menu_id', '$submenu_id', '$view', '$edit', '$all', '$user')");
    }
    ?>
    <script>
    setTimeout(function() {
        swal({
            title: "Successfully",
            text: "Completed!",
            type: "success"
        }, function() {
            window.location = "role_master.php";
        });
    }, 100);
    </script>  
    <?php
} else {
    ?>
    <script>
    setTimeout(function() {
        swal({
            title: "Not",
            text: "Completed!",
            type: "error"
        }, function() {
            window.location = "role_master.php";
        });
    }, 100);
    </script>      
    <?php
}
?>

<script src="../js/sweet-alert.js"></script>
