<?php
     session_start();
      include 'database/shikanisha.kts.php';
        if(!($_SESSION['type'] == 'Manager' || $_SESSION['type'] == 'Cashier'  || $_SESSION['type'] == 'CEO')){
            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" />
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.3/css/all.css">
    <link rel="stylesheet" href="./quixlab/plugins/sweetalert2/dist/sweetalert2.min.css">
    <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" >
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.2.2/css/buttons.dataTables.min.css">


    

    
<style>
    /* Custom CSS for the dashboard */
    .nav-tabs {
        border-bottom: 2px solid #dee2e6;
    }

    .nav-tabs .nav-link {
        border: none;
        color: #495057;
        font-weight: 500;
        padding: 12px 20px;
        transition: all 0.3s;
    }

    .nav-tabs .nav-link:hover {
        border: none;
        color: #007bff;
    }

    .nav-tabs .nav-link.active {
        color: #007bff;
        background-color: transparent;
        border: none;
        border-bottom: 3px solid #007bff;
    }

    .tab-content {
        padding: 20px 0;
    }

    .card {
        border-radius: 10px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        margin-bottom: 20px;
        transition: transform 0.3s;
    }

    .card:hover {
        transform: translateY(-5px);
    }

    .gradient-1 {
        background: linear-gradient(to right, #ff7e5f, #feb47b);
    }

    .gradient-2 {
        background: linear-gradient(to right, #4776e6, #8e54e9);
    }

    .gradient-5 {
        background: linear-gradient(to right, #f857a6, #ff5858);
    }

    .gradient-7 {
        background: linear-gradient(to right, #4e54c8, #8f94fb);
    }

    .gradient-12 {
        background: linear-gradient(to right, #11998e, #38ef7d);
    }

    .table-responsive {
        overflow-x: auto;
    }

    /* Force all tables to use full width */
    table {
        width: 100% !important;
    }

    @media (max-width: 768px) {
        .nav-tabs .nav-link {
            padding: 10px 15px;
            font-size: 14px;
        }

        .card-body {
            padding: 15px;
        }
    }
</style>
<style>
    #saleskTable tfoot td {
        font-weight: bold;
        background-color: #f8f9fa !important;
    }
    #grandTotalSales, #grandTotalProfit {
        color: #28a745;
    }
    .dataTables_scrollBody {
        max-height: none !important;
    }
</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" style="background-image: url('./quixlab/images/room.png');">
        </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>
        </div>
        <!--**********************************
            Nav header end
        ***********************************-->

        <!--**********************************
            Header start
        ***********************************-->
   
<div class="nk-sidebar">           
     <?php require 'navbar.php'; ?>
</div>


        <!--**********************************
            Header end ti-comment-alt
        ***********************************-->

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

        <!--**********************************
            Content body start
        ***********************************-->
        <div class="content-body">
        <div class="container-fluid mt-3">
    <!-- Tab Navigation -->
    <ul class="nav nav-tabs" id="dashboardTabs" role="tablist">
        <li class="nav-item">
            <a class="nav-link active" id="summary-tab" data-toggle="tab" href="#summary" role="tab" aria-controls="summary" aria-selected="true">Summary</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="reports-tab" data-toggle="tab" href="#reports" role="tab" aria-controls="reports" aria-selected="false">Reports</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="transactions-tab" data-toggle="tab" href="#transactions" role="tab" aria-controls="transactions" aria-selected="false">Transactions</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="analytics-tab" data-toggle="tab" href="#analytics" role="tab" aria-controls="analytics" aria-selected="false">Analytics</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="sales-report-tab" data-toggle="tab" href="#generator" role="tab" aria-controls="analytics" aria-selected="false">Sales Generator</a>
        </li>
    </ul>

    <!-- Tab Content -->
    <div class="tab-content" id="dashboardTabsContent">
        <!-- Summary Tab -->
        <div class="tab-pane fade show active" id="summary" role="tabpanel" aria-labelledby="summary-tab">
           <div class="row mt-3">
    <!-- Summary Cards -->
    <div class="col-md-4 col-sm-6 mb-3">
        <div class="card gradient-1">
            <div class="card-body">
                <h3 class="card-title text-white">Total Sales</h3>
                <div class="d-inline-block">
                    <h2 class="text-white" id="total-sales">0</h2>
                    <p class="text-white mb-0">Tot Amount</p>
                </div>
                <span class="float-right display-5 opacity-5"><i class="fa fa-money"></i></span>
            </div>
        </div>
    </div>
    
    <div class="col-md-4 col-sm-6 mb-3">
        <div class="card gradient-2">
            <div class="card-body">
                <h3 class="card-title text-white">Paybill Number</h3>
                <div class="d-inline-block">
                    <h2 class="text-white" id="till">0</h2>
                    <p class="text-white mb-0">Total Deposited</p>
                </div>
                <span class="float-right display-5 opacity-5"><i class="fa fa-money"></i></span>
            </div>  
        </div>
    </div>
    
    <div class="col-md-4 col-sm-6 mb-3">
        <div class="card gradient-12">
            <div class="card-body">
                <h3 class="card-title text-white">Cash</h3>
                <div class="d-inline-block">
                    <h2 class="text-white" id="cash">0</h2>
                    <p class="text-white mb-0">Amount Paid</p>
                </div>
                <span class="float-right display-5 opacity-5"><i class="fa fa-money"></i></span>
            </div>
        </div>
    </div>
    
    <div class="col-md-4 col-sm-6 mb-3">
        <div class="card gradient-5">
            <div class="card-body">
                <h3 class="card-title text-white">Debt</h3>
                <div class="d-inline-block">
                    <h2 class="text-white" id="debt">0</h2>
                    <p class="text-white mb-0">Pending Amount</p>
                </div>
                <span class="float-right display-5 opacity-5"><i class="fa fa-money"></i></span>
            </div>
        </div>
    </div>
    
    <div class="col-md-4 col-sm-6 mb-3">
        <div class="card gradient-7">
            <div class="card-body">
                <h3 class="card-title text-white">Merchant</h3>
                <div class="d-inline-block">
                    <h2 class="text-white" id="merchant">0</h2>
                    <p class="text-white mb-0">Amount Paid</p>
                </div>
                <span class="float-right display-5 opacity-5"><i class="fa fa-money"></i></span>
            </div>
        </div>
    </div>
    
    <div class="col-md-4 col-sm-6 mb-3">
        <div class="card gradient-1">
            <div class="card-body">
                <h3 class="card-title text-white">Inhouse Payments</h3>
                <div class="d-inline-block">
                    <h2 class="text-white" id="inhouse">0</h2>
                    <p class="text-white mb-0">Tot Amount</p>
                </div>
                <span class="float-right display-5 opacity-5"><i class="fa fa-money"></i></span>
            </div>
        </div>
    </div>
</div>


            <!-- Daily Waiter Report -->
            <div class="row mt-3">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body">
                            <h4 class="card-title">Daily Waiter Report</h4>
                            <div class="table-responsive">
                                <table class="table table-striped table-bordered zero-configuration table-sm">
                                    <thead>
                                        <tr>
                                            <th>Seller_Name</th>
                                            <th>Total_Amount</th>
                                            <th>Cash_at_Hand</th>
                                            <th>Debt</th>
                                        </tr>
                                    </thead>
                                    <tbody id="sales-data">
                                        <!-- Data will be appended here by JavaScript -->
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <th></th>
                                            <th>Total Amt</th>
                                            <th></th>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Reports Tab -->
        <div class="tab-pane fade" id="reports" role="tabpanel" aria-labelledby="reports-tab">
            <div class="row mt-3">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body">
                            <h4 class="card-title">Indivindual Detailed Sales Report</h4>
                            <div class="basic-form">
                               <form id="waiterreports">
                                    <div class="form-row align-items-center">
                                        <div class="col-auto">
                                            <label class="sr-only">Seller Name</label>
                                            <input type="text" name="clients_names" class="form-control mb-2" placeholder="Search Cashier" onkeyup="searchClients(this.value)">
                                            <div id="clientsDropdown"></div>
                                        </div>
                                        <div class="col-auto">
                                            <input type="datetime-local" name="start" class="form-control mb-2" placeholder="Start Date and Time">
                                        </div>
                                        <div class="col-auto">
                                            <input type="datetime-local" name="end" class="form-control mb-2" placeholder="End Date and Time">
                                        </div>
                                        <div class="col-auto">
                                            <button type="submit" class="btn btn-dark mb-2">Generate Member Sales Report</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row mt-3">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body">  
                          <h4 class="card-title">Sales Detailed Report</h4>
                          <form id="salesitemreport">
                              <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="submit" class="btn btn-primary">Generate Report</button>
                                  </div>
                              </div>
                          </form>
                          
                         <div class="active-member mt-3">
    <div class="table-responsive">
        <table id="saleskTable" class="table table-striped table-bordered">
            <thead>
                <tr>
                    <th>Product Name</th>
                    <th>Category</th>
                    <th>Buying Price</th>
                    <th>Selling Price</th>
                    <th>Quantity</th>
                    <th>Subtotal</th>
                    <th>Profit</th>
                </tr>
            </thead>
            <tbody>
                <!-- Data will be inserted here -->
            </tbody>
            <tfoot>
                <tr class="bg-light">
                    <td colspan="5" class="text-right"><strong>Grand Totals:</strong></td>
                    <td id="grandTotalSales"><strong>0.00</strong></td>
                    <td id="grandTotalProfit"><strong>0.00</strong></td>
                </tr>
            </tfoot>
        </table>
    </div>
</div>

                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row mt-3">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body">
                            <h4 class="card-title">Member Sales Status</h4>
                            <div class="table-responsive">
                                <table id="member-sales-status" class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>Seller Name</th>
                                            <th>Total Sales</th>
                                            <th>Paid Amount</th>
                                            <th>Debt</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- Data will be populated by DataTables AJAX -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Transactions Tab -->
        <div class="tab-pane fade" id="transactions" role="tabpanel" aria-labelledby="transactions-tab">
            <div class="row mt-3">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body">
                            <h4 class="card-title">Transactions</h4>
                            <div class="table-responsive">
                                <table id="transactionsTable" class="table table-striped table-bordered">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Seller Name</th>
                                            <th>Total</th>
                                            <th>Paid Amount</th>
                                            <th>Status</th>
                                            <th>Date</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- Data will be inserted here by JavaScript -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row mt-3">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body">
                            <h4 class="card-title">Filtered Transaction Report</h4>
                            <div class="basic-form">
                                <form id="transactionreports">
                                    <div class="form-row align-items-center">
                                        <div class="col-auto">
                                            <input type="datetime-local" name="startz" class="form-control mb-2" placeholder="Start Date and Time">
                                        </div>
                                        <div class="col-auto">
                                            <input type="datetime-local" name="endz" class="form-control mb-2" placeholder="End Date and Time">
                                        </div>
                                        <div class="col-auto">
                                            <button type="button" class="btn btn-dark mb-2" onclick="generateTransactionReport()">Generate Transaction Report</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                            
                            <div class="table-responsive mt-3">
                                <table class="table table-striped table-bordered zero-configuration table-sm" id="transaction-reportdata">
                                    <thead>
                                        <tr>
                                            <th>Payment Method</th>
                                            <th>Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- Data fetched from AJAX request will be displayed here -->
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <td>Total</td>
                                            <td id="filtereddt-total"></td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Analytics Tab -->
        <div class="tab-pane fade" id="analytics" role="tabpanel" aria-labelledby="analytics-tab">
            <div class="row mt-3">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body">
                            <h4 class="card-title">Weekly Monetary Analysis</h4>
                            <select id="weekSelect" class="form-control mb-3">
                                <!-- Options will be populated by JavaScript -->
                            </select>
                            <canvas id="barChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row mt-3">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body">
                            <h4 class="card-title">Monthly Analysis</h4>
                            <div class="form-group">
                                <label for="yearSelect">Select Year:</label>
                                <select class="form-control" id="yearSelect" onchange="filterData()">
                                    <!-- Options will be populated dynamically using PHP -->
                                </select>
                            </div>
                            <canvas id="barChart2"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row mt-3">
                <div class="col-lg-6">
                    <div class="card">
                        <div class="card-body">
                            <h4 class="card-title">Daily Report</h4>
                            <div class="table-responsive">
                                <table class="table table-striped table-bordered zero-configuration table-sm">
                                    <thead>
                                        <tr>
                                            <th>Payment Method</th>
                                            <th>Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody id="report-data">
                                        <!-- Data fetched from AJAX request will be displayed here -->
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <td>Total</td>
                                            <td id="daily-total"></td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-lg-6">
                    <div class="card">
                        <div class="card-body">
                            <h4 class="card-title">Weekly Report</h4>
                            <div class="table-responsive">
                                <table class="table table-striped table-bordered zero-configuration table-sm">
                                    <thead>
                                        <tr>
                                            <th>Transaction Method</th>
                                            <th>Transaction Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody id="weekely-data">
                                        <!-- Data fetched from AJAX request will be displayed here -->
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <td></td>
                                            <td id="weekly-total"></td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row mt-3">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body">
                            <h4 class="card-title">Monthly Sales Report</h4>
                            <div class="table-responsive">
                                <table class="table table-striped table-bordered zero-configuration table-sm">
                                    <thead>
                                        <tr>
                                            <th>Payment Method</th>
                                            <th>Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody id="monthly-data">
                                        <!-- Data fetched from AJAX request will be displayed here -->
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <td>Total</td>
                                            <td id="monthly-total"></td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        
        <div class="tab-pane fade" id="generator" role="tabpanel">
    <div class="container mt-4">
        <h3>Beverage Sales Generator</h3>
        
        <div id="alertDiv"></div>
        
        <div class="card">
            <div class="card-body">
                <form id="generateSalesForm">
                    <input type="hidden" id="targetValue" value="0">
                    <div class="form-group">
                        <p>This will generate random beverage sales totaling 18% of current beverage sales.</p>
                        <p>Current 18% target: <span id="targetAmount">$0.00</span></p>
                    </div>
                    <div class="d-flex gap-2">
                        <button type="submit" id="generateButton" class="btn btn-primary">
                            Generate Beverage Sales
                        </button>
                        <button id="regenerateButton" class="btn btn-secondary d-none">
                            Regenerate
                        </button>
                    </div>
                </form>
            </div>
        </div>
        
        <div id="resultsSection" class="mt-4 d-none">
            <h4>Generated Sales</h4>
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Product</th>
                            <th>Quantity</th>
                            <th>Price</th>
                            <th>Subtotal</th>
                            <th>Transaction ID</th>
                        </tr>
                    </thead>
                    <tbody id="generatedSalesBody"></tbody>
                    <tfoot id="generatedSalesFooter"></tfoot>
                </table>
            </div>
        </div>
    </div>
</div>

</div>

                             <!-- Add Stock Modal -->
               <div class="modal fade" id="viewOrderDetailsModal">
                  <div class="modal-dialog" role="document">
                       <form id="deletesale">
                        <div class="modal-content">
                          <div class="modal-header">
                            <h5 class="modal-title" id="viewOrderDetailsModalLabel">Transaction Details</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                              <span aria-hidden="true">&times;</span>
                            </button>
                          </div>
                          <div class="modal-body">
                            <div class="row">
                              <div class="col-md-12">
                                   <div class="table-responsive">
                                <table class="table table-bordered">
                                  <thead>
                                    <tr>
                                      <th>Name</th>
                                      <th>Price</th>
                                      <th>Quantity</th>
                                      <th>Subtotal</th>
                                     
                                     
                                    </tr>
                                  </thead>
                                  <tbody id="orderDetailsTableBody">

                                  </tbody>
                                  <tfoot id="ordertotals">

                                  </tfoot>
                                </table>
                                </div>
                              </div>
                            </div>
                          </div>
                                <div class="modal-footer">
                                  <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                  <button type="submit" class="btn btn-danger" >Delete Sale</button>
                                </div>
                        </div>
                        </form>
                      </div>
                    </div>
               <!-- End Of aAdd Poduct Modal  -->
                   <!-- Add Stock Modal -->
     
                   
<!-- Bootstrap Modal Placeholder -->
<div class="modal fade" id="viewClientSalesModal" tabindex="-1" role="dialog" aria-labelledby="viewClientSalesModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <!-- Modal Header -->
            <div class="modal-header">
                <h5 class="modal-title" id="viewClientSalesModalLabel">Sales Details</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <!-- Modal Body -->
            <div class="modal-body">
                <!-- Table will be populated with AJAX response -->
                <div class="table-responsive">
                    <table class="table table-striped table-bordered" id="salesDetailsTable">
                        <thead>
                            <tr>
                                <th>Product Name</th>
                                <th>Total Products</th>
                                <th>Total Sales Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- Data will be inserted here by AJAX -->
                        </tbody>
                         <tfoot>
                            <!-- Footer row with totals will be inserted here -->
                        </tfoot>
                    </table>
                </div>
            </div>
            <!-- Modal Footer -->
            <div class="modal-footer">
                <!-- Export Buttons -->
                <button class="btn btn-primary buttons-csv">CSV</button>
                <button class="btn btn-primary buttons-excel">Excel</button>
                <!-- Close Button -->
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
                   <!-- End Of aAdd Poduct Modal  -->
                   <!-- End Of aAdd Poduct Modal  -->
                   <!-- Bootstrap Modal for Viewing Order Details -->
<div class="modal fade" id="orderDetailsModal" tabindex="-1" role="dialog" aria-labelledby="orderDetailsModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="orderDetailsModalLabel">Order Details</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
       
       <!-- Transaction Receipts Section -->
<h6>Transaction Receipts</h6>
 <div class="table-responsive">
<table class="table" id="transactionReceiptsTable">
  <thead>
    <tr>
      <th>Trans ID</th>
      <th>Seller Name</th>
      <th>Total</th>
      <th>Amount Received</th>
      <th>Phone Number</th>
      <th>Seller Date</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
    <!-- Transaction receipts data will be loaded here -->
  </tbody>
</table>

        <!-- Payments Section -->
        <h6>Payments</h6>
        <table class="table" id="paymentsTable">
          <thead>
            <tr>
              <th>Payment ID</th>
              <th>Trans ID</th>
              <th>Payment Method</th>
              <th>Amount</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <!-- Payments data will be loaded here -->
          </tbody>
        </table>

        <!-- Sales Items Section -->
        <h6>Sales Items</h6>
        <table class="table" id="salesItemsTable">
          <thead>
            <tr>
              <th>Sale ID</th>
              <th>Trans ID</th>
              <th>Product ID</th>
              <th>Product Name</th>
              <th>Quantity</th>
              <th>Selling Price</th>
              <th>Subtotal</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <!-- Sales items data will be loaded here -->
          </tbody>
        </table>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

                   <!-- End Of aAdd Poduct Modal  -->
               <div class="modal fade " id="editSaleModal" tabindex="-1" role="dialog" aria-labelledby="editSaleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="editSaleModalLabel">Edit Sale Item</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="editSaleForm">
          <input type="hidden" id="originalSaleId" name="originalSaleId">
          <input type="hidden" id="originalQuantity" name="originalQuantity">
          <input type="hidden" id="originalSubtotal" name="originalSubtotal">
          <div class="form-group">
            <label for="editQuantity">Quantity</label>
            <input type="number" class="form-control" id="editQuantity" name="quantity" onchange="updateSubtotal()">
          </div>
          <div class="form-group">
            <label for="editSellingPrice">Selling Price</label>
            <input type="text" class="form-control" id="editSellingPrice" name="sellingPrice" readonly>
          </div>
          <div class="form-group">
            <label for="editSubtotal">Subtotal</label>
            <input type="text" class="form-control" id="editSubtotal" name="subtotal" readonly>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
            <button type="submit" class="btn btn-primary">Update</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>                  
                     <!-- oomsale Modal -->
                     <div class="modal fade bd-example-modal-sm-loan-plan " tabindex="-1" role="dialog" aria-hidden="true" id="editRoomSaleModal">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editRoomSaleModalLabel">Edit Room Sale</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="editRoomSaleForm">
    <div class="row">
        <div class="col-md-6">
            <div class="form-group">
                <label for="rsid">Room Sale ID:</label>
                <input type="text" class="form-control" id="rsid" name="rsid" readonly>
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <label for="transId">Transaction ID:</label>
                <input type="text" class="form-control" id="transId" name="transId" readonly>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-6">
            <div class="form-group">
                <label for="roomId">Room ID:</label>
                <input type="text" class="form-control" id="roomId" name="roomId" readonly>
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <label for="roomName">Room Name:</label>
                <input type="text" class="form-control" id="roomName" name="roomName" readonly>
            </div>
        </div>
    </div>
    <div class="row">
    <div class="col-md-6">
        <div class="form-group">
            <label for="nod">Number of Days:</label>
            <input type="number" class="form-control" id="nod" name="nod" min="1" value="1">
        </div>
    </div>
    <div class="col-md-6">
        <div class="form-group">
            <label for="roomPrice">Room Price:</label>
            <input type="text" class="form-control" id="roomPrice" name="roomPrice">
        </div>
    </div>
</div>
    <div class="row">
        <div class="col-md-12">
            <div class="form-group">
                <label for="subtotal">Subtotal:</label>
                <input type="text" class="form-control" id="subtotal" name="subtotal" readonly>
            </div>
        </div>
    </div>
    <button type="submit" class="btn btn-primary">Save Changes</button>
</form>

            </div>
        </div>
    </div>
</div>

                     <!-- oomsale Modal -->
                     <!-- Payment Modal -->
                
                 <div class="modal fade bd-example-modal-sm-loan-plan " tabindex="-1" role="dialog" aria-hidden="true" id="editmodal">
                                        <div class="modal-dialog modal-sm">
                                            <div class="modal-content">
                                               <form id="payment_update">
                                                <div class="modal-header">
                                                    <h5 class="modal-title">Update Payment Details</h5>
                                                    <button type="button" class="close" data-dismiss="modal"><span>&times;</span>
                                                    </button>
                                                </div> <div class="modal-header">
                                                     <button type="button" id="doublePaymentBtn" class="btn btn-primary">Double Payment</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">
                                                        </div>
                                                         <div class="basic-form">
                                                          <label>Payment Amount</label>
                                                          <input type="number" min="0" id="payamount" name="payamount" value="" class="form-control input-rounded">
                                                        </div>
                                                        <div class="basic-form">
                                                          <label>Payment Mode</label>
                                                          <select class="custom-select browser-default input-rounded" id="paymethod" name="paymethod" required>
                                                          <option value="">Please select</option>
                                                          <option value="cash">Cash</option>
                                                          <option value="till">Till</option>
                                                          <option value="merchant"> Merchant</option>
                                                          <option value="inhouse"> Inhouse Payment</option>
                                                        </select>
                                                        <div class="double-payment-section" style="display:none">
                                                        <div class="basic-form">
                                                          <label>Payment Amount 2</label>
                                                          <input type="number" min="0" id="payamount2" name="payamount2" value="" class="form-control input-rounded">
                                                        </div>
                                                        <div class="basic-form">
                                                          <label>Payment Mode 2</label>
                                                          <select class="custom-select browser-default input-rounded" id="paymethod2" name="paymethod2" >
                                                          <option value="">Please select</option>
                                                          <option value="cash">Cash</option>
                                                          <option value="till">Till</option>
                                                          <option value="merchant"> Merchant</option>
                                                           <option value="inhouse"> Inhouse Payment</option>      
                                                        </select>
                                                          </div>
                                                        </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>
                                                
                                            </div>
                                                   </form>
                                        </div>
                                    </div>
                
                <!-- end of payment modal -->
                
                <!-- Edit Sale Item Modal -->
                
                
                <!-- Edit Room Sale Modal -->
 

 <!-- Edit Sale Item Modal -->
                 
            </div>
            <!-- #/ container -->
     
        <!--**********************************
            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>
           </div>
        <!--**********************************
            Footer end
        ***********************************-->
  
    <!--**********************************
        Main wrapper end
    ***********************************-->

    <!--**********************************
        Scripts
***********************************-->
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script src="./quixlab/plugins/common/common.min.js"></script>
    <script src="./quixlab/plugins/sweetalert2/dist/sweetalert2.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>

    <!-- 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="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.66/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.66/vfs_fonts.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 src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.2.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.2.2/js/buttons.html5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.2.2/js/buttons.print.min.js"></script>

   
<script>
    $(document).ready(function() {
        $('#empTable').DataTable({
            dom: 'Bfrtip',
            buttons: [
                {
                    extend: 'csv',
                    exportOptions: {
                        columns: [0, 1, 2] // include columns 0, 1, and 2 in the CSV export
                    }
                },
                {
                    extend: 'excel',
                    exportOptions: {
                        columns: [0, 1, 2] // include columns 0, 1, and 2 in the Excel export
                    }
                }
            ]
        });
    });
</script>

<Script>
      
$(document).ready(function() {
    $('#member-sales-status').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": "database/fetch_member_sales.kts.php",
        "columns": [
            { "data": "seller_name" },
            { "data": "total_sales" },
            { "data": "amount_collected" },
            { "data": "debt" },
            { "data": "status" }
        ],
        "dom": 'Bfrtip',
        "buttons": [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ]
    });
});
      
</Script>

<script>
	$(document).ready(function() {
		// Add event listener to form submit button
		$('#deletesale').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/saledelete.kts.php', // PHP script to handle the request
				type: 'POST',
				data: formData,
				success: function(response) {
                    // Display the response from the PHP script
                    alert(response);

                    // Clear the form input fields
                    $('#deletesale')[0].reset();

                    // Reload the current page
                    location.reload();
                },
				error: function(xhr, status, error) {
					// Handle errors
					console.log(xhr.responseText);
				}
			});
		});
	});
