<?php
     session_start();
      include 'database/shikanisha.kts.php';
        if(!($_SESSION['type'] == 'Manager' )){
            header("location:logout.php");
}


?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>THE FARM</title>
    <!-- Favicon icon -->
    <link rel="icon" type="./quixlab/image/png" sizes="16x16" href="./quixlab/images/favicon.png">
    <!-- Pignose Calender -->
    <link href="./quixlab/plugins/pg-calendar/css/pignose.calendar.min.css" rel="stylesheet">
    <!-- Chartist -->
    <link rel="stylesheet" href="./quixlab/plugins/chartist/css/chartist.min.css">
    <link rel="stylesheet" href="./quixlab/plugins/chartist-plugin-tooltips/css/chartist-plugin-tooltip.css">
    <!-- Custom Stylesheet -->
    <link href="./quixlab/css/design.css" rel="stylesheet">
    <!-- DataTables with Buttons -->
    <link rel="stylesheet" href="./quixlab/plugins/tables/css/datatable/dataTables.bootstrap4.min.css">
    <link href="./quixlab/plugins/tables/css/datatable/dataTables.bootstrap4.min.css" rel="stylesheet">
    <link href="./quixlab/css/buttons.bootstrap.min.css" rel="stylesheet" />

</head>

<body>

    <!--*******************
        Preloader start
    ********************-->
    <div id="preloader">
        <div class="loader">
            <svg class="circular" viewBox="25 25 50 50">
                <circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="3" stroke-miterlimit="10" />
            </svg>
        </div>
    </div>
    <!--*******************
        Preloader end
    ********************-->

    
    <!--**********************************
        Main wrapper start
    ***********************************-->
    <div id="main-wrapper">

        <!--**********************************
            Nav header start
        ***********************************-->
        <div class="nav-header">
            <div class="brand-logo" style="background-image: url('./quixlab/images/room.png');">
               
            </div>
        </div>
        <!--**********************************
            Nav header end
        ***********************************-->

        <!--**********************************
            Header start
        ***********************************-->
        <div class="header">    
            <div class="header-content clearfix">
                
                <div class="nav-control">
                    <div class="hamburger">
                        <span class="toggle-icon"><i class="icon-menu"></i></span>
                    </div>
                </div>
                <div class="header-left">
                    <div class="input-group icons">
                        <div class="input-group-prepend">
                            <span class="input-group-text bg-transparent border-0 pr-2 pr-sm-3" id="basic-addon1"><i class="mdi mdi-magnify"></i></span>
                        </div>
                        <input type="search" class="form-control" placeholder="Search Dashboard" aria-label="Search Dashboard">
                        <div class="drop-down animated flipInX d-md-none">
                            <form action="#">
                                <input type="text" class="form-control" placeholder="Search">
                            </form>
                        </div>
                    </div>
                </div>
                <div class="header-right">
                    <ul class="clearfix">
                        
                        <li class="icons dropdown d-none d-md-flex"><a href="javascript:void(0)" id="storecart">
                                <i class="fa fa-user">Add Employee</i>
                               
                            </a>
                        </li>
                        
                    </ul>
                </div>
            </div>
        </div>
        <!--**********************************
            Nav header end
        ***********************************-->

        <!--**********************************
            Header start
        ***********************************-->
     <?php


// Define arrays for each user role and the corresponding allowed links
$managerLinks = array(
    "orders.php", 
    "table.php", 
    "payments.php", 
    "reports.php", 
    "purchases.php", 
    "employee.php", 
    "reg-customer.php", 
    "inventory.php"
);

$cashierLinks = array(
    "orders.php", 
    "reg-customer.php", 
    "sales.php"
);

$receptionistLinks = array(
    "orders.php", 
    "reg-customer.php", 
    "payments.php", 
    "sales.php"
);

// Check if user is logged in and their role is set in the session
if(isset($_SESSION['type'])) {
    $role = $_SESSION['type'];
    
    // Assign the corresponding links based on the user role
    switch($role) {
        case "Manager":
            $links = $managerLinks;
            break;
        case "Cashier":
            $links = $cashierLinks;
            break;
        case "Accountant":
            $links = $receptionistLinks;
            break;
        default:
            $links = array();
            break;
    }
} else {
    // Redirect user to login page if they are not logged in
    header("Location: login.php");
    exit();
}

