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

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

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

// Pagination variables
$limit = 100; // Number of rows per page
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// Fetch target data with pagination
$stmt = $conn->prepare("
    SELECT 
        target_id,
        product_group_name, 
        product_name, 
        target_qty, 
        cateogry,
        ach_qty, 
        q_ach_perc, 
        target_value, 
        ach_value, 
        v_ach_perc, 
        bac_t_qty, 
        bac_a_qty, 
        bac_q_ach_perc 
    FROM target_data 
    LIMIT :limit OFFSET :offset
");
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$targetData = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch total rows for pagination
$countStmt = $conn->prepare("SELECT COUNT(*) as total FROM target_data");
$countStmt->execute();
$totalRows = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];

// Calculate total pages
$totalPages = ceil($totalRows / $limit);
?>
	<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>Employee Target Data</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>Product Group Name</th>
                                <th>Product Name</th>
                                <th>Target Quantity</th>
                                <th>Achieved Quantity</th>
                                <th>Quantity Achievement %</th>
                                <th>Target Value</th>
                                <th>Achieved Value</th>
                                <th>Value Achievement %</th>
                                <th>Category</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $displayIndex = 1;
                            foreach($targetData as $target) { 
                            ?>
                            <tr>
                                <td><?= $displayIndex ?></td>
                                <td><?= htmlspecialchars($target['product_group_name']) ?></td>
                                <td><?= htmlspecialchars($target['product_name']) ?></td>
                                <td><?= htmlspecialchars($target['target_qty']) ?></td>
                                <td><?= htmlspecialchars($target['ach_qty']) ?></td>
                                <td><?= htmlspecialchars($target['q_ach_perc']) ?>%</td>
                                <td><?= htmlspecialchars($target['target_value']) ?></td>
                                <td><?= htmlspecialchars($target['ach_value']) ?></td>
                                <td><?= htmlspecialchars($target['v_ach_perc']) ?>%</td>
                                <td><?= htmlspecialchars($target['cateogry']) ?></td>
                             <td>
    <a href="edit_target.php?target_id=<?= htmlspecialchars($target['target_id']) ?>" class="btn btn-sm btn-primary">Edit</a>
    <a href="delete_target.php?target_id=<?= htmlspecialchars($target['target_id']) ?>" class="btn btn-sm btn-danger">Delete</a>
</td>

                            </tr>
                            <?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 -->
		</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>