</script>

	
	
	<script>
   function searchClients(keyword) {
    // Make an AJAX request to search for clients by name
    $.ajax({
        url: 'database/search_employees.kts.php',
        method: 'POST',
        data: { keyword: keyword },
        success: function(response) {
            // Show the search results in a dropdown
            $('#clientsDropdown').html(response);
            $('#clientsDropdown').show();
        },
        error: function(xhr, status, error) {
            console.error(xhr);
        }
    });
}

// Listen for changes to the client name input
$('input[name="clients_names"]').on('input', function() {
    var keyword = $(this).val();
    if (keyword.length > 0) {
        // Search for clients
        searchClients(keyword);
    } else {
        // Hide the search results dropdown
        $('#clientsDropdown').hide();
    }
});

// Listen for clicks on a search result
$(document).on('click', '.client-result', function() {
    // Get the client ID, name, and phone number
    var clientName = $(this).data('name');
    
    // Update the client name and phone number inputs and hide the search results dropdown
    $('input[name="clients_names"]').val(clientName);
    $('#clientsDropdown').hide();
});

    </script>
  
    
   <script>
  function  viewOrderDet(receiptId) {
  // Make an AJAX request to get order details for the selected receipt ID
  $.ajax({
    url: './database/getsalesinfo.kts.php',
    method: 'POST',
    data: {receipt_id: receiptId},
    dataType: 'json',
    success: function(response) {
      // Update the table body with order details
      var tableBody = $('#orderDetailsTableBody');
      tableBody.empty();

      var totalSubtotal = 0.00;

      for (var i = 0; i < response.length; i++) {
        var item = response[i];
        totalSubtotal += parseFloat(item.subtotal);
        tableBody.append('<tr><td>' + item.product_name + '</td><td>' + item.selling_price + '</td><td>' + item.quantity + '</td><td>' + item.subtotal + '</td></tr>');
      }

      tableBody.append('<tr><td colspan="3"><input type="hidden" name="receipt_id" id="receipt_id" value="'+receiptId+'"></td><td></td></tr>');
      tableBody.append('<tr><td colspan="3"><strong>Total:</strong></td><td>' + totalSubtotal + '</td></tr>');

      // Show the modal
      $('#viewOrderDetailsModal').modal('show');
    },
    error: function(xhr, status, error) {
      alert('Error: ' + error);
    }
  });
}

  
  </script>

