<?php include("includes/session.php");
include 'includes/db.php';

ini_set('display_errors',1);
ini_set('system_startup_errors',1);
error_reporting(E_ALL);

$currUserInfo = getUserInfoById($user_id, $conn);
// print_r($currUserInfo);

if($currUserInfo['role'] == 'admin'){
    $stmt = $conn->prepare("SELECT * From users");
    $stmt->execute();
    $Users = $stmt->fetchAll(PDO::FETCH_ASSOC);
}else{
    $fetchPos = $currUserInfo['child_position']; // This is a comma-separated string (e.g., "1,2,3")
    $fetchPosArray = explode(',', $fetchPos); // Convert the string into an array (e.g., [1, 2, 3])
    
    // Prepare the SQL statement using the IN clause to match any current_position with the child_position values
    $in = str_repeat('?,', count($fetchPosArray) - 1) . '?'; // Creates a placeholder string like '?, ?, ?'
    
    $sql = "SELECT * FROM users WHERE current_position IN ($in)";
    $stmt = $conn->prepare($sql);
    
    // Execute the query, passing the child positions as parameters
    $stmt->execute($fetchPosArray);
    
    $Users = $stmt->fetchAll(PDO::FETCH_ASSOC);

}

// print_r($Users);

$stmt = $conn->prepare("SELECT * From position_master");
$stmt->execute();
$Positions = $stmt->fetchAll(PDO::FETCH_ASSOC);

$title = "Manage Users"; 
include("includes/head.php");

function getPositionById($id, $pdo){
    $stmt = $pdo->prepare("SELECT name FROM position_master WHERE id=$id");
    $stmt->execute();
    $positionName = $stmt->fetch(PDO::FETCH_ASSOC);
    $positionName = $positionName['name'];
    return $positionName;
}

