<?php 
include 'head.php';
include('xcrud/xcrud.php');
$xcrud = Xcrud::get_instance();
echo Xcrud::load_css(); 
include 'nav.php';
?>
<div class="content-wrapper">
	<section class="content-header">
		<h1>Users</h1>
    </section>
    <section class="content">      
		<div class="row">
			<div class="col-lg-12 col-xs-12">
			  <?php
				$xcrud->table('users');				
				$xcrud->validation_required("user_name,password,user_type");
				$xcrud->change_type('user_type','select','admin','admin,user,Godown');
				if ($_SESSION['ticl_user_type'] != 'admin') {
					$xcrud->where('user_id',$_SESSION['ticl_admin_id']);
					$xcrud->unset_add();
					$xcrud->disabled('user_type');
				}
				$xcrud->unset_title();
				$xcrud->unset_remove();
				
				if (!in_array('View', $permissionsArray['User'])) {
					$xcrud->unset_view();
				}
				if (!in_array('Edit', $permissionsArray['User'])) {
					$xcrud->unset_edit();
				}
				
				if ($_SESSION['ticl_user_type'] == 'admin') {
					$xcrud->button('javascript:;', 'Permissions', 'fa fa-edit', '', array('data-toggle' => 'modal', 'data-target' => '#UserPermissionsModal', 'onclick' => 'getUserPermission({user_id})'));
				}
				echo $xcrud->render();
			  ?>
			</div>
		</div>
    </section>
</div>

<div id="UserPermissionsModal" 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="userPermissionContainer">
                       
                        </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'])) {
	$values=array();
	$bdd = new DB();
	$user_id = $_POST["hidden_User_id"];
  
	$existingEntries = $bdd->getOne("SELECT * FROM permissions WHERE user_id = $user_id",$values);
  
  if ($existingEntries > 0) {
      $deleteResult = $bdd->execute("DELETE FROM permissions WHERE user_id = $user_id",$values);
      if ($deleteResult) {
          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]) : '';
                  
                  $insertResult = $bdd->execute("INSERT INTO permissions (user_id, page, button) VALUES ($user_id, '$main_permission', '$submenu_permissions')",$values);
                  
                  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 {
      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]) : '';
              
              $insertResult = $bdd->execute("INSERT INTO permissions (user_id, page, button) VALUES ($user_id, '$main_permission', '$submenu_permissions')",$values);
              
              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 'footer.php';
echo Xcrud::load_js();
?>

<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 getUserPermission(id) {
    $('#hidden_User_id').val(id);

    $.ajax({
        url: 'ajax_content.php',
        type: 'GET',
        data: { id: id },
        success: function(response) {
            $('#userPermissionContainer').html(response);
        },
        error: function() {
            alert('An error occurred while fetching dynamic content.');
        }
    });
}
</script>