<?php include("includes/session.php");
ini_set('display_errors', 1);
ini_set('system_startup_errors', 1);
error_reporting(E_ALL);
include 'includes/db.php'; // Ensure this includes the database connection

// Fetch logged-in employee's employee_code (assuming session contains 'employee_code')
$employeeCode = $_SESSION['employee_id']; // Replace with the session key for employee code
// print_r($employeeCode);
// Fetch attendance record for the logged-in employee
if ($employeeCode) {
    $stmt = $conn->prepare("SELECT * FROM employee_attendance WHERE employee_code = ?");
    $stmt->execute([$employeeCode]);
    $attendanceData = $stmt->fetchAll(PDO::FETCH_ASSOC);
    // print_r($attendanceData);
}
else{
    echo "Employee code not found";
}
// echo '<pre>';
// print_r($attendanceData);
// echo '</pre>';
$title = "My Attendance"; 
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>Attendance</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($attendanceData)): ?>
            <table class="table table-center table-hover datatable">
                <thead class="thead-light">
                    <tr>
                        <th>#</th>
                        <th>Employee Code</th>
                        <th>Employee Name</th>
                        <th>Department</th>
                       
                        <th>Status</th>
                        <th>D01</th>
                        <th>D02</th>
                        <th>D03</th>
                        <th>D04</th>
                        <th>D05</th>
                        <th>D06</th>
                        <th>D07</th>
                        <th>D08</th>
                        <th>D09</th>
                        <th>D10</th>
                        <th>D11</th>
                        <th>D12</th>
                        <th>D13</th>
                        <th>D14</th>
                        <th>D15</th>
                        <th>D16</th>
                        <th>D17</th>
                        <th>D18</th>
                        <th>D19</th>
                        <th>D20</th>
                        <th>D21</th>
                        <th>D22</th>
                        <th>D23</th>
                        <th>D24</th>
                        <th>D25</th>
                        <th>D26</th>
                        <th>D27</th>
                        <th>D28</th>
                        <th>D29</th>
                        <th>D30</th>
                        <th>D31</th>
                        <th>Present Days</th>
                        <th>Late Days</th>
                        <th>Early Days</th>
                        <th>One Punch Days</th>
                        <th>Leave Days</th>
                        <th>Tour Days</th>
                        <th>Woff Days</th>
                        <th>Paid Holidays</th>
                        <th>Absent Days</th>
                        <th>Payable Days</th>
                        <th>Incentive Eligible Days</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $displayIndex = 1;
                    foreach ($attendanceData as $attendance): 
                    ?>
                    <tr>
                        <td><?= $displayIndex ?></td>
                        <td><?= htmlspecialchars($attendance['employee_code']) ?></td>
                        <td><?= htmlspecialchars($attendance['employee_name']) ?></td>
                        <td><?= htmlspecialchars($attendance['department_name']) ?></td>
                        
                        <td><?= htmlspecialchars($attendance['emp_status']) ?></td>
                        <td><?= htmlspecialchars($attendance['D01']) ?></td>
                        <td><?= htmlspecialchars($attendance['D02']) ?></td>
                        <td><?= htmlspecialchars($attendance['D03']) ?></td>
                        <td><?= htmlspecialchars($attendance['D04']) ?></td>
                        <td><?= htmlspecialchars($attendance['D05']) ?></td>
                        <td><?= htmlspecialchars($attendance['D06']) ?></td>
                        <td><?= htmlspecialchars($attendance['D07']) ?></td>
                        <td><?= htmlspecialchars($attendance['D08']) ?></td>
                        <td><?= htmlspecialchars($attendance['D09']) ?></td>
                        <td><?= htmlspecialchars($attendance['D10']) ?></td>
                        <td><?= htmlspecialchars($attendance['D11']) ?></td>
                        <td><?= htmlspecialchars($attendance['D12']) ?></td>
                        <td><?= htmlspecialchars($attendance['D13']) ?></td>
                        <td><?= htmlspecialchars($attendance['D14']) ?></td>
                        <td><?= htmlspecialchars($attendance['D15']) ?></td>
                        <td><?= htmlspecialchars($attendance['D16']) ?></td>
                        <td><?= htmlspecialchars($attendance['D17']) ?></td>
                        <td><?= htmlspecialchars($attendance['D18']) ?></td>
                        <td><?= htmlspecialchars($attendance['D19']) ?></td>
                        <td><?= htmlspecialchars($attendance['D20']) ?></td>
                        <td><?= htmlspecialchars($attendance['D21']) ?></td>
                        <td><?= htmlspecialchars($attendance['D22']) ?></td>
                        <td><?= htmlspecialchars($attendance['D23']) ?></td>
                        <td><?= htmlspecialchars($attendance['D24']) ?></td>
                        <td><?= htmlspecialchars($attendance['D25']) ?></td>
                        <td><?= htmlspecialchars($attendance['D26']) ?></td>
                        <td><?= htmlspecialchars($attendance['D27']) ?></td>
                        <td><?= htmlspecialchars($attendance['D28']) ?></td>
                        <td><?= htmlspecialchars($attendance['D29']) ?></td>
                        <td><?= htmlspecialchars($attendance['D30']) ?></td>
                        <td><?= htmlspecialchars($attendance['D31']) ?></td>
                        <td><?= htmlspecialchars($attendance['present_days']) ?></td>
                        <td><?= htmlspecialchars($attendance['late_days']) ?></td>
                        <td><?= htmlspecialchars($attendance['early_days']) ?></td>
                        <td><?= htmlspecialchars($attendance['onepunch_days']) ?></td>
                        <td><?= htmlspecialchars($attendance['leave_days']) ?></td>
                        <td><?= htmlspecialchars($attendance['tour_days']) ?></td>
                        <td><?= htmlspecialchars($attendance['woff_days']) ?></td>
                        <td><?= htmlspecialchars($attendance['paid_holidays']) ?></td>
                        <td><?= htmlspecialchars($attendance['absent_days']) ?></td>
                        <td><?= htmlspecialchars($attendance['payable_days']) ?></td>
                        <td><?= htmlspecialchars($attendance['incentive_eligible_days']) ?></td>
                    </tr>
                    <?php $displayIndex++; endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <p>No attendance records 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>