<?= $this->element('user_management_nav', array(
    'title' => __('Role Pages Association'),
    'permissions' => $user_permission,
    'showNavigationButtons' => false
)); ?>


  <div class="row">
        <div class="col-md-12">
        <?= $this->Form->create(); ?>
         <?= $this->Form->hidden('selected_pages'); ?>
          <div class="box box-primary">
            <div class="box-header">

			  <div class="row">
				 <div class="col-md-6">
				     
                 <div class="form-group">
                        <label for="role">Role Name</label>

                        <span id="ANCSb1">
                                <?php
                                echo $this->Form->input('role', array('label' => false, 'options' => $roles,
                                    'empty' => __('Select a role'), 'class' => 'form-control','id'=>'company-role'));
                                ?>
                                <img src="<?php echo $this->Url->build('/images/ajax-loader.gif'); ?>"
                                     class="loading_icon"
                                     style="display:none;float: right"/>
                            </span>
                    
                        </div>
           
				 </div>
                              
                              <div class="col-md-6">
				     
                 <div class="form-group" id="modul-element">
                        <label for="role">Module</label>
                            <span id="ANCSb1">
                                <?php
                                echo $this->Form->input('drop', array('label' => false, 'options' => $companymodules,
                                    'empty' => __('Select a Module'), 'id'=>'module-dropdown', 'class' => 'form-control'));
                                ?>
                                
                            </span>
                    
                        </div>
           
				 </div>
			  </div>
			</div><!-- box-header end -->
	  <div class="box-body table-responsive ">
	    <div class="table-responsive">
                            <table class="table table-bordered" id="role-table">

                                <thead>
                                <tr>
                                    <th>
                                        Id
                                    </th>

                                    <th>
                                        Module
                                    </th>

                                    <th >
                                        Sub Module
                                    </th>

                                    <th>
                                        Pages
                                    </th>

                                    <th>
                                        Action
                                    </th>

                                </tr>
                                </thead>

                                <tbody>
                                <?php
                                $submoduleCounter = 0;
                                foreach ($modules as $module) { ?>

                                    <tr id="module-table_<?= $module->id; ?>">
                                        <td>
                                            <?= $module->id; ?>
                                        </td>

                                        <td>
                                            <?= $module->name; ?>
                                        </td>

                                        <td colspan="3">
                                            <table class="table"  style="width:100%;">
                                                <tbody>
                                                <?php
                                                
                                                foreach ($module->sub_modules as $submodule) {
                                                    if(!$submodule->pages){
                                                        continue;
                                                    }
                                                    ?>
                                                    <tr>
                                                        <td style="width:50%;"><input id="sub_module_<?= $submodule->id;?>" class="sub_module_<?= $submoduleCounter;?>" type="checkbox"
                                                                                      <?php 
//                                                                                      if(isset($submittingcheck)){
//                                                                                          if($submittingcheck[$submoduleCounter]==1){
//                                                                                              echo 'checked';
//                                                                                          }
//                                                                                      }
                                                                                      ?>
                                                                                      > <?= $submodule->name; ?></td>
                                                        <td style="width:50%;">
                                                            <table  class="table table-hover"  style="width:100%">
                                                                <tbody>
                                                                <?php
                                                                $pages = array();
                                                                $pageCounter = 0;
                                                                foreach ($submodule->pages as $page) {
                                                                    array_push($pages, $page);
                                                                    //array_push($submodule_with_pages[$submoduleCounter],'page_'.$page->id);
                                                                   $submodule_with_pages[$submoduleCounter][$pageCounter]='page_'.$page->id;
                                                                    ?>

                                                                    <tr>
                                                                    <td style="width:80%;">
                                                                        <?= $page->name; ?>
                                                                    </td>

                                                                    <td style="align-content: right;">
                                                                        <a class="sub_module_<?= $submodule->id;?>"  id="page_<?= $page->id ?>" role="button">  <!--href="#page_<?= $page->id ?>"-->   
                                                                            <i class="fa fa-size fa-remove"></i>
                                                                        </a>
                                                                    </td>
                                                                    </tr>

                                                                    <?php
                                                                  $pageCounter++;  
                                                                }
                                                                
                                                                ?>
                                                                <tbody>
                                                            </table>
                                                        </td>
                                                    </tr>
                                                    <?php
                                                     $submoduleCounter++;
                                                } ?>
                                                </tbody>
                                            </table>
                                        </td>
                                    </tr>

                                    <?php
                                } ?>

                                </tbody>
                            </table>
                        </div>
                        <!-- / table-responsive -->
	  </div><!-- box-body end -->
          <div class="box-footer" id="footer-btn">
	   <div class="col-md-12 text-right mb-15">
                        <?= $this->Form->hidden('submittingcheck')?>   
                        <?= $this->Form->button(__('Save'), ['class' => 'btn btn-primary']) ?>
                   

              
                        <?= $this->Form->button(__('Cancel'), ['class' => 'cancel btn btn-primary']) ?>
                
                
            </div>
	  </div>
	</div><!-- box box-primary end -->
	 <?= $this->Form->end(); ?>
	</div> <!-- col-md-12 end-->
	</div>  <!-- row end -->
		
		   
