<?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>Jacyjoka Apartments</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">


    

    

</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
        ***********************************-->
     <?php


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

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

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

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

?>

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

            ?>
            <li>
                <a href="logout.php" aria-expanded="false">
                    <i class="icon-lock menu-icon"></i><span class="nav-text">LogOut</span>
                </a>
            </li>
        </ul>
    </div>
</div>


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

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

        <!--**********************************
            Content body start
        ***********************************-->
        <div class="content-body">
            <div class="container-fluid mt-3">
                <div class="row">
                   
                    <div class="col-md-4 col-sm-6">
                        <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"><?php
                     include 'database/shikanisha.kts.php';
                     $sql = "SELECT SUM(total) AS total_sum FROM transaction_receipts WHERE DATE(seller_date) = CURDATE()";
                     $result = mysqli_query($conn, $sql);
                     while($row=mysqli_fetch_array($result)){
                    ?><?php echo $row['total_sum'];} ?></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">
                        <div class="card gradient-2">
                           <div class="card-body">
                               
                                <h3 class="card-title text-white">Till Number</h3>
                                <div class="d-inline-block">
                                  <?php
include 'database/shikanisha.kts.php';

$sql = "SELECT 
  p.payment_method,
  SUM(p.amount) AS till
FROM 
  payments AS p
JOIN 
  transaction_receipts AS tr ON p.trans_id = tr.trans_id
WHERE 
  DATE(tr.seller_date) = CURDATE() AND p.payment_method = 'till'
GROUP BY 
  p.payment_method;
";

$result = mysqli_query($conn, $sql);