function getUserInfoById($id, $pdo){
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id=$id");
    $stmt->execute();
    $userInfo = $stmt->fetch(PDO::FETCH_ASSOC);
    return $userInfo;
}
?>
	<body>
	
	
		<!-- Main Wrapper -->
		<div class="main-wrapper">
		
			<!-- Header -->
			<?php include("includes/header.php"); ?>
			<!-- /Header -->
			
				<!-- Sidebar -->
				<?php include("includes/sidebar.php"); ?>
				<!-- /Sidebar -->
	
			<!-- Page Wrapper -->
			<div class="page-wrapper">
				<div class="content container-fluid">				
					<!-- Page Header -->
					<div class="page-header">
						<div class="content-page-header ">
							<h5>Users</h5>
							<div class="list-btn">
								<ul class="filter-list">
									<li>
										<!--<a class="btn btn-filters w-auto popup-toggle" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-original-title="Filter"><span class="me-2"><img src="assets/img/icons/filter-icon.svg" alt="filter"></span>Filter </a>-->
									</li>
									<li>
										<a class="btn btn-primary" href="javascript:void(0);" data-bs-toggle="modal" data-bs-target="#add_user"><i class="fa fa-plus-circle me-2" aria-hidden="true"></i>Add user</a>
									</li>
								</ul>
							</div>
						</div>
					</div>
					<!-- /Page Header -->
					
					<div class="row">
						<div class="col-sm-12">
							<div class="card-table">
								<div class="card-body">
									<div class="table-responsive">
										<table class="table table-center table-hover datatable">
											<thead class="thead-light">
												<tr>
													<th>#</th>
													<th>User Name</th>
													<th>Mobile Number</th>
													<th>Position</th>
													<th>Created on</th>
													<th>Status</th>
													<th Class="no-sort">Actions</th>
												</tr>
											</thead>
											<tbody>
											    <?php 
											    $displayIndex = 1; 
											    foreach($Users as $i=> $user) { 
    											    if($user['role'] == 'admin'){
    											        continue;
    											    }
    											    
    											    $posId = $user['current_position'];
    											    $positionName = getPositionById($posId, $conn);
											    ?>
												<tr>
													<td><?= $displayIndex ?></td>
													<td>
														<h2 class="table-avatar">
															<!--<a href="profile.html" class="avatar avatar-sm me-2"><img class="avatar-img rounded-circle" src="assets/img/profiles/avatar-14.jpg" alt="User Image"></a>-->
															<a href="#"><?=  $user['fname'] . ' ' . $user['lname']; ?></a>
														</h2>
													</td>
													<td><?= $user['phone']; ?></td>
													<td><?= $positionName ?></td>
													<td><?= date("d M Y, h:i A", strtotime($user['created_at'])); ?></td>
													<td><span class="badge  bg-success-light"><?= $user['status'] ?></span></td>
													<td class="d-flex align-items-center">
														<div class="dropdown dropdown-action">
															<a href="#" class=" btn-action-icon " data-bs-toggle="dropdown" aria-expanded="false"><i class="fas fa-ellipsis-v"></i></a>
															<div class="dropdown-menu dropdown-menu-right">
																<ul>
																	<li>
																		<a class="dropdown-item" href="javascript:void(0);" data-bs-toggle="modal" data-bs-target="#edit_user<?= $user['id'] ?>"><i class="far fa-edit me-2"></i>Edit</a>
																	</li>
																	<li>
																		<a class="dropdown-item" href="javascript:void(0);" data-bs-toggle="modal" data-bs-target="#delete_modal<?= $user['id'] ?>"><i class="far fa-trash-alt me-2"></i>Delete</a>
																	</li>
																</ul>
															</div>
														</div>
													</td>
												</tr>
												
												<!-- Edit User -->
                                    			<div class="modal custom-modal modal-lg fade" id="edit_user<?= $user['id'] ?>" role="dialog">
                                    				<div class="modal-dialog modal-dialog-centered modal-md">
                                    					<div class="modal-content">
                                    						<div class="modal-header border-0 pb-0">
                                    							<div class="form-header modal-header-title text-start mb-0">
                                    								<h4 class="mb-0">Edit User</h4>
                                    							</div>
                                    							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
                                    								
                                    							</button>
                                    						</div>
                                    						<form id="edit_userForm<?= $user['id'] ?>" action="manage_users.php" method="post" enctype="multipart/form-data">
                                    						    <input type="hidden" name="updateUser" value="true">
                                    						    <input type="hidden" name="userId" value="<?= $user['id'] ?>">
                                    							<div class="modal-body">
                                    								<div class="row">
                                    									<div class="col-md-12">
                                    										<div class="card-body">
                                    											<div class="form-groups-item">
                                    												<!--<h5 class="form-title">Profile Picture</h5>-->
                                    												<!--<div class="profile-picture">-->
                                    												<!--	<div class="upload-profile">-->
                                    												<!--		<div class="profile-img">-->
                                    												<!--			<img id="blah2" class="avatar" src="assets/img/profiles/avatar-10.jpg" alt="profile-img">-->
                                    												<!--		</div>-->
                                    												<!--		<div class="add-profile">-->
                                    												<!--			<h5>Upload a New Photo</h5>-->
                                    												<!--			<span>Profile-pic.jpg</span>-->
                                    												<!--		</div>-->
                                    												<!--	</div>-->
                                    												<!--	<div class="img-upload">-->
                                    												<!--		<label class="btn btn-primary">-->
                                    												<!--			Upload <input type="file">-->
                                    												<!--		</label>-->
                                    												<!--		<a class="btn btn-remove">Remove</a>-->
                                    												<!--	</div>										-->
                                    												<!--</div>-->
                                    												<div class="row">
                                    													<div class="col-lg-4 col-md-6 col-sm-12">
                                    														<div class="input-block mb-3">
                                    															<label>First Name</label>
                                    															<input name="fname" value="<?= $user['fname'] ?>" type="text" class="form-control" placeholder="Enter First Name">
                                    														</div>
                                    													</div>
                                    													<div class="col-lg-4 col-md-6 col-sm-12">
                                    														<div class="input-block mb-3">
                                    															<label>Last Name</label>
                                    															<input name="lname" value="<?= $user['lname'] ?>" type="text" class="form-control" placeholder="Enter Last Name">
                                    														</div>
                                    													</div>
                                    													<div class="col-lg-4 col-md-6 col-sm-12">
                                    														<div class="input-block mb-3">
                                    															<label>Middle Name</label>
                                    															<input name="mname" value="<?= $user['mname'] ?>" type="text" class="form-control" placeholder="Enter User Name">
                                    														</div>
                                    													</div>
                                    													<div class="col-lg-4 col-md-6 col-sm-12">
                                    														<div class="input-block mb-3">
                                    															<label>Email</label>
                                    															<input type="email" class="form-control" name="email" value="<?= $user['email'] ?>" placeholder="Enter Email Address">
                                    														</div>											
                                    													</div>
                                    													<div class="col-lg-4 col-md-6 col-sm-12">
                                    														<div class="input-block mb-3">
                                    															<label>Phone Number</label>
                                    															<input type="text" class="form-control" name="phone" value="<?= $user['phone'] ?>" placeholder="Enter Phone Number">
                                    														</div>
                                    													</div>
                                    													<div class="col-lg-4 col-md-6 col-sm-12">											
                                    														<div class="input-block mb-3">
                                    															<label>Current Position</label>
                                    															<select name="current_position" class="select">
                                    																<option>Select Position</option>
                                    																<?php foreach($Positions as $pos){ ?>
                                    														            <option value="<?= $pos['id']; ?>" <?= ($user['current_position']==$pos['id']) ? 'selected' : '' ?>><?= $pos['name']; ?></option>
                                    																<?php } ?>
                                    															</select>
                                    														</div>
                                    													</div>
                                    													<div class="col-lg-4 col-md-6 col-sm-12">
                                    														<div class="pass-group" id="passwordInput1">
                                    															<div class="input-block">
                                    																<label>Password</label>
                                    																<input type="password" class="form-control pass-input" name="password" value="<?= $user['password'] ?>" placeholder="">
                                    																<span class="toggle-password feather-eye"></span>
                                    															</div>
                                    														</div>
                                    													</div>
                                    													<div class="col-lg-4 col-md-6 col-sm-12">
                                    														<div class="pass-group" id="passwordInput4">
                                    															<div class="input-block">
                                    																<label>Confirm Password</label>
                                    																<input type="password" class="form-control pass-input" name="cpassword" value="<?= $user['password'] ?>" placeholder="">
                                    																<span class="toggle-password feather-eye"></span>
                                    															</div>
                                    														</div>
                                    													</div>

                                    													<div class="col-lg-4 col-md-6 col-sm-12">											
                                    														<div class="input-block ">
                                    															<label>Parent Position</label>
                                    															<select name="parent_position" class="select">
                                    																<option>Select Position</option>
                                    																<?php foreach($Positions as $pos){ ?>
                                    														            <option value="<?= $pos['id']; ?>" <?= ($user['parent_position']==$pos['id']) ? 'selected' : '' ?>><?= $pos['name']; ?></option>
                                    																<?php } ?>
                                    															</select>
                                    														</div>
                                    													</div>
                                    													<div class="col-lg-4 col-md-6 col-sm-12">
                                                                                            <div class="input-block ">
                                                                                                <label>Child Position</label>
                                                                                                <!-- Make sure the 'multiple' attribute is present to allow multi-select -->
                                                                                                <select name="child_position[]" class="select" multiple>
                                                                                                    <option>Select Position</option>
                                                                                                    <?php
                                                                                                    // Assuming $user['child_position'] is an array of selected child positions
                                                                                                    $selectedChildPositions = explode(',', $user['child_position']); // Assuming stored as a comma-separated string
                                                                                        
                                                                                                    foreach ($Positions as $pos) {
                                                                                                        // Check if the current position is in the selected positions array
                                                                                                        $isSelected = in_array($pos['id'], $selectedChildPositions) ? 'selected' : '';
                                                                                                    ?>
                                                                                                        <option value="<?= $pos['id']; ?>" <?= $isSelected ?>><?= $pos['name']; ?></option>
                                                                                                    <?php } ?>
                                                                                                </select>
                                                                                            </div>
                                                                                        </div>
                                    													<div class="col-lg-4 col-md-6 col-sm-12">											
                                    														<div class="input-block ">
                                    															<label>Status</label>
                                    															<select name="status" class="select" required>
                                                                                                    <option value="">Select Status</option>
                                                                                                    <option value="active" <?php echo ($user['status'] == 'active') ? 'selected' : ''; ?>>Active</option>
                                                                                                    <option value="inactive" <?php echo ($user['status'] == 'inactive') ? 'selected' : ''; ?>>Inactive</option>
                                                                                                </select>
                                    														</div>
                                    													</div>
                                    												</div>
                                    											</div>						
                                    											
                                    										</div>
                                    									</div>
                                    								</div>
                                    							</div>
                                    							<div class="modal-footer">
                                    								<button type="button" data-bs-dismiss="modal" class="btn btn-primary paid-cancel-btn me-2">Cancel</button>
                                    								<button name="submit" type="submit" class="btn btn-primary paid-continue-btn" data-bs-dismiss="modal">Update</button>
                                    							</div>
                                    						</form>
                                    					</div>
                                    				</div>
                                    			</div>
                                    			<!-- /Edit User -->
                                    			
                                    			
                        						<!-- Delete Items Modal -->
                                    			<div class="modal custom-modal fade" id="delete_modal<?= $user['id'] ?>" role="dialog">
                                                    <div class="modal-dialog modal-dialog-centered modal-md">
                                                        <div class="modal-content">
                                                            <div class="modal-body">
                                                                <div class="form-header">
                                                                    <h3>Delete Users</h3>
                                                                    <p>Are you sure you want to delete?</p>
                                                                </div>
                                                                <div class="modal-btn delete-action">
                                                                    <div class="row">
                                                                        <div class="col-6">
                                                                            <a href="#" class="btn btn-primary paid-continue-btn delete-user" data-id="<?= $user['id'] ?>">Delete</a>
                                                                        </div>
                                                                        <div class="col-6">
                                                                            <a href="#" data-bs-dismiss="modal" class="btn btn-primary paid-cancel-btn">Cancel</a>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>

                                    			<!-- /Delete Items Modal -->
												<?php $displayIndex++; } ?>
											</tbody>
										</table>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
			<!-- /Page Wrapper -->

			<!-- Add Asset -->
			<div class="toggle-sidebar">
				<div class="sidebar-layout-filter">
					<div class="sidebar-header">
						<h5>Filter</h5>
						<a href="#" class="sidebar-closes"><i class="fa-regular fa-circle-xmark"></i></a>
					</div>
					<div class="sidebar-body">						
						<form action="#" autocomplete="off">
							<!-- Customer -->
							<div class="accordion" id="accordionMain1">
								<div class="card-header-new" id="headingOne">
									<h6 class="filter-title">
									<a href="javascript:void(0);" class="w-100" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
										Customer	
										<span class="float-end"><i class="fa-solid fa-chevron-down"></i></span>
									</a> 
									</h6>
								</div>
							
								<div id="collapseOne" class="collapse show" aria-labelledby="headingOne"  data-bs-parent="#accordionExample1">
									<div class="card-body-chat">
										<div class="row">
											<div class="col-md-12">
												<div id="checkBoxes1">
													<div class="form-custom">														
														<input type="text" class="form-control" id="member_search1" placeholder="Search here">
														<span><img src="assets/img/icons/search.svg" alt="img"></span>
													</div>
													<div class="selectBox-cont">
														<label class="custom_check w-100">
															<input type="checkbox" name="username">
															<span class="checkmark"></span>  John Smith
														</label>
														<label class="custom_check w-100">
															<input type="checkbox" name="username">
															<span class="checkmark"></span>  Johnny
														</label>
														<label class="custom_check w-100">
															<input type="checkbox" name="username">
															<span class="checkmark"></span>  Robert
														</label>
														<label class="custom_check w-100">
															<input type="checkbox" name="username">
															<span class="checkmark"></span> Sharonda
														</label>
														<!-- View All -->
														<div class="view-content">
															<div class="viewall-One">	
																<label class="custom_check w-100">
																	<input type="checkbox" name="username">
																	<span class="checkmark"></span> Pricilla
																</label>
																<label class="custom_check w-100">
																	<input type="checkbox" name="username">
																	<span class="checkmark"></span> Randall
																</label>
															</div>
															<div class="view-all">
																<a href="javascript:void(0);" class="viewall-button-One"><span class="me-2">View All</span><span><i class="fa fa-circle-chevron-down"></i></span></a>
															</div>
														</div>
														<!-- /View All -->
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
							</div>
							<!-- /Customer -->

							<!-- Select Date -->
							<div class="accordion" id="accordionMain2">
								<div class="card-header-new" id="headingTwo">
									<h6 class="filter-title">
									<a href="javascript:void(0);" class="w-100 collapsed"  data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo">
										Select Date	
										<span class="float-end"><i class="fa-solid fa-chevron-down"></i></span>
									</a> 
									</h6>
								</div>
							
								<div id="collapseTwo" class="collapse" aria-labelledby="headingTwo"  data-bs-parent="#accordionExample2">
									<div class="card-body-chat">
										<div class="input-block mb-3">
											<label class="form-control-label">From</label>
											<div class="cal-icon">
												<input type="email" class="form-control datetimepicker" placeholder="DD-MM-YYYY">
											</div>
										</div>
										<div class="input-block mb-3">
											<label class="form-control-label">To</label>
											<div class="cal-icon">
												<input type="email" class="form-control datetimepicker" placeholder="DD-MM-YYYY">
											</div>
										</div>
									</div>
								</div>
							</div>
							<!-- /Select Date -->

							<!-- By Status -->
							<div class="accordion accordion-last" id="accordionMain3">
								<div class="card-header-new" id="headingThree">
									<h6 class="filter-title">
									<a href="javascript:void(0);" class="w-100 collapsed"  data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="true" aria-controls="collapseThree">
										By Status	
										<span class="float-end"><i class="fa-solid fa-chevron-down"></i></span>
									</a> 
									</h6>
								</div>
							
								<div id="collapseThree" class="collapse" aria-labelledby="headingThree"  data-bs-parent="#accordionExample3">
									<div class="card-body-chat">
										<div id="checkBoxes2">
											<div class="form-custom">														
												<input type="text" class="form-control" id="member_search2" placeholder="Search here">
												<span><img src="assets/img/icons/search.svg" alt="img"></span>
											</div>
											<div class="selectBox-cont">
												<label class="custom_check w-100">
													<input type="checkbox" name="bystatus">
													<span class="checkmark"></span> Active
												</label>
												<label class="custom_check w-100">
													<input type="checkbox" name="bystatus">
													<span class="checkmark"></span>  Restricted
												</label>
											</div>
										</div>	
									</div>
								</div>
							</div>
							<!-- /By Status -->
							<div class="filter-buttons">
								<button type="submit" class="d-inline-flex align-items-center justify-content-center btn w-100 btn-primary">
									Apply
								</button>
								<button type="submit" class="d-inline-flex align-items-center justify-content-center btn w-100 btn-secondary">
									Reset
								</button>
							</div>
						</form>
						
					</div>
				</div>
			</div>	
			<!--/Add Asset -->

			<!-- Add User -->
			<div class="modal custom-modal modal-lg fade" id="add_user" role="dialog">
				<div class="modal-dialog modal-dialog-centered modal-md">
					<div class="modal-content">
						<div class="modal-header border-0 pb-0">
							<div class="form-header modal-header-title text-start mb-0">
								<h4 class="mb-0">Add User</h4>
							</div>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
								
							</button>
						</div>
						<form id="add_userForm" method="post" enctype="multipart/form-data">
							<div class="modal-body">
								<div class="row">
									<div class="col-md-12">
										<div class="card-body">
											<div class="form-groups-item">
												<!--<h5 class="form-title">Profile Picture</h5>-->
												<!--<div class="profile-picture">-->
												<!--	<div class="upload-profile">-->
												<!--		<div class="profile-img">-->
												<!--			<img id="blah" class="avatar" src="assets/img/profiles/avatar-10.jpg" alt="profile-img">-->
												<!--		</div>-->
												<!--		<div class="add-profile">-->
												<!--			<h5>Upload a New Photo</h5>-->
												<!--			<span>Profile-pic.jpg</span>-->
												<!--		</div>-->
												<!--	</div>-->
												<!--	    <div class="img-upload">-->
            <!--                                                <input type="file" name="profile_pic" id="profile_pic" style="display:none;" onchange="readURL(this);">-->
            <!--                                                <a class="btn btn-primary me-2" onclick="document.getElementById('profile_pic').click();">Upload</a>-->
            <!--                                                <a class="btn btn-remove" onclick="removeImage();">Remove</a>-->
            <!--                                            </div>										-->
												<!--</div>-->
												<div class="row">
													<div class="col-lg-4 col-md-6 col-sm-12">
														<div class="input-block mb-3">
															<label>First Name</label>
															<input name="fname" type="text" class="form-control" placeholder="Enter First Name">
														</div>
													</div>
													<div class="col-lg-4 col-md-6 col-sm-12">
														<div class="input-block mb-3">
															<label>Middle Name</label>
															<input name="mname" type="text" class="form-control" placeholder="Enter Middle Name">
														</div>
													</div>
													<div class="col-lg-4 col-md-6 col-sm-12">
														<div class="input-block mb-3">
															<label>Last Name</label>
															<input name="lname" type="text" class="form-control" placeholder="Enter Last Name">
														</div>
													</div>
													<div class="col-lg-4 col-md-6 col-sm-12">
														<div class="input-block mb-3">
															<label>Email</label>
															<input name="email" type="email" class="form-control" placeholder="Enter Email Address">
														</div>											
													</div>
													<div class="col-lg-4 col-md-6 col-sm-12">
														<div class="input-block mb-3">
															<label>Phone Number</label>
															<input name="phone" type="text" class="form-control" placeholder="Enter Phone Number" name="name">
														</div>
													</div>
													<div class="col-lg-4 col-md-6 col-sm-12">											
														<div class="input-block mb-3">
															<label>Current Position</label>
															<select onchange="updatePosition(event)" name="current_position" class="select">
																<option>Select Position</option>
																<?php foreach($Positions as $pos){ ?>
														            <option value="<?= $pos['id']; ?>" selected><?= $pos['name']; ?></option>
																<?php } ?>
															</select>
														</div>
													</div>
													<div class="col-lg-4 col-md-6 col-sm-12">
														<div class="pass-group" id="3">
															<div class="input-block">
																<label>Password</label>
																<input name="password" type="password" class="form-control pass-input" placeholder="">
																<span class="toggle-password feather-eye"></span>
															</div>
														</div>
													</div>
													<div class="col-lg-4 col-md-6 col-sm-12">
														<div class="pass-group" id="passwordInput2">
															<div class="input-block">
																<label>Confirm Password</label>
																<input name="cpassword" type="password" class="form-control pass-input" placeholder="">
																<span class="toggle-password feather-eye"></span>
															</div>
														</div>
													</div>
													<div class="col-lg-4 col-md-6 col-sm-12">											
														<div class="input-block mb-3">
															<label>Parent Position</label>
															<select id="parentPosition" name="parent_position" class="select">
																<option>Select Position</option>
																<?php foreach($Positions as $pos){ ?>
														            <option value="<?= $pos['id']; ?>" selected><?= $pos['name']; ?></option>
																<?php } ?>
															</select>
														</div>
													</div>
													<div class="col-lg-4 col-md-6 col-sm-12">
                                                        <div class="input-block mb-3">
                                                            <label>Child Position</label>
                                                            <select id="childPosition" name="child_position[]" class="select" multiple>
                                                                <option>Select Position</option>
                                                                <?php foreach($Positions as $pos){ ?>
                                                                    <option value="<?= $pos['id']; ?>"><?= $pos['name']; ?></option>
                                                                <?php } ?>
                                                            </select>
                                                        </div>
                                                    </div>
													<div class="col-lg-4 col-md-6 col-sm-12">											
														<div class="input-block ">
															<label>Status</label>
															<select name="status" class="select">
																<option>Select Status</option>
																<option value="active">Active</option>
																<option value="inactive">Inactive</option>
															</select>
														</div>
													</div>
												</div>
											</div>						
											
										</div>
									</div>
								</div>
							</div>
							<div class="modal-footer">
								<button type="button" data-bs-dismiss="modal" class="btn btn-back cancel-btn me-2">Cancel</button>
								<button name="createUser" type="submit" data-bs-dismiss="modal" class="btn btn-primary paid-continue-btn">Add User</button>
							</div>
						</form>
					</div>
				</div>
			</div>
			<!-- /Add User -->
			
		</div>
		<!-- /Main Wrapper -->

		<!-- jQuery -->
        <script src="assets/js/jquery-3.7.1.min.js"></script>
		
		<!-- Bootstrap Core JS -->
		<script src="assets/js/bootstrap.bundle.min.js"></script>

		<!-- Datatable JS -->
		<script src="assets/plugins/datatables/datatables.min.js"></script>

		<!-- select CSS -->
		<script src="assets/plugins/select2/js/select2.min.js"></script>
		
		<!-- Slimscroll JS -->
		<script src="assets/plugins/slimscroll/jquery.slimscroll.min.js"></script>
		
		<!-- Datepicker Core JS -->
		<script src="assets/plugins/moment/moment.min.js"></script>
		<script src="assets/js/bootstrap-datetimepicker.min.js"></script>
		
		<!-- multiselect JS -->
		<script src="assets/js/jquery-ui.min.js"></script>

		<!-- Theme Settings JS -->
		<script src="assets/js/theme-settings.js"></script>
		<script src="assets/js/greedynav.js"></script>
		
		<!-- Custom JS -->
		<script src="assets/js/script.js"></script>

	</body>