<!-- JavaScript code to populate the chart with the JSON data -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<style>
    .highlight {
        font-weight: bold;
        background-color: #f5f5f5 !important;
    }
</style>

<script>
$(document).ready(function () {
    // Initialize DataTable with export buttons
    var dataTable = $('#saleskTable').DataTable({
        dom: 'Bfrtip',
        buttons: [
            'copyHtml5',
            'excelHtml5',
            'csvHtml5',
            'pdfHtml5',
            'print'
        ],
        paging: false, // Show all records without pagination
        scrollY: "600px", // Add scroll if many records
        scrollCollapse: true,
        footerCallback: function (row, data, start, end, display) {
            var api = this.api();
            
            // Calculate totals for the current page (all records since paging is false)
            var totalSales = api
                .column(5)
                .data()
                .reduce(function (a, b) {
                    return parseFloat(a) + parseFloat(b);
                }, 0);
            
            var totalProfit = api
                .column(6)
                .data()
                .reduce(function (a, b) {
                    return parseFloat(a) + parseFloat(b);
                }, 0);
            
            // Update footer
            $('#grandTotalSales').html('<strong>' + totalSales.toFixed(2) + '</strong>');
            $('#grandTotalProfit').html('<strong>' + totalProfit.toFixed(2) + '</strong>');
        }
    });

    $('#salesitemreport').on('submit', function (e) {
        e.preventDefault();

        $.ajax({
            type: 'POST',
            url: 'database/itemsreport.kts.php',
            data: $(this).serialize(),
            dataType: 'json',
            success: function (response) {
                // Clear existing data
                dataTable.clear();
                
                // Process the response data
                var dataToProcess = response.data || response; // Handle both formats
                var grandTotalSales = 0;
                var grandTotalProfit = 0;
                
                // Add each row to the DataTable
                $.each(dataToProcess, function (_, row) {
                    // Handle numeric values with commas
                    var cleanBuyingPrice = parseFloat(String(row.Buying_Price).replace(/,/g, ''));
                    var cleanSellingPrice = parseFloat(String(row.Selling_Price).replace(/,/g, ''));
                    var cleanQuantity = parseFloat(String(row.Quantity).replace(/,/g, ''));
                    var cleanSubtotal = parseFloat(String(row.Total_Sales_Subtotal || row.Row_Sales_Subtotal || 0).replace(/,/g, ''));
                    var cleanProfit = parseFloat(String(row.Sub_Profit || 0).replace(/,/g, ''));
                    
                    // Calculate profit if not provided
                    if (!row.Sub_Profit) {
                        cleanProfit = cleanSubtotal - (cleanBuyingPrice * cleanQuantity);
                    }
                    
                    // Add to grand totals
                    grandTotalSales += cleanSubtotal;
                    grandTotalProfit += cleanProfit;
                    
                    // Add row to DataTable
                    dataTable.row.add([
                        row.Product_Name,
                        row.category,
                        cleanBuyingPrice.toFixed(2),
                        cleanSellingPrice.toFixed(2),
                        cleanQuantity.toFixed(2),
                        cleanSubtotal.toFixed(2),
                        cleanProfit.toFixed(2)
                    ]);
                });

                // Draw the table with new data
                dataTable.draw();
                
                // Update footer with totals from server if available
                if (response.total_sales_subtotal || response.total_profit) {
                    var serverTotalSales = parseFloat(String(response.total_sales_subtotal).replace(/,/g, ''));
                    var serverTotalProfit = parseFloat(String(response.total_profit).replace(/,/g, ''));
                    
                    $('#grandTotalSales').html('<strong>' + serverTotalSales.toFixed(2) + '</strong>');
                    $('#grandTotalProfit').html('<strong>' + serverTotalProfit.toFixed(2) + '</strong>');
                }
            },
            error: function (xhr, status, error) {
                console.error("Error:", error);
                alert("Error loading data. Please try again.");
            }
        });
    });
});
</script>