?>

<div class="nk-sidebar">           
    <div class="nk-nav-scroll">
        <ul class="metismenu" id="menu">
            <li class="nav-label">Dashboard</li>
            <li>
                <a class="has-arrow" href="javascript:void()" aria-expanded="false">
                    <i class="icon-speedometer menu-icon"></i><span class="nav-text">Dashboard</span>
                </a>
                <ul aria-expanded="false">
                    <li><a href="index.php">Dashboard</a></li>
                    <!-- <li><a href="./index-2.html">Home 2</a></li> -->
                </ul>
            </li>
            <?php 
               foreach($links as $link) {
    $linkText = ucfirst(str_replace(".php", "", $link)); // remove .php extension and capitalize first letter
    echo '<li><a href="' . $link . '"><i class="icon-menu menu-icon"></i><span class="nav-text">' . $linkText . '</span></a></li>';
}

            ?>
            <li>
                <a href="logout.php" aria-expanded="false">
                    <i class="icon-lock menu-icon"></i><span class="nav-text">LogOut</span>
                </a>
            </li>
        </ul>
    </div>
</div>
        <!--**********************************
            Header end ti-comment-alt
        ***********************************-->

        <!--**********************************
            Sidebar start
        ***********************************-->
    
        <!--**********************************
            Sidebar end
        ***********************************-->

        <!--**********************************
            Content body start
        ***********************************-->
        <div class="content-body">

            <div class="container-fluid mt-3">
               
               
                 
            <div class="row">
  <div class="col-lg-12 col-sm-12">
    <div class="card">
      <div class="card-body">
        <h4 class="card-title">Employee Information</h4>
        <div class="bootstrap-data-table-panel">
          <div class="table-responsive">
            <table id="bootstrap-data-table-export" class="table table-striped table-bordered zero-configuration table-sm">
              <thead>
                <tr>
                  <th>#</th>
                  <th>Full Name</th>
                  <th>Phone Number</th>
                  <th>Salary Amount</th>
                  <th>Username</th>
                  <th>Date</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody id="employeeTableBody">
                <!-- Data will be dynamically loaded here using Ajax -->
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
  
             <div class="row">
              <div class="col-lg-12">
                  <div class="card">
                      <div class="card-body">
                          <h4 class="card-title px-4 mb-3">Emplooyee to Business Transactions</h4>
                          <div class="active-member">
                              <div class="table-responsive">
                                <table class="table table-striped table-bordered zero-configuration table-sm"> 
                                  <thead>
                                      <tr>
                                          <th>Salary ID</th>
                                          <th>Phone Number</th>
                                          <th>Salary</th>
                                          <th>Salary Date</th>
                                          <th>Method</th>
                                          <th>Purpose</th>
                                          <th>Actions</th>
                                      </tr>
                                  </thead>
                                  <tbody id="data-table-body">
                                      <!-- Data fetched from AJAX request will be displayed here -->
                                  </tbody>
                              </table>
                            </div>
                        </div>
                    </div>
                </div>
               </div>
            </div>
                
               <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-body">
                        <h4 class="card-title px-4 mb-3">Employee Salary Status</h4>
                        <div class="active-member">
                            <div class="table-responsive">
                                <table class="table table-striped table-bordered zero-configuration table-sm" id="employeeSalaryTable">
                                    <thead>
                                        <tr>
                                            <th>Employee Name</th>
                                            <th>Phone Number</th>
                                            <th>Salary Amount</th>
                                            <th>Amount Paid</th>
                                            <th>Balance</th>
                                            <th>Status</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody id="employeeTableBody">
                                        <!-- Employee data will be dynamically inserted here -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
                
             
                <!-- Send To Shop Modal -->
                  <div class="modal fade" id="ShopModal">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">

                        <div class="modal-body">
                           <div class="input-group icons">
                                      <div class="input-group-prepend">
                                          <span class="input-group-text bg-transparent border-0 pr-1 pr-sm-2" id="basic-addon1"><i class="mdi mdi-magnify"></i></span>
                                      </div>
                                      <input type="search" class="form-control rounded" placeholder="Search Products" aria-label="Search Dashboard">
                                      <div class="drop-down animated flipInX d-md-none">
                                          <form action="#">
                                              <input type="text" class="form-control" placeholder="Search">
                                          </form>
                                      </div>
                                </div>
                        </div>

                    </div>
                </div>
            </div>
                <!-- End Of Send To Shop Modal -->
                <!-- Start Of Send To shop Items  Modal-->
                <div class="modal fade" id="shopite">
                  <div class="modal-dialog" role="document">
                    <div class="modal-content">
                      <div class="card">
                            <div class="card-body">
                               
                                <p></p>
                                <h4 class="card-title">Employee Registration Details</h4>
                                <p></p>
                                
                                <div></div>
                                <div class="basic-form">
                                    <form id="employee_form">
                                        <div class="form-row">
                                            <div class="form-group col-md-6">
                                                <label>Full Name</label>
                                                <input type="text" class="form-control" placeholder="Full Name" name="fullname" id="fullname" required>
                                            </div>
                                            <div class="form-group col-md-6">
                                                <label>Phone Number</label>
                                                <input type="text" class="form-control" placeholder="Phone Number" name="phone_number" id="phone_number" required>
                                            </div>
                                           </div>
                                           <div class="form-row">
                                            <div class="form-group col-md-6">
                                                <label>Salary Amount</label>
                                                <input type="number"  class="form-control" placeholder="Salary Amount" id="salary" name="salary" required>
                                            </div>
                                            <div class="form-group col-md-6">
                                                <label>Username</label>
                                                <input type="text" class="form-control" placeholder="Username" name="username"  id="username" required>
                                            </div>
                                        </div>
                                        <div class="form-row">
                                            <div class="form-group col-md-6">
                                                <label>Password</label>
                                                <input type="password" id="password" name="password" class="form-control" placeholder="Password" required>
                                            </div>
                                            <div class="form-group col-md-4">
                                                <label>Occupation</label>
                                                <select id="type" class="form-control" name="type" required>
                                                    <option selected="selected">Choose...</option>
                                                    <option value="Cashier">Waiter</option>
                                                    <option>Manager</option>
                                                    <option>Receptionist</option>
                                                </select>
                                            </div>
                                            
                                        </div>
                                        
                                        <button type="submit" class="btn btn-dark">Submit</button>
                                         <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                  </div>
                  
                </div>
                
                <!-- End  of Send to Shop Items Modal -->
                <!-- Add Stock Modal -->
             
               <!-- End Of aAdd Poduct Modal  -->
              
               
                 <!-- Payment Modal -->
                
                <div class="modal fade bd-example-modal-sm-loan-plan " tabindex="-1" role="dialog" aria-hidden="true" id="editzmodal">

                                        <div class="modal-dialog modal-sm">
                                            <div class="modal-content">
                                               <form id="salary_update">
                                                <div class="modal-header">
                                                    <h5 class="modal-title">Update Employee Payment  Details</h5>
                                                    <button type="button" class="close" data-dismiss="modal"><span>&times;</span>
                                                    </button>
                                                </div>
                                                <div class="modal-body">
                                                  <div class="basic-form">
                                                        <div class="basic-form">
                                                          <label>Reference ID</label>
                                                          <input type="text" id="loanid" name="loanid" value="" class="form-control input-rounded" disbled>
                                                        </div>
                                                         <div class="basic-form">
                                                          <label>Amount</label>
                                                          <input type="number" id="pay_amount" name="pay_amount" value="" class="form-control input-rounded">
                                                        </div>
                                                        <div class="basic-form">
                                                          <label>Purpose</label>
                                                          <select class="custom-select browser-default input-rounded" id="purpose" name="purpose">
                                                          <option value="">Select Purpose</option>
                                                          <option value="Short">Short</option>
                                                          <option value="Salary">Salary</option>
                                                          <option value="Advance">Advance</option>

                                                           </select>
                                                        </div> <div class="basic-form">
                                                          <label>Payment Mode</label>
                                                          <select class="custom-select browser-default input-rounded" id="pay_method" name="pay_method" required>
                                                          <option value="" selected disabled>Please select</option>
                                                          <option value="Cash">Cash</option>
                                                          <option value="Mpesa">Mpesa</option>
                                                          <option value="Equity">Equity</option>
                                                          <option value="Hfc">HFC</option>
                                                          <option value="Absa">Absa</option>
                                                          <option value="KCB">KCB</option>
                                                          <option value="Mpesa-2">Mpesa 2</option>

                                                           </select>
                                                        </div>
                                                       
                                                        
                                                    
                                                  </div>
                                                  
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                                                    <button type="submit" class="btn btn-success">Save</button>
                                                </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                
                <!-- end of payment modal -->
   <!-- Modal for Edit -->
    <div class="modal  fade" id="editModal">
        <div class="modal-dialog">
            <div class="modal-content">

                <!-- Modal Header -->
                <div class="modal-header">
                    <h4 class="modal-title">Edit Salary Details</h4>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>

                <!-- Modal Body -->
                <div class="modal-body">
                    <!-- Form to display salary details for editing -->
                    <form id="editForm">
                        <input type="hidden" id="editSalaryId" name="salaryId">
                        <div class="form-group">
                            <label for="editPhoneNumber">Phone Number:</label>
                            <input type="text" class="form-control" id="editPhoneNumber" name="phoneNumber" readonly>
                        </div>
                        <div class="form-group">
                            <label for="editSalary">Salary:</label>
                            <input type="text" class="form-control" id="editSalary" name="salary" required>
                        </div>
                        <div class="form-group">
                            <label for="editSalaryDate">Salary Date:</label>
                            <input type="date" class="form-control" id="editSalaryDate" name="salaryDate" required>
                        </div>
                        <div class="form-group">
                            <label for="editMethod">Method:</label>
                            <input type="text" class="form-control" id="editMethod" name="method" required>
                        </div>
                        <div class="form-group">
                            <label for="editPurpose">Purpose:</label>
                            <input type="text" class="form-control" id="editPurpose" name="purpose" required>
                        </div>
                        <button type="submit" class="btn btn-primary">Save Changes</button>
                    </form>
                </div>

            </div>
        </div>
    </div>
             <!-- Modal for Edit Employee Info -->
    <div class="modal  fade" id="employeeModal">
        <div class="modal-dialog">
            <div class="modal-content">

                <!-- Modal Header -->
                <div class="modal-header">
                    <h4 class="modal-title">Edit Salary Details</h4>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>

                <!-- Modal Body -->
                <div class="modal-body">
                    <!-- Form to display salary details for editing -->
                    <form id="employee_salary">
                        <input type="hidden" id="editEmployeeIds" name="empid">
                       
                        <div class="form-group">
                            <label for="editPhoneNumber">Full Names:</label>
                            <input type="text" class="form-control" id="editNames" name="names" readonly>
                        </div>
                         <div class="form-group">
                            <label for="editPhoneNumber">Phone Number:</label>
                            <input type="text" class="form-control" id="editPhoneNumbers" name="phonenumber" readonly>
                        </div>
                        <div class="form-group">
                            <label for="editMethod">Usernames:</label>
                            <input type="text" class="form-control" id="editUsernames" name="username" readonly>
                        </div>
                        <div class="form-group">
                            <label for="editSalary">Salary:</label>
                            <input type="text" class="form-control" id="editSalaryAmounts" name="salary" required>
                        </div>
                        <div class="form-group">
                            <label for="editSalaryDate">Regitration Date:</label>
                            <input type="date" class="form-control" id="editRegistrartionDates" name="regdate" required>
                        </div>
                        
                        
                        <button type="submit" class="btn btn-primary">Save Changes</button>
                    </form>
                </div>

            </div>
        </div>
    </div>
                 
                   
            </div>
            <!-- #/ container -->
        </div>
        <!--**********************************
            Content body end
        ***********************************-->
        
        
        <!--**********************************
            Footer start
        ***********************************-->
        <div class="footer">
            <div class="copyright">
                <p>Copyright &copy; Designed & Developed by <a href="https://kakashitech.com">Kakashi Tech</a></p>
            </div>
        </div>
        <!--**********************************
            Footer end
        ***********************************-->
    </div>
    <!--**********************************
        Main wrapper end
    ***********************************-->

    <!--**********************************
        Scripts
