<?php
session_start();
include './veriflog.php';
include './core.php';
$pageSequence = $_SESSION['sequence'];
$toDiv = "contentZone" . $pageSequence;
$resultZoneDiv = "resultZone" . $pageSequence;
$tableZone = "#tableZone" . $pageSequence;
$_SESSION['sequence']++;
//echo  dirname(__FILE__);  
//echo $_SERVER['DOCUMENT_ROOT'] . "   ".dirname(__FILE__)."  ".str_replace($_SERVER['DOCUMENT_ROOT'],"",dirname(__FILE__)) ;

$rpage = "roles.php";
$profileList = $dba->getProfileListByRight($_SESSION['right']);
$headerRes = $dba->getSystemHeader(-1);
$moduleRes = $dba->getSystemModules(-1);
$accessres = $dba->getAccessLevel($levelId, false);

$roleName = "";
$roleDesc = "";
$json = "";
$all = "-- Tout --";
$tblData = "";
$roleId = $_REQUEST['roleId'];

$datares = $dba->getSystemRolesById($roleId);
$roleName = $datares[0]['role_name_v'];
$roleDesc = $datares[0]['role_desc_v'];


$actionType = 1; // Add form default value
if (isset($_REQUEST['actionType']) && $_REQUEST['actionType'] == 2) {
    $actionType = 2;
    $datares = $dba->getRoleDetailsById($roleId);
    $total = count($datares);







    for ($i = 0; $i < $total; $i++) {

        $headerName = ($datares[$i]['header_menu_id_n'] == -1) ? $all : $datares[$i]['headerName'];
        $moduleName = ($datares[$i]['module_id_n'] == -1) ? $all : $datares[$i]['module'];
        $menuName = ($datares[$i]['menu_id_n'] == -1) ? $all : $datares[$i]['menu'];
        $submenuName = ($datares[$i]['object_id_n'] == -1) ? $all : $datares[$i]['submenu'];
        $submenuName = str_replace("'", "''", $submenuName);
        $rightName = $datares[$i]['uright'];

        $json = $json . '{ "HeaderName":"'.addslashes($headerName). '","HeaderValue":' .$datares[$i]['header_menu_id_n']. ',"ApplicationName":"'.$moduleName.'","ApplicationValue":"' .$datares[$i]['module_id_n'].'","MenuId":' . $datares[$i]['menu_id_n'] . ',"MenuName":"' .addslashes($menuName). '","SubMenuId":' . $datares[$i]['object_id_n'] . ',"SubMenuName":"' . $submenuName. '","RightId":"' . $datares[$i]['object_right_n'] . '","RightName":"' . $rightName . '","ItemId":"' . $i .'"  },';

        
      
        $tblData = $tblData . '<tr><td align="center"><a href="#" data-href="' . $i . '" class="optRem"><img src="images/b_drop.png"/></a> </td> <td>' . $headerName . '</td><td>'.$moduleName.'</td><td>' . $menuName . '</td><td>' . $submenuName . '</td><td>' . $rightName . '</td></tr>';
    }


    if ($total > 0) {
        $json = rtrim($json, ",");
        $json = "[" . $json . "]";
    }
    
   // echo $json;
}
?>