<script>
$(document).ready(function() {
    // Bind the submit event to the form
    $("#waiterreports").submit(function(e) {
        e.preventDefault(); // Prevent the form from submitting normally
        var formData = $(this).serialize(); // Serialize the form data

        // Send an AJAX request
        $.ajax({
            url: 'database/fetch_waiter_sales.kts.php', // The server-side script to process the form
            type: 'POST',
            data: formData,
            dataType: 'json', // Expecting JSON response
          success: function(response) {
    // Check if the response is not empty
    if (response && response.length > 0) {
        var tableRows = "";
        var totalQuantity = 0;
        var totalSubtotal = 0;

        // Iterate over the response to build the table rows
        response.forEach(function(item) {
            tableRows += '<tr>' +
                '<td>' + item.product_name + '</td>' +
                '<td>' + item.quantity + '</td>' +
                '<td>' + item.subtotal + '</td>' +
                '</tr>';

            // Accumulate totals
            totalQuantity += parseFloat(item.quantity);
            totalSubtotal += parseFloat(item.subtotal);
        });

        // Insert the table rows into the modal's table body
        $("#salesDetailsTable tbody").html(tableRows);

        // Create and insert the footer row with totals
        var footerRow = '<tr>' +
            '<td><strong>Total</strong></td>' +
            '<td><strong>' + totalQuantity.toFixed(2) + '</strong></td>' +
            '<td><strong>' + totalSubtotal.toFixed(2) + '</strong></td>' +
            '</tr>';
        $("#salesDetailsTable tfoot").html(footerRow);

        // Show the modal
        $("#viewClientSalesModal").modal("show");
    } else {
        // If there is no data, don't show the modal and optionally alert the user
        alert("No data found for the given criteria.");
    }
},
            error: function(xhr, status, error) {
                // Handle any AJAX errors
                console.error("AJAX Error:", status, error);
            }
        });
    });
});
</script>