<script>
$('.delete-user').click(function(e) {
            e.preventDefault(); // Prevent the default anchor click behavior
            var userId = $(this).data('id'); // Get the user ID from data-id attribute
            var deleteUser = true;
            // Perform AJAX request to delete the user
            $.ajax({
                type: "POST",
                url: "manage_users.php", // Change this to your delete script
                data: { 
                    id: userId,
                    deleteUser: deleteUser
                },
                success: function(response) {
                    if (response.status === 'success') {
                        // Optionally, you can refresh the page or remove the deleted user from the UI
                        toastr.success(response.message);
                        location.reload(); // Reload the page to see changes
                    } else {
                        alert("Failed to delete user: " + response.message);
                    }
                },
                error: function() {
                    alert("An error occurred. Please try again.");
                }
            });
        });
$('#add_userForm').submit(function(e){
    e.preventDefault();

    // Create a FormData object to include file data
    var formData = new FormData(this);
    formData.append('createUser', true); // Append the createUser key to FormData

    $.ajax({
        url: 'manage_users.php',
        type: 'POST',
        data: formData,
        processData: false, // Prevent jQuery from processing the data
        contentType: false, // Prevent jQuery from setting the content-type
        dataType: 'json', // Ensure response is JSON
        success: function(response){
            if(response.status == 'success'){
                toastr.success(response.message);
                $('#add-user').modal('hide'); // Close the modal on success
                window.location.reload();
            } else {
                toastr.error(response.message);
            }
        },
        error: function(xhr, status, error){
            console.log(xhr.responseText); // Log the actual response for debugging
            toastr.error('An error occurred while adding the user.');
        }
    });
});
function updatePosition(event) {
    // alert('helo');
    const positions = <?php echo json_encode($Positions); ?>;
    const selectedValue = event.target.value;
    
    // Get the parent position select element
    const parentSelect = document.getElementById('parentPosition');

    // Set the parent position based on the current position
    console.log(positions);
    parentSelect.value = selectedValue;
}


