<?php
include 'header.php';
include('xcrud/xcrud.php');
echo Xcrud::load_css();
$xcrud = Xcrud::get_instance();
$xcrud->table('user');
$xcrud->fields('username,password,name,type');
$xcrud->validation_required('username,password,name,type');
$xcrud->change_type('type', 'select', 'admin', 'admin,user,app_user,restricted_user,hsrp_user');
$xcrud->unset_title();

if ($type != 'admin') {
    $xcrud->where('user_id', $_SESSION['admin_id']);
    $xcrud->unset_add();
    $xcrud->unset_remove();
}

?>

<div class="row">
    <div class="col-sm-12"><button class="btn btn-blue btn-block">Users</button></div>
    <div class="col-sm-12">&nbsp;</div>
    <div class="col-sm-12">
        <?php
        if ($type == 'admin') {
            $xcrud->button('javascript:;', 'Screen View', 'fa fa-edit', '', array('data-toggle' => 'modal', 'data-target' => '#UserInfoModal', 'onclick' => 'updateUserInfo({user_id})'));
        }
        echo $xcrud->render();
        ?>
    </div>
</div>
</div>
</div>
</div>
<div id="UserInfoModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Edit User</h4>
            </div>
            <div class="modal-body">
                <form method="post">
                    <input type="hidden" id="hidden_User_id" name="hidden_User_id">
                    <div>
                        <h5>Select Permissions:</h5>
                       
                        <div id="dynamicContentContainer">
                       
                        </div>
                    </div>
                    <button type="submit" name="submit_User_info" class="btn btn-info" style="margin-top:5px">Submit</button>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<?php


if (isset($_POST['submit_User_info'])) {
  $bdd = new DB();
  $user_id = $_POST["hidden_User_id"];
  
  // Check if there are existing entries for the same user_id
  $existingEntries = $bdd->getOne("SELECT * FROM Permissions WHERE UId = $user_id");
  
  if ($existingEntries > 0) {
      // Delete previous permissions for the same user_id
      $deleteResult = $bdd->execute("DELETE FROM Permissions WHERE UId = $user_id");
      if ($deleteResult) {
          // Insert new permissions
          if(isset($_POST["main_permissions"]) && is_array($_POST["main_permissions"])) {
              foreach($_POST["main_permissions"] as $main_permission) {
                  $submenu_permissions = isset($_POST["submenu_permissions"][$main_permission]) ? implode(',', $_POST["submenu_permissions"][$main_permission]) : '';
                  
                  // Insert a new row for each main permission with its sub-menu permissions
                  $insertResult = $bdd->execute("INSERT INTO Permissions (UId, Tabs, Submenu) VALUES ($user_id, '$main_permission', '$submenu_permissions')");
                  
                  if ($insertResult) {
                      $check = 1;
                  } else {
                      echo "Error inserting user: " . $bdd->error;
                  }
              }
              if(isset($check)){ 
                  echo "<script>alert('User with permissions and sub-menu permissions has been added successfully!')</script>"; 
              }
          } else {
              echo "No main permissions selected.";
          }
      } else {
          echo "Error deleting previous permissions: " . $bdd->error;
      }
  } else {
      // Insert new permissions directly since there are no existing entries
      if(isset($_POST["main_permissions"]) && is_array($_POST["main_permissions"])) {
          foreach($_POST["main_permissions"] as $main_permission) {
              $submenu_permissions = isset($_POST["submenu_permissions"][$main_permission]) ? implode(',', $_POST["submenu_permissions"][$main_permission]) : '';
              
              // Insert a new row for each main permission with its sub-menu permissions
              $insertResult = $bdd->execute("INSERT INTO Permissions (UId, Tabs, Submenu) VALUES ($user_id, '$main_permission', '$submenu_permissions')");
              
              if ($insertResult) {
                  $check = 1;
              } else {
                  echo "Error inserting user: " . $bdd->error;
              }
          }
          if(isset($check)){ 
              echo "<script>alert('User with permissions and sub-menu permissions has been added successfully!')</script>"; 
          }
      } else {
          echo "No main permissions selected.";
      }
  }

  $bdd->disconnect();
}
?>
<!-- Include jQuery from a CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function toggleSubmenu(submenuId) {
    var submenu = document.getElementById(submenuId);
    if (submenu.style.display === 'none' || submenu.style.display === '') {
        submenu.style.display = 'block';
    } else {
        submenu.style.display = 'none';
    }
}

function updateUserInfo(id) {
    $('#hidden_User_id').val(id);

    $.ajax({
        url: 'ajax_content.php', // URL to your PHP script
        type: 'GET',
        data: { id: id }, // Pass id as a data object
        success: function(response) {
            // Replace the content of a specific div with the dynamic content
            $('#dynamicContentContainer').html(response);
        },
        error: function() {
            alert('An error occurred while fetching dynamic content.');
        }
    });
}

</script>
<?php
include "footer.php";
echo Xcrud::load_js();
?>