while ($row = mysqli_fetch_array($result)) {
    echo '<h2 class="text-white">' . $row['till'] . '</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">
                        <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"> <?php
                     include 'database/shikanisha.kts.php';
                   
$sql = "SELECT 
  p.payment_method,
  SUM(p.amount) AS cash
FROM 
  payments AS p
JOIN 
  transaction_receipts AS tr ON p.trans_id = tr.trans_id
WHERE 
  DATE(tr.seller_date) = CURDATE() AND p.payment_method = 'cash'
GROUP BY 
  p.payment_method;
";

                     $result = mysqli_query($conn, $sql);
                     while($row=mysqli_fetch_array($result)){
                    ?><?php echo $row['cash']; }?></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">
                        <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"><?php
                     include 'database/shikanisha.kts.php';
                     $sql = "SELECT 
  SUM(total) - SUM(amount_received) AS debt
FROM 
  transaction_receipts
WHERE 
  DATE(seller_date) = CURDATE();
";
                     $result = mysqli_query($conn, $sql);
                     while($row=mysqli_fetch_array($result)){
                    ?><?php echo $row['debt'];} ?></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">
                        <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"> <?php
                     include 'database/shikanisha.kts.php';
                   
$sql = "SELECT 
  p.payment_method,
  SUM(p.amount) AS merchant
FROM 
  payments AS p
JOIN 
  transaction_receipts AS tr ON p.trans_id = tr.trans_id
WHERE 
  DATE(tr.seller_date) = CURDATE() AND p.payment_method = 'merchant'
GROUP BY 
  p.payment_method;
";

                     $result = mysqli_query($conn, $sql);
                     while($row=mysqli_fetch_array($result)){
                    ?><?php echo $row['merchant']; }?></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">
                        <div class="card gradient-1">
                            <div class="card-body">
                                <h3 class="card-title text-white">Captain Order Payments</h3>
                                <div class="d-inline-block">
                                    <h2 class="text-white"><?php
                     include 'database/shikanisha.kts.php';
                                  
$sql = "SELECT 
  p.payment_method,
  SUM(p.amount) AS captain
FROM 
  payments AS p
JOIN 
  transaction_receipts AS tr ON p.trans_id = tr.trans_id
WHERE 
  DATE(tr.seller_date) = CURDATE() AND p.payment_method = 'Captains Order'
GROUP BY 
  p.payment_method;
";

                     $result = mysqli_query($conn, $sql);
                     while($row=mysqli_fetch_array($result)){
                    ?><?php echo $row['captain'];} ?></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>
                  
                    
             
                
                 <div class="row">
    <div class="col-lg-12 col-sm-12">
        <div class="card">
            <div class="card-body">
                <h4 class="card-title">Waiter Detailed Report</h4>
                <div class="basic-form">
                   <form id="waiterreports">
    <div class="form-row align-items-center">
        <!-- Waiter Name Input -->
        <div class="col-auto">
                                <label class="sr-only">Waiter 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>
        <!-- Start Date Input -->
        <div class="col-auto">
            <input type="datetime-local" name="start" class="form-control mb-2" placeholder="Start Date and Time">
        </div>
        <!-- End Date Input -->
        <div class="col-auto">
            <input type="datetime-local" name="end" class="form-control mb-2" placeholder="End Date and Time">
        </div>
        <!-- Submit Button -->
        <div class="col-auto">
            <button type="submit" class="btn btn-dark mb-2">Generate Waiter Report</button>
        </div>
    </div>
</form>
                </div>
            </div>
        </div>
        
      
  </div>
</div>
              
               <div class="row">
    <div class="col-lg-12 col-sm-12">
        <div class="card">
            <div class="card-body">  
              <h4 class="card-title">Sales Detailed Report</h4>  <!-- Items Report Form -->
    <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>

    <!-- Items Report Table -->
    <div class="active-member">
        <div class="table-responsive">
             <table id="saleskTable" class="table table-striped table-bordered">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Buying Price</th>
            <th>Selling Price</th>
            <th>Quantity</th>
            <th>Subtotal Bp</th>
            <th>Sales Subtotal</th>
            <th>Profit</th>
        </tr>
    </thead>
    <tbody>
        <!-- Data will be inserted here by AJAX -->
    </tbody>
    <tfoot>
        <tr>
            <td colspan="7"></td>
            <td><b><i>Total Profit: Ksh<span id="totalProfit">0.00</span></i></b></td>
        </tr>
    </tfoot>
</table>

        </div>
    </div>
</div>
          </div>
                 </div>
          </div>
 
             <div class="row">
  <div class="col-lg-12 col-sm-12">
    <div class="card">
      <div class="card-body">
        <h4 class="card-title">Transactions</h4>
        <div class="active-member">
          <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>


               <div class="row">
                    <div class="col-lg-12 col-sm-12">
                      <div class="card">
                              <div class="card-body">
                                <h4 class="card-title">Member Sales Status</h4>
                                <div class="active-member">
                                    <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>
               
             <div class="row">
                    <div class="col-lg-12 col-sm-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 @ Hand</th>                       <th>Total Unpaid</th>
                                               
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
        
                                                    $sql = "SELECT
    `seller_name`,
    SUM(`total`) AS `total_sales`,
    SUM(`amount_received`) AS `cash_at_hand`,
    (SUM(`total`) - SUM(`amount_received`)) AS `debt`
FROM
    `transaction_receipts`
WHERE
    `seller_date` >= CONCAT(CURDATE(), ' 06:00:00') AND
    `seller_date` < CONCAT(CURDATE() + INTERVAL 1 DAY, ' 05:00:00')
GROUP BY
    `seller_name`;
";
                                                    $result=mysqli_query($conn,$sql);
                                                     while($row=mysqli_fetch_array($result)){
                                                  ?>
                                            
                                            <tr>
                                                <td><?php echo $row['seller_name']; ?></td>
                                                <td><?php echo $row['total_sales']; ?></td>
                                                 <td><?php echo $row['cash_at_hand']; ?></td>
                                                  <td><?php echo $row['debt']; ?></td>
                                                
                                            </tr>
                                             <?php } ?> 
                                        </tbody>
                                        <tfoot>
                                            <tr>
                                                <th></th>
                                                <th>Total Amt</th>
                                                <th></th>
                                            </tr>
                                         
                                            
                                        </tfoot>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>  
                
                 <div class="row">
        <div class="col-lg-12 col-sm-12">
            <div class="card">
                <div class="card-body">
                    <h4 class="card-title">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 class="row">
        <div class="col-lg-12 col-sm-12">
            <div class="card">
                <div class="card-body">
                    <h4 class="card-title">Weekly sales 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">
    <div class="col-lg-12 col-sm-12">
        <div class="card">
            <div class="card-body">
                <h4 class="card-title">Filtered Transaction Report</h4>
                <div class="basic-form">
                    <!-- Add ID to the form for easier identification -->
                    <form id="transactionreports">
                        <div class="form-row align-items-center">
                            <!-- Start Date Input -->
                            <div class="col-auto">
                                <input type="datetime-local" name="startz" class="form-control mb-2" placeholder="Start Date and Time">
                            </div>
                            <!-- End Date Input -->
                            <div class="col-auto">
                                <input type="datetime-local" name="endz" class="form-control mb-2" placeholder="End Date and Time">
                            </div>
                            <!-- Submit Button -->
                            <div class="col-auto">
                                <!-- Change button type to button to prevent default form submission -->
                                <button type="button" class="btn btn-dark mb-2" onclick="generateTransactionReport()">Generate Transaction Report</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <div class="card-body">
                <h4 class="card-title">Filtered Transaction Report</h4>
                <div class="table-responsive">
                    <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 class="row">
        <div class="col-lg-12 col-sm-12">
            <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>
                              <div class="row">
                          
                         <div class="col-sm-12 col-md-12">
                            <div class="card">
                                <div class="card-body">
                                    <h4 class="card-title">Weekly Monatory Analysis</h4>
                                  <canvas id="barChart"></canvas>
                                </div>
                            </div>
                            
                        </div>
                    </div>
                    
                     <div class="row">
            <div class="col-sm-12 col-md-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 -->
                                <?php
                                // Retrieve distinct years from the data
                                $sql = "SELECT DISTINCT YEAR(seller_date) AS year FROM transaction_receipts ORDER BY year DESC";
                                $result = $conn->query($sql);
                                if ($result->num_rows > 0) {
                                    while ($row = $result->fetch_assoc()) {
                                        $year = $row["year"];
                                        echo "<option value=\"$year\">$year</option>";
                                    }
                                }
                                ?>
                            </select>
                        </div>
                        <canvas id="barChart2"></canvas>
                    </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>
                    </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>
                                                        </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>
                                                        </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>
                                                </form>
                                            </div>
                                        </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>
    $(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>
<script>

$(document).ready(function () {
    // Initialize DataTable with Buttons
    var dataTable = $('#saleskTable').DataTable({
        dom: 'Bfrtip',
        buttons: [
            'copyHtml5',
            'excelHtml5',
            'csvHtml5',
            'pdfHtml5',
            'print'
        ]
    });

    $('#salesitemreport').on('submit', function (e) {
        e.preventDefault(); // Prevent the default form submission

        $.ajax({
            type: 'POST',
            url: 'database/itemsreport.kts.php',
            data: $(this).serialize(),
            dataType: 'json',
            success: function (response) {
                // Clear previous table data
                dataTable.clear().draw();

                // Iterate over each row of data
                $.each(response.data, function (_, row) {
                    // Add row data to the DataTable
                    dataTable.row.add([
                        row.product_id,
                        row.product_name,
                        row.buying_price,
                        row.selling_price,
                        row.total_quantity,
                        row.total_subtotal,
                         row.bp,
                        parseFloat(row.profit).toFixed(2)
                    ]);
                });

                // Draw the updated DataTable
                dataTable.draw();

                // Append total to table footer
                dataTable.row.add([
                    'Total', '', '', '', '', '', '',
                    parseFloat(response.total_profit).toFixed(2)
                ]).draw();

                // Update the total profit in the footer
                $('#totalProfit').text(parseFloat(response.total_profit).toFixed(2));
            },
            error: function (xhr, status, error) {
                console.error("An error occurred: " + error);
            }
        });
    });
});
</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 = "";

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

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

        // 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", // The server-side script to fetch data
        type: "GET",
        dataType: "json", // Expecting JSON formatted data
        success: function(data) {
            // Initialize the DataTable with the fetched data
            $('#transactionsTable').DataTable({
                "data": data, // Use the data source from the AJAX call
                "columns": [
                    { "data": "trans_id" },
                    { "data": "seller_name" },
                    { "data": "total" },
                    { "data": "amount_received" },
                    { "data": "status" },
                    { "data": "seller_date" },
                    { "data": "action" }
                  
                ],
                "dom": 'Bfrtip', // Needs to be added to define where the buttons will appear
                "buttons": [
                    'copy', 'csv', 'excel', 'pdf', 'print'
                ]
            });
        },
        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', // Server-side script to fetch order details
        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) {
                $('#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>' +
                  
                    '<i class="fas fa-trash" data-trans-id="' + receipt.trans_id + '"></i>&nbsp;' +
                   '&nbsp;<i class="fas fa-money" data-trans-id="' + receipt.trans_id + '"></i>' +
                    '</td>' +
                    '</tr>'
                );
            });
           $('#transactionReceiptsTable').on('click', '.fas.fa-trash', function() {
                var transId = $(this).data('trans-id');
                deletetrans(transId);
            });
            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 call to delete the transaction
                        $.ajax({
                            url: 'database/delete_transaction.kts.php',
                            type: 'POST',
                            data: { trans_id: transId },
                            success: function(response) {
                                // Handle success (reload parts of the page, update UI, etc.)
                                Swal.fire(
                                    'Deleted!',
                                    'The transaction has been deleted.',
                                    'success'
                                );
                                // Optionally, reload the DataTable or remove the row from the table
                              location.reload();
                            },
                            error: function(xhr, status, error) {
                                // Handle error
                                Swal.fire(
                                    'Error!',
                                    'There was a problem deleting the transaction.',
                                    'error'
                                );
                            }
                        });
                    }
                })
            }
          
           $('#transactionReceiptsTable').on('click', '.fas.fa-money', function() {
              var transId = $(this).data('trans-id');
              addPayment(transId);
          });

           function addPayment(transId) {
              // Set the transaction ID in the form
              console.log('Delete details for transaction ID: ' + transId);
              $('#loanid').val(transId);
              // Show the modal
              $('#editmodal').modal('show');
          }
          // Handler for the double payment button

          $('#doublePaymentBtn').click(function() {
              $('.double-payment-section').toggle(); // Show/hide the double payment section
          });

            // Populate Payments Table
            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>' +
                     '<i class="fas fa-trash" data-pay-id="' + payment.pay_id + '"></i>&nbsp;' +
                  
                    '</tr>'
                );
            });
             $('#paymentsTable').on('click', '.fas.fa-trash', function() {
                var payId = $(this).data('pay-id');
                deletePayment(payId);
            });
            function deletePayment(payId) {
              Swal.fire({
                  title: 'Are you sure?',
                  text: "You want to delete this payment? This action is irreversible!",
                  icon: 'warning',
                  showCancelButton: true,
                  confirmButtonColor: '#3085d6',
                  cancelButtonColor: '#d33',
                  confirmButtonText: 'Yes, delete it!'
              }).then((result) => {
                  if (result.isConfirmed) {
                      // AJAX call to delete the payment
                      $.ajax({
                          url: 'database/delete_payment.kts.php',
                          type: 'POST',
                          data: { pay_id: payId },
                          success: function(response) {
                              // Handle success
                              Swal.fire('Deleted!', 'The payment has been deleted.', 'success');
                              // Optionally, reload the DataTable or remove the row from the table
                             location.reload();
                          },
                          error: function(xhr, status, error) {
                              // Handle error
                              Swal.fire('Error!', 'There was a problem deleting the payment.', 'error');
                          }
                      });
                  }
              });
          }