<script>
$(document).ready(function() {
  
  // Attach submit event handler to the form
$('#editRoomSaleForm').submit(function(event) {
    // Prevent the default form submission
    event.preventDefault();

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

    // Make AJAX POST request to submit form data to the server
    $.ajax({
        url: 'database/update_room_sale.kts.php', // Replace with the URL of your server-side script
        type: 'POST',
        data: formData, // Form data to be submitted
        dataType: 'json',
        success: function(response) {
            // Handle success response from the server
            // Display SweetAlert success message
            Swal.fire({
                title: 'Success!',
                text: response.message,
                icon: 'success',
                confirmButtonText: 'OK'
            }).then(function() {
                // Reload the page after SweetAlert confirmation
                location.reload();
            });
        },
        error: function(xhr, status, error) {
            // Handle error response from the server
            // Display SweetAlert error message
            Swal.fire({
                title: 'Error!',
                text: 'An error occurred while saving changes: ' + error,
                icon: 'error',
                confirmButtonText: 'OK'
            });
        }
    });
});

});
          </script>
<script>
$(document).ready(function() {
    // Fetch the data
    $.ajax({
        url: "database/fetch_transactions.kts.php",
        type: "GET",
        dataType: "json",
        success: function(data) {
            // Initialize the DataTable with the fetched data
            $('#transactionsTable').DataTable({
                "data": data,
                "columns": [
                    { "data": "trans_id" },
                    { "data": "seller_name" },
                    { "data": "total" },
                    { "data": "amount_received" },
                    { "data": "status" },
                    { "data": "seller_date" },
                    { 
                        "data": null,
                        "render": function(data, type, row) {
                            return '<button class="btn btn-info btn-view" data-trans-id="' + row.trans_id + '">View Details</button>';
                        }
                    }
                ],
                "dom": 'Bfrtip',
                "buttons": [
                    'copy', 'csv', 'excel', 'pdf', 'print'
                ]
            });

            // Add click handler for view buttons
            $('#transactionsTable').on('click', '.btn-view', function() {
                var transId = $(this).data('trans-id');
                viewOrderDet(transId);
            });
        },
        error: function(xhr, status, error) {
            console.error("Error fetching data: " + error);
        }
    });
});

function viewOrderDet(transId) {
    // Make AJAX call to fetch payment details
    $.ajax({
        url: 'database/fetch_order_details.kts.php',
        type: 'POST',
        data: { trans_id: transId },
        dataType: 'json',
        success: function(response) {
            // Clear previous data
            $('#paymentsTable tbody, #salesItemsTable tbody, #transactionReceiptsTable tbody').empty();

            response.transaction_receipts.forEach(function(receipt) {
                // Check if user is manager
                const isManager = <?php echo (isset($_SESSION['type']) && $_SESSION['type'] == 'Manager') ? 'true' : 'false'; ?>;
                
                let actionButtons = '';
                if (isManager) {
                    actionButtons = '<button class="btn btn-danger btn-lg btn-block" data-trans-id="' + receipt.trans_id + '">' +
                        '<i class="fas fa-trash"></i> DELETE TRANSACTION' +
                        '</button>';
                }

                // Add Pay button for all users
                const payButton = '<button class="btn btn-primary btn-pay" data-trans-id="' + receipt.trans_id + '" data-total="' + receipt.total + '">' +
                    '<i class="fas fa-money-bill-wave"></i> PAY' +
                    '</button>';

                $('#transactionReceiptsTable tbody').append(
                    '<tr>' +
                    '<td>' + receipt.trans_id + '</td>' +
                    '<td>' + receipt.seller_name + '</td>' +
                    '<td>' + receipt.total + '</td>' +
                    '<td>' + receipt.amount_received + '</td>' +
                    '<td>' + receipt.phone_number + '</td>' +
                    '<td>' + receipt.seller_date + '</td>' +
                    '<td>' + payButton + ' ' + actionButtons + '</td>' +
                    '</tr>'
                );
            });

            // Populate Payments Table
            if (response.payments && response.payments.length > 0) {
                response.payments.forEach(function(payment) {
                    $('#paymentsTable tbody').append(
                        '<tr>' +
                        '<td>' + payment.pay_id + '</td>' +
                        '<td>' + payment.trans_id + '</td>' +
                        '<td>' + payment.payment_method + '</td>' +
                        '<td>' + payment.amount + '</td>' +
                        '<td>' + payment.payment_date + '</td>' +
                        '<td><i class="fas fa-trash delete-payment" data-pay-id="' + payment.pay_id + '"></i></td>' +
                        '</tr>'
                    );
                });
            }

            // Populate Sales Items Table
            if (response.sales && response.sales.length > 0) {
                response.sales.forEach(function(sale) {
                    $('#salesItemsTable tbody').append(
                        '<tr>' +
                        '<td>' + sale.sale_id + '</td>' +
                        '<td>' + sale.product_name + '</td>' +
                        '<td>' + sale.quantity + '</td>' +
                        '<td>' + sale.selling_price + '</td>' +
                        '<td>' + sale.subtotal + '</td>' +
                        '</tr>'
                    );
                });
            }

            // Delete transaction handler (only for managers)
            $('#transactionReceiptsTable').on('click', '.btn-danger', function() {
                var transId = $(this).data('trans-id');
                deletetrans(transId);
            });

            // Pay button handler
            $('#transactionReceiptsTable').on('click', '.btn-pay', function() {
                var transId = $(this).data('trans-id');
                var totalAmount = $(this).data('total');
                
                // Set the transaction ID and total amount in the payment modal
                $('#loanid').val(transId);
                $('#payamount').val(totalAmount);
                
                // Show the payment modal
                $('#editmodal').modal('show');
            });

            // Delete payment handler
            $('#paymentsTable').on('click', '.delete-payment', function() {
                var payId = $(this).data('pay-id');
                deletePayment(payId);
            });

            // Show the modal
            $('#orderDetailsModal').modal('show');
        },
        error: function(xhr, status, error) {
            console.error("An error occurred: " + error);
            Swal.fire({
                title: 'Error!',
                text: 'Failed to load order details',
                icon: 'error',
                confirmButtonText: 'OK'
            });
        }
    });
}

function deletetrans(transId) {
    Swal.fire({
        title: 'Are you sure?',
        text: "This action is irreversible!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: 'database/delete_transaction.kts.php',
                type: 'POST',
                data: { trans_id: transId },
                success: function(response) {
                    Swal.fire(
                        'Deleted!',
                        'The transaction has been deleted.',
                        'success'
                    ).then(() => {
                        location.reload();
                    });
                },
                error: function(xhr, status, error) {
                    Swal.fire(
                        'Error!',
                        'There was a problem deleting the transaction.',
                        'error'
                    );
                }
            });
        }
    });
}

function deletePayment(payId) {
    Swal.fire({
        title: 'Are you sure?',
        text: "You want to delete this payment?",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: 'database/delete_payment.kts.php',
                type: 'POST',
                data: { pay_id: payId },
                success: function(response) {
                    Swal.fire(
                        'Deleted!',
                        'The payment has been deleted.',
                        'success'
                    ).then(() => {
                        location.reload();
                    });
                },
                error: function(xhr, status, error) {
                    Swal.fire(
                        'Error!',
                        'There was a problem deleting the payment.',
                        'error'
                    );
                }
            });
        }
    });
}

