<?php
include("includes/session.php");
$employee_code = $_SESSION['employee_id'];
include 'includes/db.php';

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

// Get the employee code from the request
$employeeCode = $_GET['employee_code'] ?? null;

if (!$employeeCode) {
    die('Error: Employee code is missing.');
}

// Fetch employee details from the Employees table
$sqlEmployee = "SELECT * FROM Employees WHERE employee_code = ?";
$stmtEmployee = $conn->prepare($sqlEmployee);
$stmtEmployee->execute([$employeeCode]);
$employee = $stmtEmployee->fetch(PDO::FETCH_ASSOC);

if (!$employee) {
    die('Error: Employee not found.');
}

// Fetch category details from the Category table
$sqlCategory = "SELECT * FROM category";
$stmtCategory = $conn->prepare($sqlCategory);
$stmtCategory->execute();
$categoryList = $stmtCategory->fetchAll(PDO::FETCH_ASSOC);

// Fetch assigned targets for the employee from the EmployeeTarget table
$sqlAssignedTargets = "
    SELECT et.*, c.category_name
    FROM EmployeeTarget et
    JOIN category c ON et.category_id = c.category_id
    WHERE et.employee_code = ?
";
$stmtAssignedTargets = $conn->prepare($sqlAssignedTargets);
$stmtAssignedTargets->execute([$employeeCode]);
$assignedTargets = $stmtAssignedTargets->fetchAll(PDO::FETCH_ASSOC);

$title = "Assign Category and Target to Employee";
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>Assign Category & Target</h5>
							<div class="list-btn">
					<ul class="filter-list">
    <!-- Add Category -->
    <li>
        <a class="btn btn-primary" href="javascript:void(0);" data-bs-toggle="modal" data-bs-target="#assign_category_target">
            <i class="fa fa-plus-circle me-2" aria-hidden="true"></i>Assign Category & Target
        </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>
        <tr>
            <th>#</th>
            <th>Category</th>
            <th>Target</th>
            <th>Month</th>
            <th>Assigned At</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($assignedTargets as $index => $target): ?>
            <tr>
                <td><?= $index + 1 ?></td>
                <td><?= htmlspecialchars($target['category_name']) ?></td>
                <td><?= htmlspecialchars($target['target']) ?></td>
              <?php
$months = [
    1 => 'January', 2 => 'February', 3 => 'March', 4 => 'April', 5 => 'May', 
    6 => 'June', 7 => 'July', 8 => 'August', 9 => 'September', 10 => 'October', 
    11 => 'November', 12 => 'December'
];

// Assuming $target['month'] contains the month number
$monthName = isset($months[$target['month']]) ? $months[$target['month']] : 'Unknown';
?>

<td><?= htmlspecialchars($monthName) ?></td>
                <td><?= htmlspecialchars($target['assigned_at']) ?></td>
                <td>
                    <button 
                        class="btn btn-sm btn-primary edit-assigned-target-btn" 
                        data-id="<?= $target['id'] ?>" 
                        data-category-id="<?= $target['category_id'] ?>" 
                        data-target="<?= $target['target'] ?>" 
                        data-month="<?= $target['month'] ?>" 
                        data-bs-toggle="modal" 
                        data-bs-target="#edit_category_target">
                        Edit
                    </button>
                    
                    <a href="javascript:void(0);" 
       class="btn btn-sm btn-danger delete-assigned-target-btn" 
       data-bs-toggle="modal" 
       data-bs-target="#delete_category_target_modal" 
       data-id="<?= $target['id'] ?>">
        <i class="far fa-trash-alt me-2"></i>Delete
    </a>
                </td>
            </tr>
        <?php endforeach; ?>
    </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 -->