var roomSalesData;

if (response.sales.length === 0) {
    // Fetch data from room_sales table since there are no sales
    $.ajax({
        url: 'database/fetch_room_sales.kts.php',
        type: 'POST',
        data: { trans_id: response.transaction_receipts[0].trans_id },
        dataType: 'json',
        success: function(data) {
            roomSalesData = data;
            // Populate Sales Items Table with room sales data
            roomSalesData.forEach(function(roomSale) {
                $('#salesItemsTable tbody').append(
                    '<tr>' +
                    '<td>' + roomSale.rsid + '</td>' +
                    '<td>' + roomSale.trans_id + '</td>' +
                    '<td>' + roomSale.room_id + '</td>' +
                    '<td>' + roomSale.room_name + '</td>' +
                    '<td>' + roomSale.nod + '</td>' +
                    '<td>' + roomSale.room_price + '</td>' +
                    '<td>' + roomSale.subtotal + '</td>' +
                    '<td>' +
                    '<i class="fas fa-trash" data-rsid="' + roomSale.rsid + '"></i>&nbsp;' +
                    '<i class="fas fa-pencil roomedit" data-rsid="' + roomSale.rsid + '"></i>' +
                    '</td>' +
                    '</tr>'
                );
            });

            // Attach click event handler to room edit icon in the sales items table
            $('#salesItemsTable').on('click', '.roomedit', function(event) {
                // Prevent the default action
                event.preventDefault();

                // Get the room sale ID from the data attribute of the clicked icon
                var rsid = $(this).data('rsid');
                console.log(rsid);
                // Find the corresponding room sale in the room sales data
                var roomSale = roomSalesData.find(function(item) {
                    return item.rsid === rsid;
                });
                // Call the function to display the edit room sale modal with the room sale details
                editRoomSaleModal(roomSale);
            });
        },
        error: function(xhr, status, error) {
            console.error("An error occurred while fetching room sales data: " + error);
        }
    });
} else {
    // Populate Sales Items Table with existing sales data
    response.sales.forEach(function(sale) {
        $('#salesItemsTable tbody').append(
            '<tr>' +
            '<td>' + sale.sale_id + '</td>' +
            '<td>' + sale.trans_id + '</td>' +
            '<td>' + sale.product_id + '</td>' +
            '<td>' + sale.product_name + '</td>' +
            '<td>' + sale.quantity + '</td>' +
            '<td>' + sale.selling_price + '</td>' +
            '<td>' + sale.subtotal + '</td>' +
            '<td>' +
            '<i class="fas fa-trash" data-sale-id="' + sale.sale_id + '"></i>&nbsp;' +
            '<i class="fas fa-edit" data-sale-id="' + sale.sale_id + '"></i>' +
            '</td>' +
            '</tr>'
        );
    });
}