// Payment form submission
$('#payment_update').on('submit', function(event) {
    event.preventDefault();

    var formData = $(this).serialize();
    $.ajax({
        url: './database/payment.kts.php',
        type: 'POST',
        data: formData,
        success: function(response) {
            try {
                var jsonResponse = JSON.parse(response);
                if (jsonResponse.status === 'success') {
                    Swal.fire({
                        title: 'Success!',
                        text: jsonResponse.message,
                        icon: 'success',
                        confirmButtonText: 'OK'
                    }).then(function() {
                        $('#editmodal').modal('hide');
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: jsonResponse.message,
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                }
            } catch (e) {
                Swal.fire({
                    title: 'Error!',
                    text: 'Invalid response from server',
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
            }
            $('#payment_update')[0].reset();
        },
        error: function(xhr, status, error) {
            Swal.fire({
                title: 'Error!',
                text: 'An error occurred while processing payment',
                icon: 'error',
                confirmButtonText: 'OK'
            });
            console.log(xhr.responseText);
        }
    });
});

// Helper functions for the payment modal
function showHideBookingIdInput() {
    var paymentMethod = $('#paymethod').val();
    if (paymentMethod === 'rooms') {
        $('#bookingIdContainer').show();
    } else {
        $('#bookingIdContainer').hide();
    }
}

function showHideSecondPayment() {
    if ($('#addSecondPaymentCheckbox').is(':checked')) {
        $('#secondPaymentContainer').show();
    } else {
        $('#secondPaymentContainer').hide();
    }
}
</script>
<script>
      
$(document).ready(function() {
    // This event listener is for debugging purposes to ensure the modal can be manually opened.
    $('#testOpenModal').on('click', function() {
        $('#editSaleModal').modal('show');
    });

    $('#salesItemsTable').on('click', '.fas.fa-edit', function() {
        var saleId = $(this).data('sale-id');
        console.log('Fetching data for sale ID:', saleId); // Debugging
        fetchSaleData(saleId);
    });

    function fetchSaleData(saleId) {
        $.ajax({
            url: 'database/get_sale_item.kts.php',
            type: 'POST',
            data: { sale_id: saleId },
            dataType: 'json',
            success: function(response) {
                console.log('Response received:', response); // Debugging
                if(response && response.sale_id) {
                    // Assuming response contains the expected data
                    $('#editSaleModal').find('#originalSaleId').val(response.sale_id);
                    $('#editSaleModal').find('#editQuantity').val(response.quantity);
                    $('#editSaleModal').find('#editSellingPrice').val(response.selling_price);
                    $('#editSaleModal').find('#editSubtotal').val(response.subtotal);
                    $('#editSaleModal').find('#originalQuantity').val(response.quantity);
                    $('#editSaleModal').find('#originalSubtotal').val(response.subtotal);

                    $('#editSaleModal').modal('show');
                } else {
                    alert('No data found for the selected sale.');
                }
            },
            error: function(xhr, status, error) {
                console.error("Error fetching sale data: " + error);
            }
        });
    }
  
    // Function to update subtotal when quantity changes
    $('#editSaleModal').on('change', '#editQuantity', function() {
        var quantity = $(this).val();
        var sellingPrice = $('#editSellingPrice').val();
        var subtotal = quantity * sellingPrice;
        $('#editSubtotal').val(subtotal.toFixed(2));
    });
  
   // Handle edit sale form submission
    $('#editSaleForm').submit(function(event) {
        event.preventDefault();
        var formData = $(this).serialize();
        $.ajax({
            url: 'database/update_sale_item.kts.php',
            type: 'POST',
            data: formData,
            success: function(response) {
                // Handle success
                $('#editSaleModal').modal('hide');
                // Refresh the DataTable
                table.ajax.reload();
            },
            error: function(xhr, status, error) {
                // Handle error
            }
        });
    });


});
      
</script>


<script>
$(document).ready(function() {
    $('#payment_update').submit(function(e) {
        e.preventDefault(); // Prevent the form from submitting the traditional way

        $.ajax({
            type: 'POST',
            url: './database/payment.kts.php', // Replace with the path to your PHP script
            data: $(this).serialize(),
            dataType: 'json', // Expect a JSON response from the server
            success: function(response) {
                if(response.status === 'success') {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: response.message,
                        confirmButtonText: 'OK'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            // Optionally redirect or perform another action
                            window.location.reload(); // As an example, reload the page
                        }
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: response.message,
                        confirmButtonText: 'OK'
                    });
                }
            },
            error: function(xhr, status, error) {
                Swal.fire({
                    icon: 'error',
                    title: 'AJAX Error',
                    text: 'There was an error processing your request: ' + error,
                    confirmButtonText: 'OK'
                });
            }
        });
    });
});
</script>
 <script>
        // Use jQuery to make the AJAX request when the page loads
        $(document).ready(function () {
            $.ajax({
                type: 'POST',
                url: 'database/daily_report.kts.php', // Create a PHP file to handle the AJAX request (daily_report.php)
                dataType: 'json', // Expect JSON response
                success: function (data) {
                    // Update the HTML with the fetched data
                    if (data.success) {
                        $('#report-data').html(data.reportData);
                        $('#daily-total').html(data.dailyTotal);
                    } else {
                        // Handle errors here
                        alert(data.message);
                    }
                },
                error: function () {
                    // Handle AJAX errors here
                    alert('Error fetching data.');
                }
            });
        });
    </script>
 <script>
        // Use jQuery to make the AJAX request when the page loads
        $(document).ready(function () {
            $.ajax({
                type: 'POST',
                url: 'database/weekely_report.kts.php', // Create a PHP file to handle the AJAX request
                dataType: 'json', // Expect JSON response
                success: function (data) {
                    // Update the HTML with the fetched data
                    if (data.success) {
                        $('#weekely-data').html(data.reportData);
                        $('#weekly-total').html(data.weeklyTotal);
                    } else {
                        // Handle errors here
                        alert(data.message);
                    }
                },
                error: function () {
                    // Handle AJAX errors here
                    alert('Error fetching data.');
                }
            });
        });
    </script>
   

    <script>
    $(document).ready(function() {
        // Send an AJAX request on page load
        $.ajax({
            url: './database/monthly_report.kts.php', // The server-side script to process the form
            type: 'GET',
            dataType: 'json', // Expecting JSON response
            success: function(response) {
                if (response.success) {
                    var tableRows = "";

                    // Iterate over the response to build the table rows
                    response.reportData.forEach(function(item) {
                        tableRows += '<tr>' +
                            '<td>' + item.payment_method + '</td>' +
                            '<td>' + item.tills + '</td>' +
                            '</tr>';
                    });

                    // Insert the table rows into the table body
                    $("#monthly-data").html(tableRows);

                    // Display the total amount in the footer
                    $("#monthly-total").text(response.monthlyTotal.toFixed(2));
                } else {
                    // If there is an error, alert the user
                    alert(response.message || "An error occurred while fetching the data.");
                }
            },
            error: function(xhr, status, error) {
                // Handle any AJAX errors
                console.error("AJAX Error:", status, error);
            }
        });
    });
    </script>
   

<script>
  
  
  var ctx = document.getElementById("pieChart");
  ctx.height = 350;

  var myChart = new Chart(ctx, {
    type: 'pie',
    data: {
      datasets: [{
        data: <?php echo $json_data; ?>,
        backgroundColor: [
          "rgba(117, 113, 249, 0.5)",
          "rgba(144, 104, 190, 0.5)",
          "rgba(235, 12, 192, 0.5)"
         
        ],
        hoverBackgroundColor: [
          "rgba(117, 113, 249, 0.5)",
          "rgba(144, 104, 190, 0.5)",
          "rgba(235, 12, 192, 0.8)"
         
        ]
      }],
      labels: [
        <?php
          // Loop through the data array to get the labels
          foreach ($data as $row) {
            echo '"' . $row["label"] . '",';
          }
        ?>
      ]
    },
    options: {
      responsive: true,
      legend: {
        position: 'bottom'
      }
    }
  });
</script> 
   


<script>
$(document).ready(function () {
    function getWeekOptions() {
        $.ajax({
            url: './database/getweeks.kts.php',
            method: 'GET',
            dataType: 'json',
            success: function (data) {
                let weekSelect = $('#weekSelect');
                weekSelect.empty();
                data.forEach(function (week) {
                    weekSelect.append(new Option(week.text, week.value));
                });
                fetchDataAndRenderChart(data[0].value); // Fetch data for the first week by default
            }
        });
    }

    function fetchDataAndRenderChart(week) {
        $.ajax({
            url: './weekly_data.php',
            method: 'GET',
            data: { week: week },
            dataType: 'json',
            success: function (data) {
                renderChart(data);
            }
        });
    }

    function renderChart(data) {
        let ctx = document.getElementById('barChart').getContext('2d');
        let datasets = [];

        Object.keys(data.data).forEach(function (key) {
            datasets.push({
                label: key.replace('_total', '').toUpperCase(),
                data: data.data[key],
                backgroundColor: getRandomColor(),
                borderColor: getRandomColor(),
                borderWidth: 1
            });
        });

        datasets.push({
            label: 'Debt',
            data: data.debt,
            backgroundColor: 'rgba(255, 99, 132, 0.6)',
            borderColor: 'rgba(255, 99, 132, 1)',
            borderWidth: 1
        });

        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: data.labels,
                datasets: datasets
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }

    function getRandomColor() {
        let letters = '0123456789ABCDEF';
        let color = '#';
        for (let i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }

    $('#weekSelect').change(function () {
        let selectedWeek = $(this).val();
        fetchDataAndRenderChart(selectedWeek);
    });

    getWeekOptions();
});

</script>

  <!--  Monthly Analysis -->
      <script>
        $(document).ready(function() {
            // Populate year options dynamically
            $.ajax({
                url: './database/fetch_years.kts.php',
                type: 'GET',
                dataType: 'json',
                success: function(data) {
                    var yearSelect = $('#yearSelect');
                    data.forEach(function(year) {
                        yearSelect.append(new Option(year, year));
                    });
                    filterData(); // Load data for the first year in the list
                },
                error: function(xhr, status, error) {
                    console.log('Error fetching years:', xhr.responseText);
                }
            });
        });

        function filterData() {
            var selectedYear = $("#yearSelect").val();

            $.ajax({
                url: './database/fetchyeardata.kts.php',
                type: 'GET',
                data: { year: selectedYear },
                dataType: 'json',
                success: function(data) {
                    var labels = data.labels;
                    var datasets = [];
                    var colors = ["rgba(144, 104, 190, 0.5)", "rgba(0, 128, 0, 0.5)", "rgba(0, 0, 255, 0.5)", "rgba(255, 99, 132, 0.5)"];

                    for (var key in data.data) {
                        if (data.data.hasOwnProperty(key)) {
                            datasets.push({
                                label: key,
                                data: data.data[key],
                                borderColor: colors[datasets.length % colors.length].replace("0.5", "0.9"),
                                borderWidth: 1,
                                backgroundColor: colors[datasets.length % colors.length]
                            });
                        }
                    }

                    datasets.push({
                        label: 'Total Debt',
                        data: data.debt,
                        backgroundColor: 'rgba(255, 99, 132, 0.2)',
                        borderColor: 'rgba(255, 99, 132, 1)',
                        borderWidth: 1
                    });

                    var ctx = document.getElementById('barChart2').getContext('2d');
                    new Chart(ctx, {
                        type: 'bar',
                        data: {
                            labels: labels,
                            datasets: datasets
                        },
                        options: {
                            scales: {
                                yAxes: [{
                                    ticks: {
                                        beginAtZero: true
                                    }
                                }]
                            },
                            legend: {
                                display: true
                            }
                        }
                    });
                },
                error: function(xhr, status, error) {
                    console.log('Error fetching data:', xhr.responseText);
                }
            });
        }
    </script>
   <script>
// Function to handle form submission and AJAX request
function generateTransactionReport() {
    // Get the form data
    var formData = {
        startz: $('input[name=startz]').val(),
        endz: $('input[name=endz]').val()
    };

    // Send the AJAX request to the server
    $.ajax({
        type: 'POST',
        url: 'database/filtered.kts.php',
        data: formData,
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                // Update the table with the fetched data
                $('#transaction-reportdata tbody').html(response.reportData);

                // Update the total amount with two decimal places and set the color to red
                $('#filtereddt-total').text(response.monthlyTotal.toFixed(2)).css('color', 'red');
            } else {
                // Display an error message if the request was not successful
                console.error(response.message);
            }
        },
        error: function(xhr, status, error) {
            // Handle AJAX error
            console.error(xhr.responseText);
            alert('AJAX Error: ' + error);
        }
    });
}