<style type="text/css">
    .error-message {
        color: #ff0000;
    }

    .table tbody tr td:last-child {
           text-align: left !important;
         /*padding-right: 8px;*/
        padding: 8px !important;
     }




</style>
<!-- Core JavaScript Files -->
<?php echo $this->Html->script('jquery-1.11.2.js'); ?>
<?php echo $this->Html->script('jquery.multi-select.js'); ?>

<script type="text/javascript">
    
    $(window).load(function () {
        refreshIcons();
        //getChecked();
        
        function refreshIcons() {
          
            var selected_pages_element = $("input[name='selected_pages']");
            var selected_pages = selected_pages_element.val();
            var array = selected_pages.split(',');
            
            $("a[id^='page_']").each(function () {
                var page = $(this).prop('id');
                if ($.inArray(page, array) != -1) {
                    $(this).find("i").removeClass('fa-remove');
                    $(this).find("i").addClass('fa-check');
                    $(this).addClass('color-fa2');
                } else {
                    $(this).find("i").removeClass('fa-check');
                    $(this).find("i").addClass('fa-remove');
                    $(this).removeClass('color-fa2');
                }
            });
            
            getChecked(array);
        }
        
        
      
         
         
        $(document).on('change', '#company-role', function () {
             // alert("hello1");
            var selectedValue = $(this).val();
            var selected_pages_element = $("input[name='selected_pages']");
            //alert(selected_pages_element);
           // alert("hello");
            if (selectedValue) {
                $('.loading_icon').show();
                $('.error-message').remove();
                $.ajax({
                    type: "GET",
                    url: '<?=$this->Url->build('/RolePagesAssociation/getAssociatedPages/');?>' + selectedValue,
                    dataType: "json",
                    success: function (response) {
                        $('.loading_icon').hide();
                      //  alert(response);
                        processPages(response);
                    },
                    error: function (xhr, status, error) {
                        $('.loading_icon').hide();
                        selected_pages_element.val('');
                        refreshIcons();
                    }
                });
            } else {
                selected_pages_element.val('');
                refreshIcons();
            }

        });

        function processPages(roles) {
            var selected_pages_element = $("input[name='selected_pages']");
            selected_pages_element.val(roles.selected_pages.join(','));
            if(roles.selected_pages.length>0){
                $('#role-table').show();
                $('#footer-btn').show();
                $('#modul-element').show();  
                getChecked(roles.selected_pages);
            }
            
            refreshIcons();
        }

        $(".cancel").click(function (e) {
            window.location.href = "<?= $this->Url->build('/RolePagesAssociation/')?>";
            return false;

        });
        
        // for checkbox checked start
        
        function getChecked($selected_pages){ 
            
            for($i=0;$i<$submoduleCounter;$i++){
                
                if(isAllchecked($selected_pages,$submodule_with_pages[$i])){
                    checkedList.push(1);
                    $('.sub_module_'+$i).prop('checked',true);
                }else{
                    checkedList.push(0);
                   // $('.sub_module_'+$i).prop('checked',false);
                }
                
               
        }
         $("input[name='submittingcheck']").val(checkedList);
        }
        
            function isAllchecked($selected_pages, $submodule_pages) {   //isAllchecked(superset, subset)
                $selected_pages.sort();
                $submodule_pages.sort();
                var i, j;
                for (i=0,j=0; i<$selected_pages.length && j<$submodule_pages.length;) {
                    if ($selected_pages[i] < $submodule_pages[j]) {
                        ++i;
                    } else if ($selected_pages[i] == $submodule_pages[j]) {
                        ++i; ++j;
                    } else {
                        return false;   // submodule_page[j] not in $selected_pages, so submodule_pages not subset
                    }
                }
                return j == $submodule_pages.length;   // make sure there are no pages left in submodule_pages
            }
        
        // for checkbox checked end
        
        // for check All sub module pages start
        
        $("input[id^='sub_module_']").click(function(e){
             $sub_module_id = $(this).prop('id');
             
             var selected_pages_element = $("input[name='selected_pages']");
            var selected_pages = selected_pages_element.val();
            var checkedValue = [];
             var value = selected_pages_element.val();
             var array = selected_pages.split(',');
             if($(this).prop('checked')==true){
                  
                $('.'+$sub_module_id).each(function(){
                    checkedValue.push($(this).prop('id'));
                });
              //  alert(checkedValue);
               
                if(value != ''){
                    selected_pages_element.val(value+ ',' +checkedValue);
                } else {
                     selected_pages_element.val(checkedValue);
                }
                $("."+$sub_module_id+" i").addClass('fa-check').removeClass('fa-remove');

              }else{
                 
                    $('.'+$sub_module_id).each(function(){
                        checkedValue.push($(this).prop('id'));
                     });
                      
                    //alert(selected_pages_element.val()+"===="+checkedValue);
                     var pagesStr = selected_pages_element.val();
                     var pagesStrArr = pagesStr.split(",");
                     var finalStr = "";
                     for(var index=0;index < pagesStrArr.length;index++ ){
                         
                      if($.inArray(pagesStrArr[index],checkedValue) == -1){
                            if(finalStr == ""){
                                 finalStr = finalStr+pagesStrArr[index];
                             } else {
                                 finalStr = finalStr+","+pagesStrArr[index];
                             }
                       }
                      }
                      
                      //alert(finalStr);
                      selected_pages_element.val(finalStr);
                    
                    
//                    var newVal = '';
//                    if(value != ''){
//                            for($i=0;$i<=checkedValue.length;$i++){
//                             newVal =  removePages(selected_pages_element.val(),checkedValue[$i])
//                            }
//
//                        alert(newVal);
//                       //selected_pages_element.val(newVal);
//                    
//                     
//                    }                
                     $("."+$sub_module_id+" i").removeClass('fa-check').addClass('fa-remove');
                }

        });  
        
        // for check All sub module pages end
        
//        function removePages($pageStr,$checked){
//            
//            if($pageStr.indexOf($checked)>0){
//              $pageStr =  $pageStr.replace($checked,'');
//            }else if($pageStr.indexOf(","+$checked)>0){
//              $pageStr =  $pageStr.replace(","+$checked,'');
//            }
//            
//            return $pageStr;
//        }
        
        $("a[id^='page_']").click(function (e) {
            var selected_pages_element = $("input[name='selected_pages']");
            var selected_pages = selected_pages_element.val();
            var clickedValue = $(this).prop('id');
            
           //alert(clickedValue);
            
            var array = selected_pages.split(',');
            
            if ($.inArray(clickedValue, array) != -1) {
               // alert("1");
                array = $.grep(array, function (value) {
                    return value != clickedValue;
                });
                selected_pages_element.val(array.join(','));
            } else {
                
                var value = selected_pages_element.val();
                if (value != '') {
                    //alert(value + ',' + clickedValue);
                    selected_pages_element.val(value + ',' + clickedValue);
                } else {
                    selected_pages_element.val(clickedValue);
                }
            }
            refreshIcons();
            e.preventDefault();
        });
    });
</script>

<script> 
   $role_value =  $('#company-role :selected').val();
   
   if($role_value == ''){
    $('#role-table').hide();   
     $('#footer-btn').hide();   
     $('#modul-element').hide(); 
   }
   
    
 // submodule info with pages start
 
 $submoduleCounter = <?php echo $submoduleCounter; ?>           
 $submodule_with_pages = <?php echo json_encode($submodule_with_pages); ?>

 // submodule info with pages end 
  
$('#module-dropdown').change(function(){
            if($(this).val()==''){
                $("tr[id^='module-table_']").show();
            }else{
                $("tr[id^='module-table_']").hide();
                $('#module-table_'+$(this).val()).show();
            }
        });
        

var checkedList = [];


</script>