<!-- Assign Category & Target Modal -->
<div class="modal custom-modal modal-lg fade" id="assign_category_target" 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">Assign Category and Target</h4>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="assign_category_target_form" method="post" action="assign_category_target.php">
                <div class="modal-body">
                    <input type="hidden" name="employee_code" value="<?= htmlspecialchars($employeeCode) ?>">
                    <input type="hidden" name="assign_by" value="<?= htmlspecialchars($employee_code) ?>">
                    
                    <div class="input-block mb-3">
                        <label for="category_id">Category</label>
                        <select name="category_id" id="category_id" class="form-control" required>
                            <option value="">-- Select Category --</option>
                            <?php foreach ($categoryList as $category): ?>
                                <option value="<?= $category['category_id'] ?>">
                                    <?= htmlspecialchars($category['category_name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="input-block mb-3">
                        <label for="target">Target</label>
                        <input type="number" name="target" id="target" class="form-control" placeholder="Enter Target" required step="0.01" min="0">
                    </div>

                    <div class="input-block mb-3">
                        <label for="month">Month</label>
                        <select name="month" class="form-control" id="month" required>
                            <option value="">-- Select Month --</option>
                            <?php
                            $months = [
                                'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'
                            ];
                            foreach ($months as $index => $month): ?>
                                <option value="<?= $index + 1 ?>"><?= $month ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                </div> <!-- End of modal-body -->
                <div class="modal-footer">
                    <button type="button" class="btn btn-back cancel-btn me-2" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Assign</button>
                </div>
            </form>
        </div>
    </div>
</div>






<!-- Edit Assigned Target Modal -->
<div class="modal custom-modal modal-lg fade" id="edit_category_target" 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 Assigned Target</h4>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="edit_assigned_target_form" method="post" action="edit_assigned_target.php">
                <div class="modal-body">
                    <input type="hidden" name="employee_target_id" id="edit_employee_target_id">
                    <div class="input-block mb-3">
                        <label for="edit_category_id">Category</label>
                        <select name="category_id" class="form-control" id="edit_category_id" required>
                            <option value="">-- Select Category --</option>
                            <?php 
                            foreach ($categoryList as $category): ?>
                                <option value="<?= $category['category_id'] ?>">
                                    <?= htmlspecialchars($category['category_name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="input-block mb-3">
                        <label for="edit_target">Target</label>
                        <input name="target" type="number" class="form-control" id="edit_category_target_feild" placeholder="Enter target" required>
                    </div>
                               <div class="input-block mb-3">
    <label for="edit_month">Month</label>
    <select name="month" class="form-control" id="edit-month" required>
        <option value="">-- Select Month --</option>
        <?php
        $months = [
            'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'
        ];
        $selectedMonth = $target['month']; // Assuming $target['month'] contains the month number
        foreach ($months as $index => $month):
            // Check if the current month matches the selected month
            $selected = ($index + 1 == $selectedMonth) ? 'selected' : '';
        ?>
            <option value="<?= $index + 1 ?>" <?= $selected ?>><?= $month ?></option>
        <?php endforeach; ?>
    </select>
</div>

                    
                    
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update</button>
                </div>
            </form>
        </div>
    </div>
</div>



<div class="modal custom-modal fade" id="delete_category_target_modal" role="dialog">
   <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Delete Category Target</h4>
                <button type="button" class="close" data-bs-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete this Category Target?</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" id="confirmDelete" class="btn btn-danger">Delete</button>
            </div>
        </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>
$(document).ready(function () {
    // Handle form submission for assigning category and target
    $('#assign_category_target_form').on('submit', function (e) {
        e.preventDefault();

        // Serialize the form data
        var formData = $(this).serialize();

        // Send AJAX request
        $.ajax({
            type: 'POST',
            url: 'insert_category_target.php', // PHP handler for assigning category and target
            data: formData,
            dataType: 'json',
            success: function (response) {
                if (response.status === 'success') {
                    toastr.success(response.message);
                    $('#assign_category_target').modal('hide');
                    $('#assign_category_target_form')[0].reset();
                    window.location.reload();
                    // Optionally refresh or reload the related data table
                } else {
                    toastr.error(response.message);
                }
            },
            error: function () {
                toastr.error('An error occurred. Please try again later.');
            }
        });
    });
    
    // Open Edit Assigned Target Modal
$(document).on('click', '.edit-assigned-target-btn', function () {
    var targetId = $(this).data('id');
    var categoryId = $(this).data('category-id');
    var targetValue = $(this).data('target');
    var monthValue = $(this).data('month');

    // Populate the fields in the edit form
    $('#edit_employee_target_id').val(targetId);
    $('#edit_category_id').val(categoryId);
    $('#edit_category_target_feild').val(targetValue);
    $('#edit_month').val(monthValue);

    // Show the modal
    $('#edit_category_target').modal('show');
});

// Handle Edit Form Submission
$('#edit_assigned_target_form').on('submit', function (e) {
    e.preventDefault();

    // Serialize the form data
    var formData = $(this).serialize();

    // Send AJAX request to update the target
    $.ajax({
        type: 'POST',
        url: 'update_category_target.php', // PHP handler for updating the assigned target
        data: formData,
        dataType: 'json',
        success: function (response) {
            if (response.status === 'success') {
                toastr.success(response.message);
                $('#edit_category_target').modal('hide');
                $('#edit_assigned_target_form')[0].reset();
                window.location.reload(); // Refresh the page to reflect changes
            } else {
                toastr.error(response.message);
            }
        },
        error: function () {
            toastr.error('An error occurred. Please try again.');
        }
    });
});


    // Open Assign Category Target Modal
    $(document).on('click', '.assign-category-btn', function () {
        var employeeCode = $(this).data('employee-code');

        // Populate the employee_code field in the modal
        $('#assign_category_target_form input[name="employee_code"]').val(employeeCode);

        // Show the modal
        $('#assign_category_target').modal('show');
    });

    // Delete Assigned Target
    $(document).on('click', '.delete-assigned-target-btn', function () {
        var targetId = $(this).data('id');
console.log('targetId', targetId);
        if (!targetId) {
            toastr.error('Invalid Target ID.');
            return;
        }

        // Set the target ID to the confirm delete button
        $('#confirmDelete').data('id', targetId);
        $('#delete_category_target_modal').modal('show');
    });

    $('#confirmDelete').click(function () {
        var targetId = $(this).data('id');

        if (!targetId) {
            toastr.error('Unable to identify the assigned target. Please try again.');
            return;
        }

        $.ajax({
            url: 'delete_category_target.php',
            type: 'POST',
            data: { id: targetId },
            dataType: 'json',
            success: function (response) {
                if (response.status === 'success') {
                    toastr.success(response.message);
                    $('#delete_category_target_modal').modal('hide');
                    window.location.reload(); // Reload the page
                } else {
                    toastr.error(response.message);
                }
            },
            error: function () {
                toastr.error('An error occurred while deleting the assigned target.');
            }
        });
    });
});







</script>
</html>