// Call the function when the document is ready
$(document).ready(function () {
    generateTransactionReport();

    // Assuming you have a button with id "generate-report-btn"
    $('#generate-report-btn').on('click', function () {
        generateTransactionReport();
    });
});
</script>

<script>
$(document).ready(function() {
    // Function to update subtotal
    function updateSubtotal() {
        var numberOfDays = $('#nod').val();
        var roomPrice = $('#roomPrice').val();
        var subtotal = numberOfDays * roomPrice;
        $('#subtotal').val(subtotal);
    }

    // Bind input event handler to both inputs
    $('#nod, #roomPrice').on('input', function() {
        updateSubtotal();
    });

    // Initial update of subtotal
    updateSubtotal();
});
</script>
 <script>
$(document).ready(function() {
    $('#reportzForm').on('submit', function(e) {
        e.preventDefault();

        // Gather form data
        var formData = new FormData(this);

        $.ajax({
            url: './database/consumption_report.kts.php',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function(response) {
                let report = JSON.parse(response);
                let reportHtml = '<h4>Stock Movement Report from ' + $('#startdateconsumption').val() + ' to ' + $('#enddateconsumption').val() + '</h4>';
                reportHtml += '<div class="table-responsive"><table id="reportTable" class="table table-bordered"><thead><tr><th>Product ID</th><th>Product Name</th><th>Category</th><th>Opening Quantity</th><th>Opening Value</th><th>Received Quantity</th><th>Received Value</th><th>Sold Quantity</th><th>Sold Value</th><th>Disposed Quantity</th><th>Closing Quantity</th><th>Closing Value</th><th>Physical Quantity</th><th>Physical Value</th><th>Variance Quantity</th><th>Variance Value</th></tr></thead><tbody>';
                
                let soldValueSum = 0;

                report.forEach(function(item) {
                    reportHtml += '<tr>';
                    reportHtml += '<td>' + item.product_id + '</td>';
                    reportHtml += '<td>' + item.productname + '</td>';
                    reportHtml += '<td>' + item.category + '</td>';
                    reportHtml += '<td>' + item.opening_quantity + '</td>';
                    reportHtml += '<td>' + item.opening_value + '</td>';
                    reportHtml += '<td>' + item.received_quantity + '</td>';
                    reportHtml += '<td>' + item.received_value + '</td>';
                    reportHtml += '<td>' + item.sold_quantity + '</td>';
                    reportHtml += '<td>' + item.sold_value + '</td>';
                    reportHtml += '<td>' + item.disposed_quantity + '</td>';
                    reportHtml += '<td>' + item.closing_quantity + '</td>';
                    reportHtml += '<td>' + item.closing_value + '</td>';
                    reportHtml += '<td>' + item.physical_quantity + '</td>';
                    reportHtml += '<td>' + item.physical_value + '</td>';
                    reportHtml += '<td>' + item.variance_qty + '</td>';
                    reportHtml += '<td>' + item.variance_value + '</td>';
                    reportHtml += '</tr>';

                    // Calculate the sum for Sold Value
                    soldValueSum += parseFloat(item.sold_value);
                });

                reportHtml += '</tbody><tfoot><tr>';
                reportHtml += '<td colspan="8">Total Sold Value</td>';
                reportHtml += '<td>' + soldValueSum.toFixed(2) + '</td>';
                reportHtml += '<td colspan="7"></td>';
                reportHtml += '</tr></tfoot></table></div>';
                
                $('#reportResult').html(reportHtml);

                // Initialize DataTable with export buttons
                $('#reportTable').DataTable({
                    dom: 'Bfrtip', // Include buttons and other elements
                    buttons: [
                        {
                            extend: 'copy',
                            exportOptions: {
                                columns: [1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], // Exclude Product ID and Category
                                footer: true // Include footer in export
                            }
                        },
                        {
                            extend: 'csv',
                            exportOptions: {
                                columns: [1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], // Exclude Product ID and Category
                                footer: true // Include footer in export
                            }
                        },
                        {
                            extend: 'excel',
                            title: 'Stock Movement Report',
                            messageTop: 'Report from ' + $('#startdateconsumption').val() + ' to ' + $('#enddateconsumption').val(),
                            exportOptions: {
                                columns: [1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], // Exclude Product ID and Category
                                footer: true // Include footer in export
                            },
                            customize: function (xlsx) {
                                let sheet = xlsx.xl.worksheets['sheet1.xml'];
                                $(sheet).find('row c[r^="A"], row c[r^="C"]').attr('s', '2'); // Hide the first column (Product ID) and third column (Category)
                            }
                        },
                        {
                            extend: 'pdf',
                            orientation: 'landscape', // Set PDF to landscape mode
                            title: 'Stock Movement Report',
                            message: 'Report from ' + $('#startdateconsumption').val() + ' to ' + $('#enddateconsumption').val(),
                            exportOptions: {
                                columns: [1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], // Exclude Product ID and Category
                                footer: true // Include footer in export
                            }
                        },
                        {
                            extend: 'print',
                            title: 'Report from ' + $('#startdateconsumption').val() + ' to ' + $('#enddateconsumption').val(),
                            exportOptions: {
                                columns: [1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], // Exclude Product ID and Category
                                footer: true // Include footer in export
                            }
                        }
                    ],
                    columnDefs: [
                        { targets: [0, 2], visible: false } // Hide the Product ID and Category columns
                    ],
                    footerCallback: function(row, data, start, end, display) {
                        var api = this.api();

                        // Remove the formatting to get integer data for summation
                        var intVal = function(i) {
                            return typeof i === 'string' ?
                                i.replace(/[\$,]/g, '')*1 :
                                typeof i === 'number' ?
                                i : 0;
                        };

                        // Total over all pages
                        total = api
                            .column(8)
                            .data()
                            .reduce(function(a, b) {
                                return intVal(a) + intVal(b);
                            }, 0);

                        // Update footer
                        $(api.column(8).footer()).html(
                            'Total: ' + total.toFixed(2)
                        );
                    }
                });
            },
            error: function(error) {
                console.error('Error:', error);
            }
        });
    });
});
</script>