// Define a function to populate and display the edit room sales modal
function editRoomSaleModal(roomSale) {
    // Populate form fields with room sales details
    $('#rsid').val(roomSale.rsid);
    $('#transId').val(roomSale.trans_id);
    $('#roomId').val(roomSale.room_id);
    $('#roomName').val(roomSale.room_name);
    $('#nod').val(roomSale.nod);
    $('#roomPrice').val(roomSale.room_price);
    $('#subtotal').val(roomSale.subtotal);

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

          
           $('#salesItemsTable').on('click', '.fas.fa-trash', function() {
                var saleId = $(this).data('sale-id');
                deleteSale(saleId);
            });
            function deleteSale(saleId) {
              Swal.fire({
                  title: 'Are you sure?',
                  text: "You want to delete this sale item? This action is irreversible!",
                  icon: 'warning',
                  showCancelButton: true,
                  confirmButtonColor: '#3085d6',
                  cancelButtonColor: '#d33',
                  confirmButtonText: 'Yes, delete it!'
              }).then((result) => {
                  if (result.isConfirmed) {
                      // AJAX call to delete the payment
                      $.ajax({
                          url: 'database/delete_sale.kts.php',
                          type: 'POST',
                          data: { sale_id: saleId },
                          success: function(response) {
                              // Handle success
                              Swal.fire('Deleted!', 'The sale item has been deleted.', 'success');
                              // Optionally, reload the DataTable or remove the row from the table
                             location.reload();
                          },
                          error: function(xhr, status, error) {
                              // Handle error
                              Swal.fire('Error!', 'There was a problem deleting the sale item.', 'error');
                          }
                      });
                  }
              });
            }
 
            // Show the modal
            $('#orderDetailsModal').modal('show');
        },
        error: function(xhr, status, error) {
            console.error("An error occurred: " + error);
        }
      
   
    });
}


