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


?>
<?php
date_default_timezone_set('Africa/Nairobi');
$today = date('Y-m-d');
$dayNumber = date('j');
$monthName = date('F');

// Database connection

// Query to fetch total expenses for today
$query = "SELECT SUM(expense_amount) AS totalExpenses FROM expenses WHERE DATE(date_incurred) = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param('s', $today);
$stmt->execute();
$result = $stmt->get_result();
$totalExpenses = $result->fetch_assoc()['totalExpenses'] ?? 0;
$stmt->close();
?>

<!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">
    <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">
                    <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">           
    <?php require 'navbar.php'; ?>
</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 id="create-expense">
    <div class="form-group">
        <select class="form-control" name="expense_type" required>
            <?php
            // 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>";
                }
            }
            ?>
        </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">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-lg-12 col-md-6 mb-4">
                <div class="card gradient-card">
                    <div class="card-body text-center">
                        <h2>Expenses</h2>
                        <h4><?= $dayNumber . ' ' . $monthName; ?></h4>
                        <h1 class="display-4">Ksh <?= number_format($totalExpenses, 2); ?></h1>
                    </div>
                </div>
            </div>
        </div>
                <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="expenses" class="table table-striped table-bordered">
                                    <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" id="generateReportBtn">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 Name</th>
            <th>Expense Amount</th>
        </tr>
    </thead>
    <tbody id="expenseTableBody">
    </tbody>
    
</table>
            </div>
        </div>
    </div>
          </div>
                 </div>
          </div>
          
       </div>
       <div class="container mt-5">
        <h2>Expense Types</h2>
        <table id="expensetypeTable" class="table table-striped table-bordered" style="width:100%">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Category</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <!-- Data will be populated here by JavaScript -->
    </tbody>
</table>
    </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>
  <div class="modal fade" id="edittypeModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editModalLabel">Edit 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="editForm">
                        <input type="hidden" id="expensetypeId" name="idtype">
                        <div class="form-group">
                            <label for="expenseName">Name</label>
                            <input type="text" class="form-control" id="expensetypeName" name="nametype" required>
                        </div>
                        <div class="form-group">
                            <label for="expenseCategory">Category</label>
                            <input type="text" class="form-control" id="expensetypeCategory" name="categorytype" required>
                        </div>
                        <button type="submit" class="btn btn-primary">Save changes</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="./js/jquery-3.6.4.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/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="./js/bootstrap.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="./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="./js/sweetalert2@10.js"></script>

    <script src="./quixlab/js/expense.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>


    

   
<script>
  // Get the table body element
 
    </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>
    <script>
        $(document).ready(function() {
            // Fetch data using AJAX
          var userType = '<?php echo $_SESSION['type'] ?? ''; ?>'; // Pass the session type from PHP

    $.ajax({
        url: 'database/fetch_expenses.kts.php',
        type: 'GET',
        dataType: 'json', // Expecting JSON response
        success: function(data) {
            if (data && data.length > 0) {
                var rows = '';
                $.each(data, function(index, expense) {
                    rows += '<tr data-expense-id="' + expense.expense_id + '">';
                    rows += '<td data:name="expense_id">' + expense.expense_id + '</td>';
                    rows += '<td data:name="expense_name">' + expense.expense_name + '</td>';
                    rows += '<td data:name="expense_amount">' + expense.expense_amount + '</td>';
                    rows += '<td data:name="date_incurred">' + expense.date_incurred + '</td>';

                    // Check if the user is authorized to see the delete button
                    if (userType === 'Manager' || userType === 'CEO' || userType === 'Accounts') {
                        rows += '<td><button class="btn btn-danger delete-expense" data-expense-id="' + expense.expense_id + '">Delete</button></td>';
                    } else {
                        rows += '<td>Not authorized</td>'; // Display message if not authorized
                    }

                    rows += '</tr>';
                });
                $('#expenses tbody').html(rows); // Update the table body
                $('#expenses').DataTable(); // Initialize DataTable
            } else {
                $('#expenses tbody').html('<tr><td colspan="5">No expenses found</td></tr>');
            }
        },
        error: function(xhr, status, error) {
            console.error('Error fetching expenses:', error);
        }
    });

            // Delete expense
            $('#expenses').on('click', '.delete-expense', function() {
                var expenseId = $(this).data('expense-id');
                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 (result.isConfirmed) {
                        $.ajax({
                            url: './database/delete-expense.kts.php',
                            type: 'POST',
                            data: { expense_id: expenseId },
                            success: function(response) {
                                try {
                                    var data = JSON.parse(response);
                                    if (data.status === 'success') {
                                        $('#expenses tbody tr[data-expense-id="' + expenseId + '"]').remove();
                                        Swal.fire('Deleted!', 'The expense has been deleted.', 'success');
                                    } else {
                                        Swal.fire('Error!', data.message || 'An error occurred.', 'error');
                                    }
                                } catch (error) {
                                    Swal.fire('Error!', 'An error occurred while processing the response.', 'error');
                                }
                            },
                            error: function(xhr, status, error) {
                                Swal.fire('Error!', 'AJAX error: ' + error, 'error');
                            }
                        });
                    }
                });
            });
        });
    </script>