***********************************-->
     <script src="./quixlab/plugins/common/common.min.js"></script>
    <script src="./quixlab/js/custom.min.js"></script>
    <script src="./quixlab/js/settings.js"></script>
    <script src="./quixlab/js/gleek.js"></script>
    <script src="./quixlab/js/styleSwitcher.js"></script>

    <script src="./quixlab/plugins/tables/js/jquery.dataTables.min.js"></script>
    <script src="./quixlab/plugins/tables/js/datatable/dataTables.bootstrap4.min.js"></script>
    <script src="./quixlab/plugins/tables/js/datatable-init/datatable-basic.min.js"></script>

    <!-- Chartjs -->
    <script src="./quixlab/plugins/chart.js/Chart.bundle.min.js"></script>
    <!-- Circle progress -->
    <script src="./quixlab/plugins/circle-progress/circle-progress.min.js"></script>
    <!-- Datamap -->
    <script src="./quixlab/plugins/d3v3/index.js"></script>
    <script src="./quixlab/plugins/topojson/topojson.min.js"></script>
    <script src="./quixlab/plugins/datamaps/datamaps.world.min.js"></script>
    <!-- Morrisjs -->
    <script src="./quixlab/plugins/raphael/raphael.min.js"></script>
    <script src="./quixlab/plugins/morris/morris.min.js"></script>
    <!-- Pignose Calender -->
    <script src="./quixlab/plugins/moment/moment.min.js"></script>
    <script src="./quixlab/plugins/pg-calendar/js/pignose.calendar.min.js"></script>
    <!-- ChartistJS -->
    <script src="./quixlab/plugins/chartist/js/chartist.min.js"></script>
    <script src="./quixlab/plugins/chartist-plugin-tooltips/js/chartist-plugin-tooltip.min.js"></script>
    <script src="./quixlab/js/dashboard/dashboard-1.js"></script>
    <script src="./quixlab/plugins/chart.js/Chart.bundle.min.js"></script>
    <script src="./quixlab/js/plugins-init/chartjs-init.js"></script>
    <!-- Datatables -->
    <script src="./quixlab/js/dashboard/dashboard-1.js"></script>
    <script src="./quixlab/plugins/tables/js/jquery.dataTables.min.js"></script>
    <script src="./quixlab/plugins/tables/js/datatable/dataTables.bootstrap4.min.js"></script>
    <script src="./quixlab/plugins/tables/js/datatable-init/datatable-basic.min.js"></script>
    
    <script src="./quixlab/js/data-table/dataTables.buttons.min.js"></script>
    <script src="./quixlab/js/data-table/buttons.flash.min.js"></script>
    <script src="./quixlab/js/data-table/jszip.min.js"></script>
    <script src="./quixlab/js/data-table/pdfmake.min.js"></script>
    <script src="./quixlab/js/data-table/vfs_fonts.js"></script>
    <script src="./quixlab/js/data-table/buttons.html5.min.js"></script>
    <script src="./quixlab/js/data-table/buttons.print.min.js"></script>
    <script src="./quixlab/js/data-table/datatables-init.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>

  <script>
 //Add Stock Modal 
 $('#addstock').click(function(){
   $('#basicModal').modal();
 });
