<?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 KRA Templates";
include("includes/head.php");

// Fetch PMS Templates Data
$stmt = $conn->prepare("SELECT id, kra_name, measure_of_success, weightage, created_at FROM PMS_Template");
$stmt->execute();
$pmsTemplates = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

	<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>KRA Template</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="#add_kra_template">
            <i class="fa fa-plus-circle me-2" aria-hidden="true"></i>Add KRA
        </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>KRA Name</th>
            <th>Measure of Success</th>
            <th>Weightage</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <?php 
        $displayIndex = 1;
        foreach ($pmsTemplates as $template) { 
        ?>
        <tr>
            <td><?= $displayIndex ?></td>
            <td><?= htmlspecialchars($template['kra_name']) ?></td>
            <td><?= htmlspecialchars($template['measure_of_success']) ?></td>
            <td><?= htmlspecialchars($template['weightage']) ?></td>
            <td>
                <!-- Edit and Delete buttons -->
                <button 
                    class="btn btn-sm btn-primary edit-kra-template-btn" 
                    data-id="<?= $template['id'] ?>" 
                    data-kra-name="<?= htmlspecialchars($template['kra_name']) ?>" 
                    data-measure-of-success="<?= htmlspecialchars($template['measure_of_success']) ?>" 
                    data-weightage="<?= htmlspecialchars($template['weightage']) ?>">
                    Edit
                </button>
                      <a href="javascript:void(0);" 
       class="btn btn-sm btn-danger delete-package-btn" 
       data-bs-toggle="modal" 
       data-bs-target="#delete_kra_template" 
       data-id="<?= $template['id'] ?>">
        <i class="far fa-trash-alt me-2"></i>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 -->

<!-- Add KRA Template Modal -->
<div class="modal custom-modal modal-lg fade" id="add_kra_template" 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 KRA Template</h4>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="add_kra_template_form" method="post">
                <div class="modal-body">
                    <div class="input-block mb-3">
                        <label for="kra_name">KRA Name</label>
                        <input name="kra_name" type="text" class="form-control" id="kra_name" placeholder="Enter KRA Name" required>
                    </div>
                    <div class="input-block mb-3">
                        <label for="measure_of_success">Measure of Success</label>
                        <textarea name="measure_of_success" class="form-control" id="measure_of_success" placeholder="Enter Measure of Success" required></textarea>
                    </div>
                    <div class="input-block mb-3">
                        <label for="weightage">Weightage</label>
                        <input name="weightage" type="number" class="form-control" id="weightage" placeholder="Enter Weightage" required step="0.01" min="0" max="100">
                    </div>
                </div>
                <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">Add KRA</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit KRA Template Modal -->
<div class="modal custom-modal modal-lg fade" id="edit_kra_template" 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 KRA Template</h4>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="edit_kra_template_form" method="post">
                <div class="modal-body">
                    <input type="hidden" name="id" id="edit_kra_id">
                    <div class="input-block mb-3">
                        <label for="edit_kra_name">KRA Name</label>
                        <input name="kra_name" type="text" class="form-control" id="edit_kra_name" required>
                    </div>
                    <div class="input-block mb-3">
                        <label for="edit_measure_of_success">Measure of Success</label>
                        <textarea name="measure_of_success" class="form-control" id="edit_measure_of_success" required></textarea>
                    </div>
                    <div class="input-block mb-3">
                        <label for="edit_weightage">Weightage</label>
                        <input name="weightage" type="number" class="form-control" id="edit_weightage" required step="0.01" min="0" max="100">
                    </div>
                </div>
                <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">Update KRA</button>
                </div>
            </form>
        </div>
    </div>
</div>


<div class="modal custom-modal fade" id="delete_kra_template" role="dialog">
   <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Delete KRA Template</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 KRA template?</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 () {
    // Add KRA Template form submission
    $('#add_kra_template_form').on('submit', function (e) {
        e.preventDefault();

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

        // Send AJAX request
        $.ajax({
            type: 'POST',
            url: 'insert_kra_template.php', // PHP handler for adding KRA template
            data: formData,
            dataType: 'json',
            success: function (response) {
                if (response.status === 'success') {
                    toastr.success(response.message);
                    $('#add_kra_template').modal('hide');
                    $('#add_kra_template_form')[0].reset();
                    // Reload or refresh table data
                } else {
                    toastr.error(response.message);
                }
            },
            error: function () {
                toastr.error('An error occurred. Please try again later.');
            }
        });
    });

    // Edit KRA Template form submission
    $('#edit_kra_template_form').on('submit', function (e) {
        e.preventDefault();

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

        // Send AJAX request
        $.ajax({
            type: 'POST',
            url: 'update_kra_template.php', // PHP handler for updating KRA template
            data: formData,
            dataType: 'json',
            success: function (response) {
                if (response.status === 'success') {
                    toastr.success(response.message);
                    $('#edit_kra_template').modal('hide');
                    // Reload or refresh table data
                } else {
                    toastr.error(response.message);
                }
            },
            error: function () {
                toastr.error('An error occurred. Please try again later.');
            }
        });
    });

    // Open Edit KRA Template Modal
    $(document).on('click', '.edit-kra-template-btn', function () {
        var id = $(this).data('id');
        var kraName = $(this).data('kra-name');
        var measureOfSuccess = $(this).data('measure-of-success');
        var weightage = $(this).data('weightage');

        // Populate the modal fields
        $('#edit_kra_id').val(id);
        $('#edit_kra_name').val(kraName);
        $('#edit_measure_of_success').val(measureOfSuccess);
        $('#edit_weightage').val(weightage);

        // Show the modal
        $('#edit_kra_template').modal('show');
    });
    
    
$(document).on('click', '.delete-package-btn', function () {
    // Get the KRA ID from the clicked button
    var kraId = $(this).data('id');
    console.log('Delete Button KRA ID:', kraId); // Debug log

    // Check if kraId is undefined
    if (!kraId) {
        console.error('KRA ID is not found. Check the HTML structure.');
        return;
    }

    // Set the KRA ID to the confirm delete button in the modal
    $('#confirmDelete').data('id', kraId);
});

// Delete KRA Template
$('#confirmDelete').click(function(e) {
    // Retrieve the KRA ID from the button
    var kraId = $(this).data('id');
    console.log('Confirm Delete KRA ID:', kraId); // Debug log

    // Check if kraId is undefined
    if (!kraId) {
        toastr.error('Unable to identify the KRA template. Please try again.');
        return;
    }

    $.ajax({
        url: 'delete_kra_template.php', // PHP file for handling the delete request
        type: 'POST',
        data: { id: kraId },
        dataType: 'json',
        success: function(response) {
            console.log('response', response);
            if (response.status == 'success') {
                toastr.success(response.message);
                $('#delete_kra_template').modal('hide'); // Hide the modal
                window.location.reload(); // Reload the page to reflect the changes
            } else {
                toastr.error(response.message);
            }
        },
        error: function() {
            toastr.error('An error occurred while deleting the KRA template.');
        }
    });
});

});






</script>
</html>