<script>
   $(document).ready(function() {
    $('#create-expense').submit(function(e) {
        e.preventDefault(); // Prevent default form submission
        
        var formData = $(this).serialize(); // Serialize form data
        
        $.ajax({
            type: "POST",
            url: "database/submit_expense.kts.php",
            data: formData,
            success: function(response) {
                var data = JSON.parse(response); // Parse JSON response
                if (data.status === 'success') {
                    // Reset the form
                    $('#create-expense')[0].reset();
                    // Display a success message using SweetAlert
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: data.message
                    }).then(function() {
                        // Reload the current page after the user clicks "OK"
                        location.reload();
                    });
                } else {
                    // Display an error message using SweetAlert
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: data.message
                    });
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX Error:', error);
            }
        });
    });
});
    </script>
<script>
    $(document).ready(function() {
        // Initialize DataTable with default settings (with export buttons)
        $(document).on('click', '#generateReportBtn', function() {
            // Get the values of the start and end dates
            var startDate = $('#start_date').val();
            var endDate = $('#end_date').val();  

            // Check if both dates are selected
            if (startDate && endDate) {
                // Perform the AJAX POST request
                $.ajax({
                    url: './database/process_expense_report.kts.php', // Your server-side script
                    type: 'POST',
                    data: {
                        start_date: startDate,   // Send start date
                        end_date: endDate        // Send end date
                    },
                    success: function(response) {
                        var json = JSON.parse(response); // Parse the JSON response

                        // Check if the response is successful and contains the 'expenses' key
                        if (json.status === "success" && json.expenses) {
                            var totalAmount = 0;
                            json.expenses.forEach(function(item) {
                                totalAmount += parseFloat(item.total_amount);
                            });

                            // Initialize DataTable
                            $('#expenseTable').DataTable({
                                data: json.expenses, // Pass the data to populate the table
                                destroy: true, // Destroy any existing table instance before reinitializing
                                columns: [
                                    { "data": "expense_name" },  // Expense Name column
                                    { 
                                        "data": "total_amount",   // Expense Amount column
                                        "render": function(data, type, row) {
                                            return parseFloat(data).toFixed(2);  // Format as a decimal number
                                        }
                                    }
                                ],
                                dom: 'Bfrtip',  // Enable export buttons
                                buttons: [
                                    {
                                        extend: 'copy',
                                        title: function() {
                                            return 'NGEMU TIMBER AND Hardware\nExpense Report Between ' + startDate + ' and ' + endDate;
                                        }
                                    },
                                    {
                                        extend: 'csv',
                                        title: function() {
                                            return 'NGEMU TIMBER AND Hardware\nExpense Report Between ' + startDate + ' and ' + endDate;
                                        }
                                    },
                                    {
                                        extend: 'excel',
                                        title: function() {
                                            return 'NGEMU TIMBER AND Hardware\nExpense Report Between ' + startDate + ' and ' + endDate;
                                        }
                                    },
                                    {
                                        extend: 'pdf',
                                        title: function() {
                                            return 'NGEMU TIMBER AND Hardware\nExpense Report Between ' + startDate + ' and ' + endDate;
                                        },
                                        customize: function(doc) {
                                            doc.content.push({
                                                text: 'Total Expense: ' + totalAmount.toFixed(2),
                                                alignment: 'right',
                                                margin: [0, 10, 0, 0]
                                            });
                                        }
                                    },
                                    {
                                        extend: 'print',
                                        title: function() {
                                            return 'NGEMU TIMBER AND Hardware\nExpense Report Between ' + startDate + ' and ' + endDate;
                                        },
                                        customize: function(win) {
                                            $(win.document.body).append(
                                                '<div style="text-align:right;margin-top:20px;"><strong>Total Expense: ' + totalAmount.toFixed(2) + '</strong></div>'
                                            );
                                        }
                                    }
                                ],
                                drawCallback: function(settings) {
                                    $('#totalExpenseAmount').text(totalAmount.toFixed(2));
                                    $('#expenseTableBody').append(
                                        '<tr><td colspan="1" style="text-align: right;"><strong>Total</strong></td>' +
                                        '<td><strong>' + totalAmount.toFixed(2) + '</strong></td></tr>'
                                    );
                                }
                            });
                        } else {
                            alert("No expenses found for the selected date range.");
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error("Error fetching data:", error);
                    }
                });
            } else {
                alert("Please select both start and end dates.");
            }
        });
    });
</script>



    <script>
    $(document).ready(function () {
        // Function to fetch and display data
     function fetchExpenses() {
    $.ajax({
        url: './database/fetch_expensetype.kts.php',
        method: 'GET',
        dataType: 'json',
        success: function (data) {
            let rows = '';
            data.forEach(expense => {
                rows += `
                    <tr>
                        <td>${expense.id}</td>
                        <td>${expense.name}</td>
                        <td>${expense.category || "N/A"}</td>
                        <td>
                            <button class="btn btn-warning btn-sm edittype-btn" data-id="${expense.id}">Edit</button>
                            <button class="btn btn-danger btn-sm delete-btn" data-id="${expense.id}">Delete</button>
                        </td>
                    </tr>
                `;
            });
            $('#expensetypeTable tbody').html(rows);

            // Initialize DataTable with export buttons
            $('#expensetypeTable').DataTable({
                dom: 'Bfrtip',
                buttons: [
                    'copy', 'excel', 'pdf', 'print'
                ]
            });
        },
        error: function () {
            swal("Error!", "Failed to fetch expenses.", "error");
        }
    });
}

        // Call fetchExpenses on page load
        fetchExpenses();

        // Edit button click handler
        $(document).on('click', '.edittype-btn', function () {
            const expenseId = $(this).data('id');
            $.ajax({
                url: './database/fetchexpense_type.kts.php',
                method: 'GET',
                data: { id: expenseId },
              dataType: 'json',
        success: function (response) {
            if (response.success) {
                $('#expensetypeId').val(response.data.id);
                $('#expensetypeName').val(response.data.name);
                $('#expensetypeCategory').val(response.data.category || ""); // Handle potential null category
                $('#edittypeModal').modal('show');
            } else {
                swal("Error!", response.message || "Expense not found.", "error");
            }
        },
                error: function () {
                    swal("Error!", "Failed to fetch expense details.", "error");
                }
            });
        });

        // Edit form submission
        $('#editForm').on('submit', function (e) {
            e.preventDefault();
            $.ajax({
                url: './database/update_expensetype.kts.php',
                method: 'POST',
                data: $(this).serialize(),
                dataType: 'json', // Expecting a JSON response
                success: function (response) {
                    $('#editModal').modal('hide');
                    fetchExpenses();
                    if (response.success) {
                        swal("Success!", response.message, "success");
                    } else {
                        swal("Error!", response.message, "error");
                    }
                },
                error: function () {
                    swal("Error!", "An error occurred while updating the expense.", "error");
                }
            });
        });

        // Delete button click handler
        $(document).on('click', '.delete-btn', function () {
            const expenseId = $(this).data('id');
            swal({
                title: "Are you sure?",
                text: "Once deleted, you will not be able to recover this expense!",
                icon: "warning",
                buttons: true,
                dangerMode: true,
            }).then((willDelete) => {
                if (willDelete) {
                    $.ajax({
                        url: './database/delete_expensetype.kts.php',
                        method: 'POST',
                        data: { id: expenseId },
                        dataType: 'json', // Expecting a JSON response
                        success: function (response) {
                            fetchExpenses();
                            if (response.success) {
                                swal("Deleted!", response.message, "success");
                            } else {
                                swal("Error!", response.message, "error");
                            }
                        },
                        error: function () {
                            swal("Error!", "An error occurred while deleting the expense.", "error");
                        }
                    });
                } else {
                    swal("Your expense is safe!");
                }
            });
        });
    });
</script>

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

<script>
   $('#storecart').click(function(){
    $('#shopite').modal();
  })    
 </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>