<?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 id="shopname"></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" />
<style>
    @media print {
    body {
        margin: 0;
        padding: 0;
        font-size: 12px;
    }
    
    .card {
        width: 100%;
        margin: 0 auto;
        box-shadow: none;
        border: none;
    }
    
    .card-body {
        padding: 10px;
    }

    /* Adjust table styles for printing */
    table {
        width: 100%;
        border-collapse: collapse;
    }
    
    table, th, td {
        border: 1px solid black;
        padding: 8px;
        text-align: left;
    }

    /* Adjust other elements as needed */
    .btn {
        display: none; /* Hide the print button on print */
    }
}

    </style>
</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", 
    "payments.php", 
    "reports.php", 
    "purchases.php", 
    "employee.php", 
    "inventory.php"
);

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

$receptionistLinks = array(
    "orders.php", 
    "payments.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" id="ps">
            <div></div>
            <div id="results">
                <!-- Display results here -->
            </div>
        </div>
        <button class="btn btn-rounded btn-success" onclick="printCard()">Print</button>
    </div>
</div>

<script>
    function printCard() {
        // Get the card element to be printed
        const cardToPrint = document.getElementById('ps');

        // Open a new window for printing
        const printWindow = window.open('', '_blank');

        // Write the card content to the new window
        printWindow.document.write('<html><head><title>Print</title>');
        printWindow.document.write('<link rel="stylesheet" type="text/css" href="print.css">'); // Link to print stylesheet
        printWindow.document.write('</head><body>');
        printWindow.document.write(cardToPrint.outerHTML);
        printWindow.document.write('</body></html>');

        // Close the new window after printing
        printWindow.document.close();
        printWindow.print();
        printWindow.close();
    }
</script>

             <div class="row">
              <div class="col-lg-12">
                  <div class="card">
                      <div class="card-body">
                          <h4 class="card-title px-4 mb-3">Emplooyee Salary 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">Cashier</option>
                                                    <option value="Waiter">Waiter</option>
                                                    <option value="Receptionist">Receptionist</option>
                                                    <option>Manager</option>
                                                    <option>CEO</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-address-card-o generate-payslip" data-id="' + employee.employee_id + '" title="Generate Payslip"></i> ' +
    ' <i class="fa fa-trash delete-employee" data-id="' + employee.employee_id + '"></i>' +
'</td>'
+
              '</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'
              });
            }
          });
        }
      });
    });
    });
    $(document).on('click', '.generate-payslip', function () {
    // Get the employee ID from the data-id attribute
    const employeeId = $(this).data('id');

    // Get the name and salary_amount from the corresponding columns
    const name = $(this).closest('tr').find('td:eq(1)').text(); // Assuming name is in the second column (index 1)
    const salaryAmount = $(this).closest('tr').find('td:eq(3)').text(); // Assuming salary_amount is in the fourth column (index 3)

    // Store the data in the form for later use
    $('#employeeIdInput').val(employeeId);
    $('#employeeNameInput').val(name);
    $('#employeeSalaryInput').val(salaryAmount);

    // Call the calculateNetPay function with the necessary data
    calculateNetPay(employeeId, name, salaryAmount);
});

    
  function calculateNetPay(employeeId, name, salaryAmount) {
    // Use the provided parameters instead of re-declaring variables
    const grossPay = parseFloat(salaryAmount);
    const fullname = name;

    // Prepare data to send to server
    const postData = {
        employeeId: employeeId,
        name: fullname,
        grossPay: grossPay
    };

    // Send data to server for calculations
    $.ajax({
        url: 'database/deductions.kts.php', // Your server-side script
        type: 'POST',
        data: postData,
        dataType: 'json',
        success: function (response) {
            // Handle success response
            displayResults(response);
        },
        error: function (xhr, status, error) {
            // Handle error response
            let errorMessage = 'An unexpected error occurred.';
            if (xhr.responseText) {
                try {
                    errorMessage = JSON.parse(xhr.responseText).error;
                } catch (e) {
                    errorMessage = 'An unexpected error occurred.';
                }
            }
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: errorMessage,
            });
        }
    });
}

        function calculateNssfTier2(grossPay) {
            const NssfTieriiRates = [
                { bracket: 0, rate: 0 },
                { bracket: 7000, rate: 60 },
                { bracket: 8000, rate: 120 },
                { bracket: 9000, rate: 180 },
                { bracket: 10000, rate: 240 },
                { bracket: 11000, rate: 300 },
                { bracket: 12000, rate: 360 },
                { bracket: 13000, rate: 420 },
                { bracket: 14000, rate: 480 },
                { bracket: 15000, rate: 540 },
                { bracket: 16000, rate: 600 },
                { bracket: 17000, rate: 660 },
                { bracket: 18000, rate: 720 }
            ];

            let nssfTier2 = 0;

            // Find the applicable rate based on the grossPay
            for (let i = NssfTieriiRates.length - 1; i >= 0; i--) {
                if (grossPay >= NssfTieriiRates[i].bracket) {
                    nssfTier2 = NssfTieriiRates[i].rate;
                    break;
                }
            }

            return nssfTier2;
        }

        function calculateNhif(grossPay) {
            const nhifRates = [
                { bracket: 0, rate: 150 },
                { bracket: 6000, rate: 300 },
                { bracket: 8000, rate: 400 },
                { bracket: 12000, rate: 500 },
                { bracket: 15000, rate: 600 },
                { bracket: 20000, rate: 750 },
                { bracket: 25000, rate: 850 },
                { bracket: 30000, rate: 900 },
                { bracket: 35000, rate: 950 },
                { bracket: 40000, rate: 1000 },
                { bracket: 45000, rate: 1100 },
                { bracket: 50000, rate: 1200 },
                { bracket: 60000, rate: 1300 },
                { bracket: 70000, rate: 1400 },
                { bracket: 80000, rate: 1500 },
                { bracket: 90000, rate: 1600 },
                { bracket: 100000, rate: 1700 }
            ];

            let nhif = 0;

            for (let i = nhifRates.length - 1; i >= 0; i--) {
                if (grossPay >= nhifRates[i].bracket) {
                    nhif = nhifRates[i].rate;
                    break;
                }
            }

            return nhif;
        }

        function calculateHousingLevy(grossPay) {
   // Example Housing Levy rate

    if (grossPay <= 24000) {
        return grossPay * housingLevyRate; // Example Housing Levy rate for the lowest bracket
    } else {
        // Adjust the condition for other income brackets
        // Add more conditions for other income brackets if needed
        return 0;
    }
}
function calculateDeductions(grossPay) {
    const housingLevyRate = 0.015;
    // Constants for NSSF deductions
    const nssfTier1 = 360; // Example NSSF Tier I deduction
    const nssfTier2 = calculateNssfTier2(grossPay);

    // NHIF and Housing Levy deductions
    const nhif = calculateNhif(grossPay);

    const housingLevy = grossPay * housingLevyRate;

    // Define income brackets, rates, and a base relief
    const brackets = [0, 24000, 32333.33, 499999.99, 799999.99];
    const rates = [0.1, 0.25, 0.3, 0.325, 0.35];
    const baseReliefs = [2400 + nhif * 0.15]; // Example base reliefs for each bracket

    // Calculate taxable pay
    let taxablePay = grossPay - nssfTier1 - nssfTier2;

    // Calculate PAYE before relief
    let payeBeforeRelief = 0;

    for (let i = 0; i < brackets.length - 1; i++) {
        if (taxablePay <= 0) {
            break;
        }

        const taxableAmount = Math.min(brackets[i + 1] - brackets[i], taxablePay);
        payeBeforeRelief += taxableAmount * rates[i];
        taxablePay -= taxableAmount;
    }

    // Apply base relief based on the bracket
    const baseRelief = baseReliefs.find((relief, index) => grossPay > brackets[index]);

    // Calculate dynamic relief based on taxable pay
    const dynamicRelief = Math.min(payeBeforeRelief, baseRelief);

    // Apply dynamic relief
    const payeAfterRelief = Math.max(0, payeBeforeRelief - dynamicRelief);

    // Calculate total deductions
    const totalDeductions = nssfTier1 + nssfTier2 + nhif + housingLevy + payeAfterRelief;

    // Calculate net pay
    const netPay = grossPay - totalDeductions;

    return { nssfTier1, nssfTier2, nhif, housingLevy, payeBeforeRelief, dynamicRelief, payeAfterRelief, totalDeductions, netPay };
}
function displayResults(data) {
    // Display results dynamically
    const {
        grossPay,
        nssfTier1,
        nssfTier2,
        nhif,
        housingLevy,
        payeBeforeRelief,
        dynamicRelief,
        payeAfterRelief,
        totalDeductions,
        netPay,
        name,
        deductions // Assuming deductions is an array of objects with name and amount
    } = data;

    // Calculate total deduction amount
    const totalDeductionsAmount = deductions.reduce((total, deduction) => total + deduction.amount, 0);

    // Calculate net pay after deductions
    const netPayAfterDeductions = netPay - totalDeductionsAmount;
    // Ensure grossPay is a number before using toFixed
    const formattedGrossPay = typeof grossPay === 'number' ? grossPay.toFixed(2) : '';

    // Format HTML to display payslip
    const resultsDiv = $('#results');
    resultsDiv.html(`
        <div class="container">
            <div class="row" style="width:100%">
                    <div class="col-md-12">
                        <div class="row">
                            <div class="col-md-4">
                                <img class="img" alt="" src="" />
                            </div>
                            <div class="col-md-8 text-right">
                                <h4 style="color: #F81D2D;"><strong>JasyJoka Apartments</strong></h4>
                                <p>Mombasa</p>
                                <p>P.O Box</p>
                                <p>example@gmail.com</p>
                            </div>
                        </div>
                        <br />
                        <div class="row">
                            <div class="col-md-12 text-center">
                                <h2>Salary Payslip</h2>
                                <h5>04854654101</h5>
                                <h5>${name}</h5>
                            </div>
                        </div>
                        <br />
                        <div>
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th><h5>Description</h5></th>
                                        <th><h5>Amount</h5></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td class="col-md-9">Gross Salary</td>
                                        <td class="col-md-3"><i class="fas fa-check" area-hidden="true"></i><span id="grosssalary">Kshs ${formattedGrossPay}</span></td>
                                    </tr>
                                    <tr>
                                        <td class="col-md-9">NSSF Tier (i)</td>
                                        <td class="col-md-3"><i class="fas fa-check" area-hidden="true"></i> <span id="nssftieri">${nssfTier1.toFixed(2)}</span></td>
                                    </tr>
                                    <tr>
                                        <td class="col-md-9">NSSF Tier (ii)</td>
                                        <td class="col-md-3"><i class="fas fa-check" area-hidden="true"></i> <span id="nssftierii">${nssfTier2.toFixed(2)}</span></td>
                                    </tr>
                                    <tr>
                                        <td class="col-md-9">NHIF</td>
                                        <td class="col-md-3"><i class="fas fa-check" area-hidden="true"></i><span id="nhif">${nhif.toFixed(2)}</span></td>
                                    </tr>
                                    <tr>
                                        <td class="col-md-9">Housing Levy</td>
                                        <td class="col-md-3"><i class="fas fa-check" area-hidden="true"></i><span id="housinglevy">${housingLevy.toFixed(2)}</span></td>
                                    </tr>
                                            ${deductions.map(deduction => `
                                                <tr>
                                                    <td class="col-md-9"><strong>${deduction.name}:</strong></td>
                                                    <td class="col-md-3"><i class="fas fa-check" area-hidden="true"></i><span>${deduction.amount.toFixed(2)}</span></td>
                                                </tr>
                                            `).join('')}
                                    <tr>
                                        <td class="text-right">
                                            <p><strong>PAYE before relief:</strong></p>
                                            <p><strong>Reliefs:</strong></p>
                                            <p><strong>PAYE after relief:</strong></p>
                                            <p><strong>Total Deductions:</strong></p>
                                            <!-- Include deductions dynamically here -->
                                        </td>
                                        <td>
                                            <p><strong><i class="fas fa-check" area-hidden="true"></i> <span id="payebeforerelief">${payeBeforeRelief.toFixed(2)}</span></strong></p>
                                            <p><strong><i class="fas fa-check" area-hidden="true"></i> <span id="reliefs">${dynamicRelief.toFixed(2)}</span></strong></p>
                                            <p><strong><i class="fas fa-check" area-hidden="true"></i> <span id="payeafterrelief">${payeAfterRelief.toFixed(2)}</span></strong></p>
                                            <p><strong><i class="fas fa-check" area-hidden="true"></i> <span id="totaldeductions">${totalDeductions.toFixed(2)}</span></strong></p>
                                            
                                           
                                        </td>
                                    </tr>
                                    <tr style="color: #F81D2D;">
                                        <td class="text-right"><h4><strong>Net Pay:</strong></h4></td>
                                        <td class="text-left"><h4><strong><i class="fas fa-check" area-hidden="true"></i> ${netPayAfterDeductions.toFixed(2)}</strong></h4></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div>
                            <div class="col-md-12">
                                <p id="currentDate"><b>Date :</b></p>
                                <br />
                                <p><b>Signature: </b></p>
                            </div>
                        </div>
                    </div>
            </div>
        </div>
    `);
}


        
</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 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>
    
