<?php
     session_start();
      include 'database/shikanisha.kts.php';
        if(!($_SESSION['type'] == 'Manager' || $_SESSION['type'] == 'Cashier')){
            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>Jacyjoka</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">
    <link href="./quixlab/plugins/toastr/css/toastr.min.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>
                <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-money">+</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", 
    "expense.php", 
    "employee.php", 
    "inventory.php"
);

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

$receptionistLinks = array(
    "orders.php", 
    "payments.php", 
    "reg-customer.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 "Receptionist":
            $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> 
        <!--**********************************
            Sidebar end
        ***********************************-->

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

            
            <!-- row -->
            <div class="modal fade" id="shopite">
                  <div class="modal-dialog" role="document">
                    <div class="modal-content">
          
             <div class="card">
                 <div class="card-body pb-0 d-flex justify-content-between">
             <form  action="database/expense.kts.php" method="post">
                                   <div class="form-group">
                                            <select class="form-control" name="expense_type" required>
                                                <?php
                                                // Connect to the database
                                              
                                                // Fetch data from the database
                                                $sql = "SELECT * FROM expense_type";
                                                $result = $conn->query($sql);
                                                    if ($result->num_rows > 0) {
                                                        while ($row = $result->fetch_assoc()) {
                                                            echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
                                                        }
                                                    }




                                                // Close the database connection
                                                $conn->close();
                                                ?>
                                            </select>
                                        </div>

                                    <div class="form-group">
                                        <input type="number" class="form-control" name="amount" placeholder="Expense Amount" required/>
                                    </div>
                                    
                                    <button class="btn btn-info" type="submit" name="expense">Submit</button>
                                    &nbsp;
                                  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addExpenseTypeModal">
                                    Add Type
                                  </button>
                                </form>
                              
           </div>
          </div>
             </div>
                      </div></div>
           <div class="container-fluid">
                <div class="row">
               
                    <div class="col-12">
                        <div class="card">
                          <div class="card-body pb-0 d-flex justify-content-between">
                                       
                                        <div>
                                            <h4 class="card-title">Expense Report</h4>
                                           
                                        </div>
                                        
                                    </div>
                          
                            <div class="card-body">
                               
                               
                               <div class="table-responsive">
                                  <table id="bootstrap-data-table-export" class="table table-striped table-bordered zero-configuration">
                                    <thead>
                                      <tr>
                                        <th>Expense Id</th>
                                        <th>Expense Name</th>
                                        <th>Expense Amount</th>
                                        <th>Date</th>
                                        <th>Action</th>
                                      </tr>
                                    </thead>
                                    <tbody></tbody>
                                  </table>
                                </div>
                             </div>
                        </div>
                    </div>
                </div>
                
                
                  <div class="row">
    <div class="col-lg-12 col-sm-12">
        <div class="card">
          <div class="card-body">
        <h4 class="card-title">Expense Detailed Report</h4>
        <!-- Items Report Form -->
        <form id="expenseReportForm">
            <div class="row">
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="start_date">Start Date:</label>
                        <input type="datetime-local" class="form-control" id="start_date" name="start_date" required>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="end_date">End Date:</label>
                        <input type="datetime-local" class="form-control" id="end_date" name="end_date" required>
                    </div>
                </div>
                <div class="col-md-4 d-flex align-items-end">
                    <button type="button" class="btn btn-primary" onclick="generateReport()">Generate Report</button>
                </div>
            </div>
        </form>

        <!-- Items Report Table -->
        <div class="active-member">
            <div class="table-responsive">
                <table id="expenseTable" class="table table-striped table-bordered">
                    <thead>
                        <tr>
                            <th>Expense ID</th>
                            <th>Name</th>
                            <th>Date</th>
                            <th>Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Data will be inserted here by AJAX -->
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="3"></td>
                            <td><b><i>Total Expense: Ksh<span id="totalExpense">0.00</span></i></b></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>
          </div>
                 </div>
          </div>
       </div>

    <!-- Modal -->
          <div class="modal fade" id="addExpenseTypeModal" tabindex="-1" role="dialog" aria-labelledby="addExpenseTypeModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
             <div class="container"></div>
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="addExpenseTypeModalLabel">Add Expense Type</h5>
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                  </button>
                </div>
                <div class="modal-body">
                  <form id="addExpenseTypeForm">
                    <div class="form-group">
                      <label for="name">Name:</label>
                      <input type="text" class="form-control" id="name" name="name" required>
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                  </form>
                </div>
              </div>
            </div>
          </div>

   <!-- Modal -->
            <!-- #/ container -->
        </div>
        <!--**********************************
            Content body end
        ***********************************-->
        
  </div>
        <!--**********************************
            Footer start
        ***********************************-->
        <div class="footer">
            <div class="copyright">
                <p>Copyright &copy; Designed & Developed by <a href="https://themeforest.net/user/quixlab">Quixlab</a> 2018</p>
            </div>
        </div>
        <!--**********************************
            Footer end
        ***********************************-->

    
   
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <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/toastr/js/toastr.min.js"></script>
    <script src="./quixlab/plugins/toastr/js/toastr.init.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>
    <!-- Datatables -->
    <script src="./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="./quixlab/js/expense.js"></script>
    

   
<script>
  // Get the table body element
  const tbody = document.querySelector('#bootstrap-data-table-export tbody');

  // Function to fetch data from the expense table using Ajax
  function fetchExpenses() {
    // Create an XMLHttpRequest object
    const xhr = new XMLHttpRequest();

    // Define the request URL
    const url = 'fetch_expense.php';

    // Open a GET request
    xhr.open('GET', url, true);

    // Set the response type to JSON
    xhr.responseType = 'json';

    // Set the onload callback function
    xhr.onload = function() {
      if (xhr.status === 200) {
        // Clear the table body
        tbody.innerHTML = '';

        // Loop through the response data and append it to the table body
        xhr.response.forEach(function(expense) {
          // Create a new table row element
          const tr = document.createElement('tr');

          // Create the table cells and set their text content
          const tdId = document.createElement('td');
          tdId.textContent = expense.expense_id;
          const tdName = document.createElement('td');
          tdName.textContent = expense.expense_name;
          const tdAmount = document.createElement('td');
          tdAmount.textContent = expense.expense_amount;
          const tdDate = document.createElement('td');
          tdDate.textContent = expense.date_incurred;

          // Create the delete button element
          const deleteButton = document.createElement('button');
          deleteButton.classList.add('btn', 'btn-danger');
          deleteButton.textContent = 'Delete';
          deleteButton.addEventListener('click', function() {
            if (confirm('Are you sure you want to delete this expense?')) {
              // Create an XMLHttpRequest object
              const deleteXhr = new XMLHttpRequest();

              // Define the request URL
              const deleteUrl = 'delete_expense.php?expense_id=' + expense.expense_id;

              // Open a GET request
              deleteXhr.open('GET', deleteUrl, true);

              // Set the onload callback function
              

deleteXhr.onload = function() {
  if (deleteXhr.status === 200) {
    // Remove the table row from the DOM
    tr.remove();
    // Show a success message using toastr
    toastr.success('Expense deleted successfully', '', {  "closeButton": true,
      "debug": false,
      "progressBar": true,
      "preventDuplicates": false,
      "positionClass": "toast-top-right",
      "onclick": null,
      "showDuration": "400",
      "hideDuration": "1000",
      "timeOut": "7000",
      "extendedTimeOut": "1000",
      "showEasing": "swing",
      "hideEasing": "linear",
      "showMethod": "fadeIn",
      "hideMethod": "fadeOut"});
  } else {
    console.error('Delete request failed');
  }
};


              // Send the request
              deleteXhr.send();
            }
          });

          // Create the table cell for the delete button
          const tdDelete = document.createElement('td');
          tdDelete.appendChild(deleteButton);

          // Append the table cells to the table row
          tr.appendChild(tdId);
          tr.appendChild(tdName);
          tr.appendChild(tdAmount);
          tr.appendChild(tdDate);
          tr.appendChild(tdDelete);

          // Append the table row to the table body
          tbody.appendChild(tr);
        });
      } else {
        console.error('Fetch request failed');
      }
    };

    // Send the request
    xhr.send();
  }

  // Call the fetchExpenses function to populate the table initially
  fetchExpenses();
</script>
  <script>
  $(document).ready(function() {
    // Submit form using AJAX
   $('#addExpenseTypeForm').submit(function(e) {
    e.preventDefault();
    $.ajax({
      type: 'POST',
      url: 'database/expense_type.kts.php',
      data: $(this).serialize(),
      success: function(response) {
        // Clear input field
        $('#name').val('');

        // Hide modal and reload page
        $('#addExpenseTypeModal').modal('hide');
        location.reload();

        // Show success message
        toastr.success('Expense type updated Successfully', '', { 
          closeButton: true,
          progressBar: true,
          positionClass: 'toast-top-right',
          timeOut: '3000',
          extendedTimeOut: '1000'
        });
      },
      error: function() {
        // Show error message
        toastr.error('Error: Could not add record', '', { 
          closeButton: true,
          progressBar: true,
          positionClass: 'toast-top-right',
          timeOut: '7000',
          extendedTimeOut: '1000'
        });
      }
    });
  });

  });
</script>


    <!--**********************************
        Scripts
    ***********************************-->

<script>
   $('#storecart').click(function(){
    $('#shopite').modal();
  })    
 </script>
</body>
</html>