</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.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>
        // Use jQuery to make the AJAX request when the page loads
        $(document).ready(function () {
            $.ajax({
                type: 'POST',
                url: 'database/monthly_report.kts.php', // Create a PHP file to handle the AJAX request (monthly_report.php)
                dataType: 'json', // Expect JSON response
                success: function (data) {
                    // Update the HTML with the fetched data
                    if (data.success) {
                        $('#monthly-data').html(data.reportData);
                        $('#monthly-total').html(data.monthlyTotal);
                    } else {
                        // Handle errors here
                        alert(data.message);
                    }
                },
                error: function () {
                    // Handle AJAX errors here
                    alert('Error fetching data.');
                }
            });
        });
    </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>
    // JavaScript code to fetch data from the PHP script and display the chart
    function filterweekData() {
        var selectedYear = $("#yearSelect").val();

        // Make an AJAX request to the PHP script to fetch data for the selected year
        $.ajax({
            url: 'weekly_data.php',
            type: 'GET',
            data: { year: selectedYear },
            dataType: 'json',
            success: function(data) {
                // Retrieve the data from the JSON response
                var labels = data.labels;
                var cashData = data.cash_data;
                var tillData = data.till_data;
                var captainData = data.captain_data;
                var merchantData = data.merchant_data;
                var debtData = data.debt;

                // Get the chart canvas element
                var ctx = document.getElementById('barChart').getContext('2d');

                var salesChart = new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: labels,
                        datasets: [
                            {
                                label: "Till",
                                data: tillData,
                                borderColor: "rgba(0, 128, 0, 0.9)", // Green color
                                borderWidth: 0,
                                backgroundColor: "rgba(0, 128, 0, 0.5)" // Green color with transparency
                            },
                            {
                                label: "Cash",
                                data: cashData,
                                borderColor: "rgba(144, 104, 190, 0.9)",
                                borderWidth: 0,
                                backgroundColor: "rgba(144, 104, 190, 0.5)"
                            },
                            {
                                label: "Merchant",
                                data: merchantData,
                                borderColor: "rgba(0, 0, 255, 0.9)", // Blue color
                                borderWidth: 0,
                                backgroundColor: "rgba(0, 0, 255, 0.5)" // Blue color with transparency
                            },
                            {
                                label: "Captain",
                                data: captainData,
                                borderColor: "rgba(0, 0, 255, 0.9)", // Blue color
                                borderWidth: 0,
                                backgroundColor: "rgba(0, 0, 255, 0.5)" // Blue color with transparency
                            },
                            {
                                label: "Debt",
                                data: debtData,
                                borderColor: "rgba(255, 206, 86, 0.9)",
                                borderWidth: 0,
                                backgroundColor: "rgba(255, 206, 86, 0.5)"
                            }
                        ]
                    },
                    options: {
                        scales: {
                            yAxes: [{
                                ticks: {
                                    beginAtZero: true
                                }
                            }]
                        },
                        legend: {
                            display: true
                        }
                    }
                });
            }
        });
    }

    $(document).ready(function() {
        filterweekData();
    });
