<?php
include("includes/session.php");
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include 'includes/db.php'; // Ensure this includes the database connection

function getUpperDesignations($designation) {
    // Define hierarchy levels
    $hierarchy = [
        'General Manager' => 1,
        'Asst. General Manager' => 2,
        'Functional Head' => 3,
        'Cluster Head' => 4,
        'Store Manager' => 5,
        'Asst. Store Manager' => 6,
        'Department Manager' => 7,
        'Officer' => 8,
        'Sr. Officer' => 9,
        'Executive' => 10,
        'Support' => 11,
        'Chauffeur' => 12,
        'Driver' => 13
    ];

    $currentLevel = $hierarchy[$designation] ?? null;

    if ($currentLevel === null) {
        die("Error: Designation '$designation' is not defined in the hierarchy.");
    }

    // Filter to get designations above the current level
    $upperDesignations = array_filter($hierarchy, fn($level) => $level < $currentLevel);

    return array_keys($upperDesignations);
}

// Fetch the logged-in employee's designation, store, and department
$loggedInDesignation = $_SESSION['designation'];
$loggedInStore = $_SESSION['store_name'];
$loggedInDepartmentName = $_SESSION['department_name'];



if (empty($loggedInDesignation) || empty($loggedInStore) || empty($loggedInDepartmentName)) {
    die('Error: Missing user designation, store, or department information.');
}

// Get the list of upper designations
$upperDesignations = getUpperDesignations($loggedInDesignation);

// Debug the upper designations
// var_dump("Upper Designations:", $upperDesignations);

if (!empty($upperDesignations)) {
    // Prepare the query to fetch upper employees in the same store and department
    $placeholders = str_repeat('?,', count($upperDesignations) - 1) . '?';

    $sql = "
        SELECT * 
        FROM Employees 
        WHERE designation IN ($placeholders) 
          AND store_name = ? 
          AND department_name = ?
    ";
    
    // Debug the SQL query
    // var_dump("SQL Query:", $sql);

    // Execute the query with the list of upper designations, store, and department
    $stmt = $conn->prepare($sql);

    // Combine upper designations with store and department filters
    $params = array_merge($upperDesignations, [$loggedInStore, $loggedInDepartmentName]);

    // Debug the parameters being passed
    //  var_dump("Query Parameters:", $params);

    $stmt->execute($params);
    $upperEmployees = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Debug the fetched data
    // var_dump("Fetched Upper Employees:", $upperEmployees);
} else {
    var_dump("No upper designations found for designation:", $loggedInDesignation);
}

$title = "Upper-Level Employees by Store and Department"; 
include("includes/head.php");
?>
	<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>My Hierarchy</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">
										<?php if (!empty($upperEmployees)): ?>
            <table class="table table-center table-hover datatable">
                <thead class="thead-light">
                    <tr>
                        <th>#</th>
                        <th>Emp Code</th>
                        <th>Employee Name</th>
                        <th>Department</th>
                        <th>Designation</th>
                         <th>Store</th>
                        <th>Email</th>
                        <th>Mobile</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $displayIndex = 1; 
                    foreach ($upperEmployees as $employee): 
                        
                    ?>
                    <tr>
                        <td><?= $displayIndex ?></td>
                        <td><?= htmlspecialchars($employee['employee_code']) ?></td>
                        <td><?= htmlspecialchars($employee['employee_name']) ?></td>
                        <td><?= htmlspecialchars($employee['department_name']) ?></td>
                        <td><?= htmlspecialchars($employee['designation']) ?></td>
                        <td><?= htmlspecialchars($employee['store_name']) ?></td>
                        <td><?= htmlspecialchars($employee['personal_email_id']) ?></td>
                        <td><?= htmlspecialchars($employee['personal_mobile_no']) ?></td>
                        <td>
                            <a href="edit_employee.php?id=<?= $employee['employee_code'] ?>" class="btn btn-sm btn-primary">Edit</a>
                            <a href="employee-details.php?id=<?= $employee['employee_code'] ?>" class="btn btn-sm btn-info">View</a>
                            <a href="delete_employee.php?id=<?= $employee['employee_code'] ?>" class="btn btn-sm btn-danger">Delete</a>
                        </td>
                    </tr>
                    <?php $displayIndex++; endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <p>No Upper employees found.</p>
        <?php endif; ?>
    </div>
									</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>