<script>
    // JavaScript code to fetch data and display it
    function fetchBusinessDetails() {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', './database/fetch_business.kts.php', true);
        xhr.onload = function() {
            if (this.status === 200) {
                var data = JSON.parse(this.responseText);
                
                console.log(data);  // Check if contact2 is present in the response
                
                // Check if no error
                if (!data.error) {
                    // Update the span elements with the fetched data
                    document.getElementById('shopname').innerText = data.shop_name || '';
                    document.getElementById('shopname1').innerText = data.shop_name || '';
                    document.getElementById('location').innerText = data.location || '';
                    document.getElementById('quote').innerText = data.quote || '';
                    document.getElementById('street').innerText = data.street || '';
                    document.getElementById('address').innerText = data.address || '';
                    document.getElementById('pin').innerText = data.pin || '';
                    document.getElementById('contact1').innerText = data.contact1 || '';
                    document.getElementById('contact2').innerText = data.contact2 || ''; // This should populate contact2
                } else {
                    console.error("Error: " + data.error);
                }
            } else {
                console.error("Failed to fetch data");
            }
        };
        xhr.send();
    }

    // Call the function as soon as the DOM is fully loaded
    document.addEventListener('DOMContentLoaded', fetchBusinessDetails);
</script>
 
</body>

</html>