</script>

  <!--  Monthly Analysis -->
    <script>
        // JavaScript code to fetch data from the PHP script and display the chart
        function filterData() {
            var selectedYear = $("#yearSelect").val();

            // Make an AJAX request to the PHP script to fetch data for the selected year
            $.ajax({
                url: 'fetch_data.php',
                type: 'GET',
                data: { year: selectedYear },
                dataType: 'json',
                success: function(data) {
                    // Retrieve the data from the JSON response
                    var labels = data.labels;
                    var cashData = data.cash_data;
                    var tillData = data.till_data;
                    var captainData = data.captain_data;
                    var merchantData = data.merchant_data;
                    var debtData = data.debt;

                    // Create and update the chart using Chart.js
                    var ctx = document.getElementById('barChart2').getContext('2d');
                    var salesChart = new Chart(ctx, {
                        type: 'bar',
                        data: {
                            labels: labels,
                            datasets: [{
                                label: 'Cash Sales',
                                data: cashData,
                                borderColor: "rgba(144, 104, 190, 0.9)",
                                borderWidth: "1",
                                backgroundColor: "rgba(144, 104, 190, 0.5)"
                            }, 
                            {
                                label: 'Till Payments',
                                data: tillData,
                                borderColor: "rgba(0, 128, 0, 0.9)", // Green color
                                borderWidth: "1",
                                backgroundColor: "rgba(0, 128, 0, 0.5)" 
                            },
                            {
                                label: 'Merchant Payments',
                                data: merchantData,
                                borderColor: "rgba(0, 0, 255, 0.9)", // Blue color
                                borderWidth: "1",
                                backgroundColor: "rgba(0, 0, 255, 0.5)" // Blue color with transparency
                            },
                            {
                                label: 'Merchant Payments',
                                data: captainData,
                                borderColor: "rgba(255, 0, 0, 0.9)", // Ferrari red color
                                borderWidth: "1",
                                backgroundColor: "rgba(255, 0, 0, 0.5)" // Ferrari red color with transparency
                            },
                            {
                                label: 'Total Debt',
                                data: debtData,
                                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                                borderColor: 'rgba(255, 99, 132, 1)',
                                borderWidth: 1
                            }]
                        },
                        options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: true
                        }
                    }]
                },
                legend: {
                    display: true
                }
            }
                    });
                },
                error: function(xhr, status, error) {
                    console.log('Error fetching data:', xhr.responseText);
                }
            });
        }

        // Fetch data and display the chart on page load for the default selected year (if needed)
        // You can remove this part if you want the chart to be displayed only after selecting a year.
        $(document).ready(function() {
            filterData();
        });
    </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>
</body>

</html>