// $(document).on('submit', 'form[id^="edit_userForm_"]', function(e) {
//     e.preventDefault();
//     console.log('Form submission intercepted'); // Debug line
//     alert('hello'); // Change 'helelo' to 'hello' for clarity
//     var formId = $(this).attr('id');
//     var userId = formId.split('_')[2];
//     var formData = new FormData(this);
//     formData.append('updateUser', true);
//     formData.append('userId', userId);

//     $.ajax({
//         url: 'manage_users.php',
//         type: 'POST',
//         data: formData,
//         processData: false,
//         contentType: false,
//         dataType: 'json',
//         success: function(response) {
//             if (response.status == 'success') {
//                 toastr.success(response.message);
//                 $('#edit_user' + userId).modal('hide');
//                 window.location.reload();
//             } else {
//                 toastr.error(response.message);
//             }
//         },
//         error: function(xhr, status, error) {
//             console.log(xhr.responseText);
//             toastr.error('An error occurred while updating the user.');
//         }
//     });
// });



// function readURL(input) {
//     if (input.files && input.files[0]) {
//         var reader = new FileReader();
//         reader.onload = function (e) {
//             document.getElementById('blah').src = e.target.result;
//         }
//         reader.readAsDataURL(input.files[0]);
//         console.log(input.files[0]); // This will log the selected file to the console
//     }
// }

// function removeImage() {
//     document.getElementById('blah').src = 'assets/img/profiles/avatar-10.jpg'; // Set default image
//     document.getElementById('profile_pic').value = ''; // Clear file input
// }
</script>
</html>