//Send stock to Shop  
 $('#sendshop').click(function(){
   $('#ShopModal').modal();
 });
// Items To Send
  $('#storecart').click(function(){
    $('#shopite').modal();
  })    
 </script>
 <script>
  
$(document).ready(function () {
    // Fetch employee data using Ajax
    $.ajax({
        url: 'database/fetch_emp.kts.php', // Replace with the actual file path for fetching data
        type: 'GET',
        dataType: 'json',
        success: function (response) {
            // Handle the response, e.g., update the table
            var tableBody = $('#employeeSalaryTable tbody');
            tableBody.empty();

            if (response.length > 0) {
                $.each(response, function (index, employee) {
                    tableBody.append(
                        '<tr data-phone="' + employee.phone_number + '">' +
                        '<td>' + employee.name + '</td>' +
                        '<td>' + employee.phone_number + '</td>' +
                        '<td>' + employee.salary_amount + '</td>' +
                        '<td>' + employee.amount_paid + '</td>' +
                        '<td>' + employee.balance + '</td>' +
                        '<td>' + employee.status + '</td>' +
                        '<td class="text-center">' +
                        '<button class="btn btn-success btn-sm payBtn" data-toggle="modal" data-target="#editmodal" data-empid="' + employee.phone_number + '">' +
                        '<i class="fa fa-money">&nbsp; Pay</i></button>' +
                        '</td>' +
                        '</tr>'
                    );
                });

                // Pay button click event
            // Pay button click event
$(document).on('click', '.payBtn', function() {
    var empId = $(this).attr('data-empid'); // Use .attr() to get the attribute value

    // Set the employee ID in the modal form
    $('#loanid').val(empId);
    $('#pay_amount').val('');
    $('#purpose').val('');
    $('#pay_method').val('');

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

            } else {
                // Handle case when there is no data
                tableBody.append('<tr><td colspan="7">No employees found</td></tr>');
            }
        },
        error: function (error) {
            console.log(error);
            // Handle errors if needed
        }
    });

    // Edit Employee - Open Edit Modal
    $(document).on('submit', '#salary_update', function (event) {
        event.preventDefault();

        var formData = $(this).serialize();
        var phone_number = $('#editmodal').data('phone');

       $.ajax({
    url: './database/empsalary.kts.php', // PHP script to handle the request
    type: 'POST',
    data: formData,
    dataType: 'json', // Expect JSON response from the server
    success: function(response) {
        // Display the response from the PHP script using SweetAlert
        Swal.fire({
            title: response.success ? 'Success' : 'Error',
            text: response.message,
            icon: response.success ? 'success' : 'error',
            confirmButtonText: 'OK'
        });

        // Clear the form input fields
        $('#salary_update')[0].reset();
    },
    error: function(xhr, status, error) {
        // Handle errors with SweetAlert
        Swal.fire({
            title: 'Error',
            text: 'An error occurred while processing your request.',
            icon: 'error',
            confirmButtonText: 'OK'
        });
        console.log(xhr.responseText);
    }
});

    });
});


</script>
 <script>
  $(document).ready(function() {
    // Fetch employee data using Ajax
   $.ajax({
      url: 'database/fetch_employees.kts.php',
      type: 'GET',
      dataType: 'json',
      success: function(response) {
        // Handle the response, e.g., update the table
        var tableBody = $('#employeeTableBody');
        tableBody.empty();

        if (response.length > 0) {
          $.each(response, function(index, employee) {
            tableBody.append(
              '<tr>' +
              '<td>' + employee.employee_id + '</td>' +
              '<td>' + employee.name + '</td>' +
              '<td>' + employee.phone_number + '</td>' +
              '<td>' + employee.salary_amount + '</td>' +
              '<td>' + employee.username + '</td>' +
              '<td>' + employee.registration_date + '</td>' +
              '<td>' +
              '<i class="fa fa-edit edit-employee" data-id="' + employee.employee_id + '"></i>' +
              '<i class="fa fa-eye view-order-details" data-id="' + employee.employee_id + '"></i>' +
              '<i class="fa fa-trash delete-employee" data-id="' + employee.employee_id + '"></i>' +
              '</td>' +
              '</tr>'
            );
          });
        } else {
          // Handle case when there is no data
          tableBody.append('<tr><td colspan="7">No employees found</td></tr>');
        }
      },
      error: function(error) {
        console.log(error);
        // Handle errors if needed
      }
    });


    // Edit Employee - Open Edit Modal
$(document).on('click', '.edit-employee', function() {
        var employeeId = $(this).data('id');

        // Make an AJAX request to get the employee details
        $.ajax({
            url: 'database/get_employee_details.kts.php', // Replace with the actual file path
            type: 'GET',
            data: { id: employeeId },
            dataType: 'json',
            success: function(response) {
                // Assuming the modal is named 'employeeModal'
                $('#employeeModal').find('#editEmployeeIds').val(response.employee_id);
                $('#employeeModal').find('#editNames').val(response.name);
                $('#employeeModal').find('#editPhoneNumbers').val(response.phone_number);
                $('#employeeModal').find('#editSalaryAmounts').val(response.salary_amount);
                $('#employeeModal').find('#editUsernames').val(response.username);
                $('#employeeModal').find('#editRegistrationDates').val(response.registration_date);

                $('#employeeModal').modal('show');
            },
            error: function(error) {
                console.log(error);
                // Handle errors if needed
            }
        });
    });
       
    // View Employee - Open View Modal
    $(document).on('click', '.view-order-details', function() {
      var employeeId = $(this).data('id');
      $('#viewModal').load('view_employee.php?id=' + employeeId, function() {
        
        $('#viewModal').modal('show');
      });
    });

    // Delete Employee
    $(document).on('click', '.delete-employee', function() {
      var employeeId = $(this).data('id');
      $('.delete-employee').on('click', function() {
      // Get the employee ID from the data-id attribute
      var employee_id = $(this).data('id');
      
      // Show SweetAlert confirmation dialog
      Swal.fire({
        title: 'Are you sure?',
        text: 'You won\'t be able to revert this!',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, delete it!'
      }).then((result) => {
        // If the user clicks on the "Yes" button
        if (result.isConfirmed) {
          // Send AJAX request to delete the employee record
          $.ajax({
            url: 'database/delete_employee.kts.php',
            type: 'POST',
            data: {
              employee_id: employee_id
            },
            success: function(response) {
              // Show success message with SweetAlert
              Swal.fire({
                title: 'Deleted!',
                text: 'Employee has been deleted.',
                icon: 'success'
              }).then(() => {
                // Reload the page to show the updated employee list
                location.reload();
              });
            },
            error: function() {
              // Show error message with SweetAlert
              Swal.fire({
                title: 'Error!',
                text: 'An error occurred while deleting the employee.',
                icon: 'error'
              });
            }
          });
        }
      });
    });
    });
  });
</script>
 
<script>
    $(document).ready(function() {
        // Add event listener to form submit button
        $('#employee_salary').on('submit', function(event) {
            event.preventDefault(); // Prevent default form submission behavior

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

            // Send AJAX request to server
            $.ajax({
                url: './database/empsalaryupdate.kts.php', // PHP script to handle the request
                type: 'POST',
                data: formData,
                dataType: 'json', // Expect JSON response from the server
                success: function(response) {
                    // Display the response from the PHP script using SweetAlert
                    Swal.fire({
                        title: response.success ? 'Success' : 'Error',
                        text: response.message,
                        icon: response.success ? 'success' : 'error',
                        confirmButtonText: 'OK'
                    }).then((result) => {
                        // Hide the modal after the user clicks 'OK'
                        if (result.isConfirmed) {
                            $('#yourModalId').modal('hide');
                            
                            // Reload the page after 3 seconds
                            setTimeout(function() {
                                location.reload();
                            }, 3000);
                        }
                    });

                    // Clear the form input fields
                    $('#employee_salary')[0].reset();
                },
                error: function(xhr, status, error) {
                    // Handle errors with SweetAlert
                    Swal.fire({
                        title: 'Error',
                        text: 'An error occurred while processing your request.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                    console.log(xhr.responseText);
                }
            });
        });
    });
</script>


<script>
		$(document).ready(function() {
			// Add event listener to form submit button
			$('#employee_form').on('submit', function(event) {
				event.preventDefault(); // Prevent default form submission behavior

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

				// Send AJAX request to server
				$.ajax({
					url: './database/employee.kts.php', // PHP script to handle the request
					type: 'POST',
					data: formData,
					success: function(response) {
                        // Display the response from the PHP script
                        

                        // Clear the form input fields
                        $('#employee_form')[0].reset();
                      },
					error: function(xhr, status, error) {
						// Handle errors
						console.log(xhr.responseText);
					}
				});
			});
		});
	</script>

   <script>
  $(document).ready(function() {
    // Handle delete button click
   
  });
</script>

   <script>
 $(document).ready(function () {
    // Fetch and display data on page load
    fetchData();

    // Handle form submission for editing salary details
    $('#editForm').submit(function (event) {
        event.preventDefault();

        // Get form data
        var formData = {
            salaryId: $('#editSalaryId').val(),
            salary: $('#editSalary').val(),
            salaryDate: $('#editSalaryDate').val(),
            method: $('#editMethod').val(),
            purpose: $('#editPurpose').val()
        };

        // Send AJAX request to update salary details
        $.ajax({
            type: 'POST',
            url: './database/update_salary.kts.php', // Replace with the actual path to your PHP script for updating
            data: formData,
            dataType: 'json',
            success: function (response) {
                if (response.success) {
                    alert('Salary details updated successfully!');
                    // Close the modal
                    $('#editModal').modal('hide');
                    // Fetch and display updated data
                    fetchData();
                } else {
                    alert('Error updating salary details: ' + response.message);
                }
            },
            error: function (xhr, status, error) {
                console.error(xhr.responseText);
                alert('AJAX Error: ' + error);
            }
        });
    });

    // Function to fetch and display data from the server
    function fetchData() {
        // Send AJAX request to fetch data
        $.ajax({
            type: 'GET',
            url: './database/fetch_salary.kts.php', // Replace with the actual path to your PHP script for fetching
            dataType: 'json',
            success: function (response) {
                if (response.success) {
                    // Update the table with the fetched data
                    $('#data-table-body').html(response.tableData);

                    // Attach click event to edit buttons
                    $('.edit-button').click(function () {
                        var salaryId = $(this).data('salaryid');
                        openEditModal(salaryId);
                    });

                    // Attach click event to delete buttons
                    $('.delete-button').click(function () {
                        var salaryId = $(this).data('salaryid');
                        deleteRecord(salaryId);
                    });
                } else {
                    alert('Error fetching data: ' + response.message);
                }
            },
            error: function (xhr, status, error) {
                console.error(xhr.responseText);
                alert('AJAX Error: ' + error);
            }
        });
    }

    // Function to open the edit modal with salary details
    function openEditModal(salaryId) {
        // Fetch salary details for the specified ID
        $.ajax({
            type: 'GET',
            url: './database/get_salary.kts.php', // Replace with the actual path to your PHP script for fetching salary details
            data: { salaryId: salaryId },
            dataType: 'json',
            success: function (response) {
                if (response.success) {
                    // Populate the edit modal with salary details
                    $('#editSalaryId').val(response.salaryDetails.salary_id);
                    $('#editPhoneNumber').val(response.salaryDetails.phone_number);
                    $('#editSalary').val(response.salaryDetails.salary);
                    $('#editSalaryDate').val(response.salaryDetails.salary_date);
                    $('#editMethod').val(response.salaryDetails.method);
                    $('#editPurpose').val(response.salaryDetails.purpose);

                    // Show the edit modal
                    $('#editModal').modal('show');
                } else {
                    alert('Error fetching salary details: ' + response.message);
                }
            },
            error: function (xhr, status, error) {
                console.error(xhr.responseText);
                alert('AJAX Error: ' + error);
            }
        });
    }

    // Function to delete a record
 function deleteRecord(salaryId) {
    // Show SweetAlert confirmation dialog
    Swal.fire({
        title: 'Are you sure?',
        text: 'You won\'t be able to revert this!',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        // If the user clicks "Yes"
        if (result.isConfirmed) {
            // Send AJAX request to delete record
            $.ajax({
                type: 'POST',
                url: 'database/delete_salary.kts.php', // Replace with the actual path to your PHP script for deleting
                data: { salaryId: salaryId },
                dataType: 'json',
                success: function (response) {
                    if (response.success) {
                        // Display SweetAlert for success
                        Swal.fire({
                            title: 'Success',
                            text: 'Record deleted successfully!',
                            icon: 'success',
                            confirmButtonText: 'OK'
                        });

                        // Fetch and display updated data
                        fetchData();
                    } else {
                        // Display SweetAlert for error
                        Swal.fire({
                            title: 'Error',
                            text: 'Error deleting record: ' + response.message,
                            icon: 'error',
                            confirmButtonText: 'OK'
                        });
                    }
                },
                error: function (xhr, status, error) {
                    console.error(xhr.responseText);
                    // Display SweetAlert for AJAX error
                    Swal.fire({
                        title: 'Error',
                        text: 'AJAX Error: ' + error,
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                }
            });
        }
    });
}


});

   </script>
 
</body>

</html>