<style type="text/css">

    /* Style the form */
    #regForm {
        background-color: #ffffff;
        margin: 5px auto;
        padding: 40px;
        width: 80%;
        min-width: 300px;
    }

    /* Style the input fields */
    input {
        padding: 10px;
        width: 50%;
        font-size: 17px;
        font-family: Raleway;
        border: 1px solid #aaaaaa;
    }

    textarea {
        padding: 10px;
        width: 50%;
        font-size: 17px;
        font-family: Raleway;
        border: 1px solid #aaaaaa;
    }

    /* Mark input boxes that gets an error on validation: */
    input.invalid {
        background-color: #ffdddd;
    }

    /* Hide all steps by default: */
    .tab {
        display: none;
    }

    /* Make circles that indicate the steps of the form: */
    .step {
        height: 15px;
        width: 15px;
        margin: 0 2px;
        background-color: #bbbbbb;
        border: none;
        border-radius: 50%;
        display: inline-block;
        opacity: 0.5;
    }

    /* Mark the active step: */
    .step.active {
        opacity: 1;
    }

    /* Mark the steps that are finished and valid: */
    .step.finish {
        background-color: #04AA6D;
    }

    .moduleId323 { background-color:#E9F2FE }


</style>
<section class="content" >
    <div class="row">
        <div class="col-sm-12">
            <div class="panel panel-bd lobidrag">
                <div class="panel-heading">
                    <div class="btn-group" id="buttonexport">
                        <a href="#">
                            <h4>Ajouter un rôle</h4>
                        </a>
                    </div>
                </div>
                <div class="panel-body">

                    <form id="regForm" action="exec_add_edit_role.php"  method="post" onsubmit="return false;">

                        <div class="form-group">
                            <label><em> <h3>Information de base </h3> </em> </label>
                        </div>

                        <!-- One "tab" for each step in the form: -->
                        <div class="tab">




                            <div class="form-group">
                                <label>Identifiant du rôle</label>

                            </div>
                            <div>

                                <input type="text" name="roleName" id="roleName"  size="40" required value="<?php echo $roleName; ?>"  />
                            </div>

                            <div class="form-group">
                                <label >Description du rôle</label>

                            </div>
                            <div class="form-group">

                                <textarea id="roleDesc" name="roleDesc" rows="5" cols="50"><?php echo $roleDesc; ?></textarea>

                            </div>

                        </div>

                        <div class="tab">


                            <div class="form-group">
                                <div class="form-group col-md-12">
                                    <label>Selection des entêtes </label>
                                </div>


                            </div>
                            <div class="form-group">
                                <div class="form-group col-md-12">

<!--  <select name="moduleId" id="moduleId" class="moduleId" size="10" onchange="populate_select('moduleId', 'menuId', 'get_modules.php');" > -->

                                    <select name="headerId" id="headerId" class="headerId" size="5" style="width:100%;" >
                                        <option value="-1"  > -- Tout --</option>

                                        <?php for ($i = 0; $i < count($headerRes); $i++) { ?>

                                            <option value="<?php echo $headerRes[$i]['level_id_n']; ?>" ><?php echo $headerRes[$i]['menu_name_v']; ?></option>

                                        <?php } ?>

                                    </select>

                                </div>



                            </div>

                            <div class="form-group">
                                <div class="form-group col-md-12">
                                    <label>Selection des applications </label>
                                </div>


                            </div>
                            <div class="form-group">
                                <div class="form-group col-md-12">

<!--  <select name="moduleId" id="moduleId" class="moduleId" size="10" onchange="populate_select('moduleId', 'menuId', 'get_modules.php');" > -->

                                    <select name="applicationId" id="applicationId" class="applicationId" size="5" style="width:100%;" >
                                        <option value="-1"  > -- Tout --</option>


                                    </select>

                                </div>



                            </div>

                            <div class="form-group">
                                <div class="form-group col-md-12">
                                    <label>Selection des menus </label>
                                </div>


                            </div>
                            <div class="form-group">
                                <div class="form-group col-md-12">

<!--  <select name="moduleId" id="moduleId" class="moduleId" size="10" onchange="populate_select('moduleId', 'menuId', 'get_modules.php');" > -->

                                    <select name="menuId" id="menuId" class="menuId" size="5" style="width:100%;" >
                                        <option value="-1"  > -- Tout --</option>


                                    </select>

                                </div>



                            </div>


                            <div class="form-group">
                                <div class="form-group col-md-12">
                                    <label>Selection des sous-menus </label>
                                </div>


                            </div>
                            <div class="form-group">
                                <div class="form-group col-md-12">

<!--  <select name="moduleId" id="moduleId" class="moduleId" size="10" onchange="populate_select('moduleId', 'menuId', 'get_modules.php');" > -->

                                    <select name="submenuId" id="submenuId" class="submenuId" size="5" style="width:100%;" >
                                        <option value="-1"  > -- Tout --</option>



                                    </select>

                                </div>



                            </div>


                            <div class="form-group">
                                <div class="form-group col-md-12">
                                    <label>Selection des droits </label>
                                </div>


                            </div>
                            <div class="form-group">
                                <div class="form-group col-md-12">

                                    <select name="rightId" id="rightId" class="rightId" size="5" style="width:100%"  >
                                        <?php for ($i = 0; $i < count($accessres); $i++) { ?>

                                            <option value="<?php echo $accessres[$i]['access_n']; ?>" ><?php echo $accessres[$i]['access_desc_v']; ?></option>

                                        <?php } ?>


                                    </select>

                                </div>



                            </div>





                            <div class="form-group">


                                <input type="button" name="addRoleDetails" id="addRoleDetails" class="addRoleDetails" value="Ajouter"  />

                                <input type="hidden" name="postJsonData" id="postJsonData" class="postJsonData" value='<?php echo $json; ?>' />
                                <input type="hidden" name="actionType" id="actionType" class="actionType" value="<?php echo $actionType; ?>" />
                                <input type="hidden" name="roleId" id="roleId" class="roleId" value="<?php echo $roleId; ?>" />


                            </div>





                            <div class="form-group">

                                <div id="menuZone" style="overflow:scroll; width:100%; height:200px" >
                                    <table id="tblRoleMenus"  width="100%"  class="table table-striped table-bordered"  >
                                        <thead>
                                            <tr>
                                                <th>Action</th>
                                                <th>Entêtes</th>
                                                <th>Applications</th>
                                                <th>Menu</th>
                                                <th>Sous-menu</th>
                                                <th>Droit</th>
                                            </tr>
                                        </thead>
                                        <tbody>

                                        <?php echo $tblData; ?>
                                         </tbody>
                                    </table>

                                </div>



                            </div>


                        </div>


                        <div style="overflow:auto;">
                            <div style="float:right;">
                                <button type="button" id="cancelBtn" onclick="getPage('roles.php', 'content-wrapper');">Annuler</button>
                                <button type="button" id="prevBtn" onclick="prev(-1)">Précédent</button>
                                <button type="button" id="nextBtn" onclick="nextPrev(1)">Suivant</button>
                            </div>
                        </div>

                        <!-- Circles which indicates the steps of the form: -->
                        <div style="text-align:center;margin-top:40px;">
                            <span class="step"></span>
                            <span class="step"></span>

                        </div>

                    </form>

                </div>
            </div>
        </div>
    </div>


</section>





<script type="text/javascript">




    $(document).ready(function () {
        prep_modal('<?php echo $toDiv; ?>', '<?php echo $rpage; ?>');

        $(".headerId").change(function () {

            $(".applicationId").load("get_application_menus.php?id=" + $(this).val());

        });


        $(".applicationId").change(function () {

            $(".menuId").load("get_menus_dtls.php?id=" + $(this).val());

        });



        $(".menuId").change(function () {

            $(".submenuId").load("get_submenus_dtls.php?id=" + $(this).val());

        });


      $('form').on("submit", function (event) {

                var toDiv = $("form").attr('toDiv');
                var rpage = $("form").attr('returnPage');

                $.post($(this).attr("action"), $(this).serialize(), function (data) {

                    var obj = jQuery.parseJSON(data);

                    if (obj.errorCode == 0) {

                        //alert( obj.errorMessage );

                        //    $.alert( obj.errorMessage );

                        $.confirm({
                            icon: 'glyphicon glyphicon-ok',
                            title: 'RESULTAT',
                            content: obj.errorMessage,
                            type: 'green',
                            typeAnimated: true,
                            buttons: {
                                confirm: {
                                    text: 'OK',
                                    action : function () {
                                    $("#content-wrapper").load("roles.php");
                                }
                                    
                                          }
                                        
                             
                            }

                        });
                        //  alert(data);


                    } else {


                        $.alert({
                            icon: 'glyphicon glyphicon-warning-sign',
                            title: 'RESULTAT',
                            content: obj.errorMessage,
                            type: 'red',
                            typeAnimated: true
                        });

                        // $.alert( obj.errorMessage );
                    }

                });
                // return false; // prevent normal submit


                event.preventDefault();

                /*
                 var postData = $(this).serializeArray();
                 var formURL = $(this).attr("action");
                 
                 $.ajax({
                 url: formURL,
                 type: "POST",
                 data: postData,
                 success: function(data, textStatus, jqXHR) {
                 
                 alert("Processing the form...");
                 
                 },
                 error: function(jqXHR, status, error) {
                 console.log(status + ": " + error);
                 }
                 });
                 event.preventDefault(); */
            });
           


    });


//process add data

    $('.addRoleDetails').on('click', function () {
        // create the backdrop and wait for next modal to be triggered
        // $('body').modalmanager('loading');
        $('#loader').loading({
            message: "Chargement...",
            theme: 'dark'

        });

        var data = "";
        var errorCode = 0;

        var sHeaderName = $('#headerId :selected').text();
        var sHeaderValue = $('#headerId :selected').val();


        var sApplicationName = $('#applicationId :selected').text();
        var sApplicationValue = $('#applicationId  :selected').val();

        var sMenuName = $('#menuId :selected').text();
        var sMenuValue = $('#menuId  :selected').val();

        var sSubMenuName = $('#submenuId :selected').text();
        var sSubMenuValue = $('#submenuId ').val();


        var sRightName = $('#rightId :selected').text();
        var sRightValue = $('#rightId :selected').val();

        var subMenuText = $('#submenuId  option:selected').toArray().map(item => item.text).join();

        var pJsonData = $('#postJsonData ').val();

        var array = subMenuText.toString().split(",");
        var arrayId = sSubMenuValue.toString().split(",");
        var jsonData = "";

        var cmpt = array.length;

        /************Parse selected input ************/
        if (sHeaderValue == undefined) {
            errorCode = 1;
            $.alert({
                icon: 'glyphicon glyphicon-warning-sign',
                title: 'RESULTAT',
                content: 'Veuillez choisir un entête !',
                type: 'red',
                typeAnimated: true
            });


        } else if (sApplicationValue == undefined) {
            errorCode = 2;
            $.alert({
                icon: 'glyphicon glyphicon-warning-sign',
                title: 'RESULTAT',
                content: 'Veuillez choisir une application !',
                type: 'red',
                typeAnimated: true
            });


        } else if (sMenuValue == undefined) {
            errorCode = 2;
            $.alert({
                icon: 'glyphicon glyphicon-warning-sign',
                title: 'RESULTAT',
                content: 'Veuillez choisir un menu !',
                type: 'red',
                typeAnimated: true
            });


        } else if (sSubMenuValue == undefined) {
            errorCode = 3;
            $.alert({
                icon: 'glyphicon glyphicon-warning-sign',
                title: 'RESULTAT',
                content: 'Veuillez choisir un sous-menu !',
                type: 'red',
                typeAnimated: true
            });


        } else
        if (sRightValue == undefined) {
            errorCode = 4;
            $.alert({
                icon: 'glyphicon glyphicon-warning-sign',
                title: 'RESULTAT',
                content: 'Veuillez choisir le droit !',
                type: 'red',
                typeAnimated: true
            });


        }

        /*********************************************/


        if (errorCode == 0) {
            
            var itemId = 0;
            if(pJsonData != ""){
                var tempObj = jQuery.parseJSON(pJsonData);
                itemId = Object.keys(tempObj).length ;
                
              
                
                
            }


            for (let i = 0; i < cmpt; i++) {

                jsonData = jsonData + '{ "HeaderName":"' + sHeaderName + '","HeaderValue":' + sHeaderValue + ',"ApplicationName":"' + sApplicationName + '","ApplicationValue":' + sApplicationValue + ',"MenuId":' + sMenuValue + ',"MenuName":"' + sMenuName + '","SubMenuId":' + arrayId[i] + ',"SubMenuName":"' + array[i] + '","RightId":"' + sRightValue + '","RightName":"' + sRightName + '","ItemId":"' + itemId + '" },';

                /* 
                 data = '<tr><td><input type="checkbox" id="cb' + i + '" value="' + array[i] + '"/></td> <td>' + sModuleName + '</td><td>' + sMenuName + '</td><td>' + array[i] + '</td><td>' + sRightName + '</td></tr>' ;
                 
                 $('#extendedModal #tblRoleMenus').append(data ) ; */
             itemId++;
            }

            jsonData = jsonData.substring(0, jsonData.length - 1);

            EntryJson = "[" + jsonData + "]";
            
            

            //alert(EntryJson);

            /********************** Extra JSON Work *************
             subMenuData = subMenuData.substring(0, subMenuData.length - 1);
             
             var subMenuJson = '"SubMenu":[' + subMenuData + ']' ;
             var moduleJson = '"Module":[' + moduleData + ']' ; 
             var menuJson = '"Menu":[' + menuData + ']' ; 
             var EntryJson = '"EntryPoint":[{' + moduleJson + ',' + menuJson + ',' + subMenuJson + '}]';
             
             subMenuData = subMenuData + '{"SubMenuId":'+ arrayId[i] +',"SubMenuName":"'+ array[i] +'", "RightId":"'+ sRightValue +'", "RightName":"'+ sRightName +'"},';
             subMenuData = subMenuData.substring(0, subMenuData.length - 1); 
             ****************************************************/



            /***************** Write JSON to Table *****************/


            var obj = jQuery.parseJSON(EntryJson);
            var i = 0 ;

            $.each(obj, function (index, value) {
              //  alert(value.itemId);

                data = '<tr><td align="center"><a href="#" data-href="' + value.ItemId + '" class="optRem"><img src="images/b_drop.png"/></a> </td> <td>' + value.HeaderName + '</td> <td>' + value.ApplicationName + '</td><td>' + value.MenuName + '</td><td>' + value.SubMenuName + '</td><td>' + value.RightName + '</td></tr>';

                $('#tblRoleMenus').append(data);
                
                i++;
            });



            if (pJsonData == "") {
                /***************** First Run *****************/

                /**************Set the JSON POST DATA ***************/

                $('#postJsonData ').val(EntryJson);




            } else {

                /************* Concatenate OLD JSON POST to New JSON POST ******/
                var oldJsonStr = $('#postJsonData ').val();


                var joinPostJson = oldJsonStr.substring(0, oldJsonStr.length - 1) + ',' + EntryJson.substring(1);

                $('#postJsonData ').val(joinPostJson);

            }


        }





        //alert(EntryJson);



        $('#loader').loading('stop');

        //alert($('#extendedModal #moduleId').val());



    });



 

    $("#tblRoleMenus").on("click", '.optRem', function () {
        var optId = $(this).attr('data-href');
        var currentPostJdata = $('#postJsonData ').val();

       //alert(currentPostJdata);

        var jsonData = "";

        $('table tr').find('td').remove();
        var obj = jQuery.parseJSON(currentPostJdata);
        var i = 0;
        var data = "";
        
        //alert(Object.keys(obj).length);

        $.each(obj, function (index, value) {
           // alert(value.ItemId + " ---- " + optId);
           
          
             
             if (value.ItemId !== optId) {
                 
                  data = data + '<tr><td align="center"><a href="#" data-href="' + i + '" class="optRem"><img src="images/b_drop.png"/></a> </td> <td>' + value.HeaderName + '</td> <td>' + value.ApplicationName + '</td><td>' + value.MenuName + '</td><td>' + value.SubMenuName + '</td><td>' + value.RightName + '</td></tr>';
                  jsonData = jsonData + '{ "HeaderName":"' + value.HeaderName + '","HeaderValue":' + value.HeaderValue + ',"ApplicationName":"' + value.ApplicationName + '","ApplicationValue":' + value.ApplicationValue  + ',"MenuId":' + value.MenuId + ',"MenuName":"' + value.MenuName + '","SubMenuId":' + value.SubMenuId + ',"SubMenuName":"' + value.SubMenuName + '","RightId":"' + value.RightId + '","RightName":"' + value.RightName + '","ItemId":"' + i + '" },';


                i++;
            }


        /*
            if (value["ItemId"] != optId) {

                // data = '<tr><td align="center"><a href="#" data-href="' + value["SubMenuId"] + '" class="optRem"><img src="images/b_drop.png"/></a> </td> <td>' + value["ModuleName"] + '</td><td>' + value["MenuName"] + '</td><td>' + value["SubMenuName"] + '</td><td>' + value["RightName"] + '</td></tr>';
              

            }
            else {
                
                // alert(value["ItemId"] + " ---- " + optId);
            }

          i++;  */

        });
        
      //  alert(data);
         
         $('#tblRoleMenus').append(data);

        jsonData = jsonData.substring(0, jsonData.length - 1);
        
        
        

        var EntryJson = "[" + jsonData + "]";
        
       // alert(EntryJson);
        $('#postJsonData ').val(EntryJson);
        
         event.preventDefault();


    });


    var currentTab = 0; // Current tab is set to be the first tab (0)
    showTab(currentTab); // Display the current tab

    function showTab(n) {
        // This function will display the specified tab of the form ...
        var x = document.getElementsByClassName("tab");
        x[n].style.display = "block";
        // ... and fix the Previous/Next buttons:
        if (n == 0) {
            document.getElementById("prevBtn").style.display = "none";
        } else {
            document.getElementById("prevBtn").style.display = "inline";
        }
        if (n == (x.length - 1)) {
            document.getElementById("nextBtn").innerHTML = "Soumettre";
        } else {
            document.getElementById("nextBtn").innerHTML = "Suivant";
        }
        // ... and run a function that displays the correct step indicator:
        fixStepIndicator(n)
    }

    function nextPrev(n) {

        if (document.getElementById("nextBtn").innerHTML == "Soumettre") {


            $("#regForm").submit();
           


        } else {


            var x = document.getElementsByClassName("tab");
            // Exit the function if any field in the current tab is invalid:
            if (n == 1 && !validateForm())
                return false;
            // Hide the current tab:
            x[currentTab].style.display = "none";
            // Increase or decrease the current tab by 1:
            currentTab = currentTab + n;
            // if you have reached the end of the form... :
            if (currentTab >= x.length) {
                //...the form gets submitted:
                alert("the form gets submitted");
                document.getElementById("regForm").submit();
                return false;
            }
            // Otherwise, display the correct tab:
            showTab(currentTab);

        }


        // This function will figure out which tab to display

    }


   function prev(n) {

        var x = document.getElementsByClassName("tab");
            // Exit the function if any field in the current tab is invalid:
            if (n == 1 && !validateForm())
                return false;
            // Hide the current tab:
            x[currentTab].style.display = "none";
            // Increase or decrease the current tab by 1:
            currentTab = currentTab + n;
            // if you have reached the end of the form... :
            if (currentTab >= x.length) {
                //...the form gets submitted:
                alert("the form gets submitted");
                document.getElementById("regForm").submit();
                return false;
            }
            // Otherwise, display the correct tab:
            showTab(currentTab);


        // This function will figure out which tab to display

    }


    function validateForm() {
        // This function deals with validation of the form fields
        var x, y, i, valid = true;
        x = document.getElementsByClassName("tab");
        y = x[currentTab].getElementsByTagName("input");
        // A loop that checks every input field in the current tab:
        for (i = 0; i < y.length; i++) {
            // If a field is empty...
            if (y[i].value == "") {
                // add an "invalid" class to the field:
                y[i].className += " invalid";
                // and set the current valid status to false:
                valid = false;
            }
        }
        // If the valid status is true, mark the step as finished and valid:
        if (valid) {
            document.getElementsByClassName("step")[currentTab].className += " Terminer";
        }
        return valid; // return the valid status
    }

    function fixStepIndicator(n) {
        // This function removes the "active" class of all steps...
        var i, x = document.getElementsByClassName("step");
        for (i = 0; i < x.length; i++) {
            x[i].className = x[i].className.replace(" active", "");
        }
        //... and adds the "active" class to the current step:
        x[n].className += " active";
    }


</script>

<link rel="stylesheet" href="css/jquery-confirm.min.css">
<script src="js/jquery-confirm.min.js"></script>
<script type="text/javascript" src="js/svam.js" ></script>