<script>

$(document).ready(function(){
    function fetchSalesData() {
        $.ajax({
            url: './database/fetch_sales_data.kts.php',
            method: 'GET',
            dataType: 'json',
            success: function(data) {
                let salesData = '';
                data.forEach(function(row) {
                    salesData += `
                        <tr>
                            <td>${row.seller_name}</td>
                            <td>${row.total_sales}</td>
                            <td>${row.cash_at_hand}</td>
                            <td>${row.debt}</td>
                        </tr>
                    `;
                });
                $('#sales-data').html(salesData);
            },
            error: function(error) {
                console.log('Error:', error);
            }
        });
    }

    // Fetch sales data when the page loads
    fetchSalesData();
});    
    

</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>
        <script>
$(document).ready(function() {
    // Function to fetch dashboard stats
    function fetchDashboardStats() {
        $.ajax({
            url: './database/dashboard_stats.kts.php',
            type: 'GET',
            dataType: 'json',
            success: function(data) {
                // Update the DOM with the received data
                $('#total-sales').text(data.total_sales);
                $('#till').text(data.till);
                $('#cash').text(data.cash);
                $('#debt').text(data.debt);
                $('#merchant').text(data.merchant);
                $('#inhouse').text(data.inhouse);
            },
            error: function(xhr, status, error) {
                console.error('Error fetching dashboard stats:', error);
            }
        });
    }
    
    // Fetch stats immediately when page loads
    fetchDashboardStats();
    
    // Optionally: Set up auto-refresh every X minutes (e.g., 5 minutes)
    setInterval(fetchDashboardStats, 300000); // 300000 ms = 5 minutes
});
</script> 
        


<script>
    // Initialize Bootstrap tabs
    $(document).ready(function(){
        $('#dashboardTabs a').on('click', function (e) {
            e.preventDefault();
            $(this).tab('show');
        });
        
        // You can add more JavaScript for your charts and data tables here
    });
</script>


<script>
document.addEventListener('DOMContentLoaded', function() {
    const salesGeneratorTab = document.getElementById('generator');
    
    if (salesGeneratorTab) {
        // Load initial target amount
        fetchTargetAmount();
        
        // Setup form submission
        document.getElementById('generateSalesForm').addEventListener('submit', function(e) {
            e.preventDefault();
            generateBeverageSales();
        });
        
        // Setup regenerate button
        document.getElementById('regenerateButton').addEventListener('click', function(e) {
            e.preventDefault();
            generateBeverageSales();
        });
        
        // Initialize results section as hidden
        document.getElementById('resultsSection').classList.add('d-none');
    }
});

// Fetch current 18% target amount
function fetchTargetAmount() {
    showLoading('targetAmount', true);
    
    fetch('./database/sales_generator_api.kts.php')
        .then(handleResponse)
        .then(data => {
            document.getElementById('targetAmount').textContent = `$${data.formatted_target}`;
            document.getElementById('targetValue').value = data.target;
        })
        .catch(error => {
            console.error('Error fetching target amount:', error);
            showSweetAlert('error', 'Error', 'Failed to load target amount');
        })
        .finally(() => {
            showLoading('targetAmount', false);
        });
}

// Generate beverage sales
function generateBeverageSales() {
    const button = document.getElementById('generateButton');
    const regenerateButton = document.getElementById('regenerateButton');
    const originalText = button.textContent;
    
    // Show loading state
    button.disabled = true;
    button.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Generating...';
    
    // Hide regenerate button during generation
    regenerateButton.classList.add('d-none');
    
    fetch('./database/sales_generator_api.kts.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(handleResponse)
    .then(data => {
        showSweetAlert('success', 'Success', data.message);
        displayGeneratedSales(data.sales, data.total);
        document.getElementById('targetAmount').textContent = `$${data.formatted_target}`;
        document.getElementById('targetValue').value = data.total;
        regenerateButton.classList.remove('d-none');
    })
    .catch(error => {
        console.error('Error:', error);
        showSweetAlert('error', 'Error', error.message || 'Failed to generate sales');
    })
    .finally(() => {
        button.disabled = false;
        button.textContent = originalText;
    });
}

// Handle API response
function handleResponse(response) {
    if (!response.ok) {
        throw new Error('Network response was not ok');
    }
    return response.json().then(data => {
        if (!data.success) {
            throw new Error(data.message || 'Request failed');
        }
        return data;
    });
}

// Display generated sales in table
function displayGeneratedSales(sales, total) {
    const tableBody = document.getElementById('generatedSalesBody');
    const tableFooter = document.getElementById('generatedSalesFooter');
    const resultsSection = document.getElementById('resultsSection');
    
    // Clear previous results
    tableBody.innerHTML = '';
    
    // Add new sales
    sales.forEach(sale => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${sale.product_name || 'N/A'}</td>
            <td>${sale.quantity || 0}</td>
            <td>$${parseFloat(sale.selling_price || 0).toFixed(2)}</td>
            <td>$${parseFloat(sale.subtotal || 0).toFixed(2)}</td>
            <td>${sale.trans_id || 'N/A'}</td>
        `;
        tableBody.appendChild(row);
    });
    
    // Update footer with total
    tableFooter.innerHTML = `
        <tr class="font-weight-bold">
            <td colspan="3">Total Generated</td>
            <td>$${parseFloat(total || 0).toFixed(2)}</td>
            <td></td>
        </tr>
    `;
    
    // Show results section
    resultsSection.classList.remove('d-none');
    
    // Scroll to results
    resultsSection.scrollIntoView({ behavior: 'smooth' });
}

// Show SweetAlert message
function showSweetAlert(icon, title, text) {
    Swal.fire({
        icon: icon,
        title: title,
        text: text,
        timer: 5000,
        showConfirmButton: true,
        timerProgressBar: true
    });
}

// Show loading state for elements
function showLoading(elementId, isLoading) {
    const element = document.getElementById(elementId);
    if (!element) return;
    
    if (isLoading) {
        element.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Calculating...';
    } else {
        // Default text will be set by the calling function
    }
}
</script>



</body>

</html>