<?php
include("db/cn.php");
ob_start();
if (isset($_SESSION['user_name']) && isset($_SESSION['user_role']) && isset($_SESSION['outlet_name']) && isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];
}

// Initialize filter variables
$start_date = "";
$end_date = "";
$order = "ASC"; // Default sorting order
$whereClause = "";

// Handle date filters
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $start_date = $_POST['start_date'] ?? "";
    $end_date = $_POST['end_date'] ?? "";

    // Validate dates
    if (!empty($start_date) && !empty($end_date)) {
        $whereClause = "WHERE date_time BETWEEN '$start_date' AND '$end_date'";
    }
}

// Handle sorting
if (isset($_GET['order']) && in_array($_GET['order'], ['ASC', 'DESC'])) {
    $order = $_GET['order'];
}

$query = "SELECT * FROM incash $whereClause ORDER BY date_time $order";
$rec = mysqli_query($connection, $query);

ob_end_flush();
?>
<!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, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>TAHIR ABBAS SPARY CENTER</title>

    <!-- Custom fonts for this template-->
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
   <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">

    <!-- Custom styles for this template-->
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<style>
 #table-container-wrapper {
    max-height: 660px; /* Adjust the maximum height as needed */
    overflow-y: auto; /* Enable vertical scroll when content overflows */
}
body {
    font-family: 'Quicksand', sans-serif;
    
}
		    .chart-container {
      position: relative;
      background: rgba(255, 255, 255, 0.9);
      border-radius: 10px;
      padding: 15px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }

    canvas {
      max-width: 100%;
      height: auto;
    }
.bg-gradient-primary{
    
	background:#0A4657;
	color:#fff;	
	
	}

.btn-primary{
	background:#0A4657;
	color:#fff;
	 border:1px #0A4657 solid;
	
	}  
.btn-primary:hover{
  
  background:#fff;
  border:1px #0A4657 solid;
	color:#0A4657;
	
	}	 
    .chart-container {
      position: relative;
      background: rgba(255, 255, 255, 0.9);
      border-radius: 10px;
      padding: 15px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }

    canvas {
      max-width: 100%;
      height: auto;
    }
	
	.fa-download:hover{
		color:#953E39;
		}
		
.select{
    font-weight:500;
    color:#000;
	  	
		}
		label{
		    font-weight:700;
		    color:#000;
		}
  </style>

<body id="page-top">

    <!-- Page Wrapper -->
    <div id="wrapper">

        <!-- Sidebar -->
        <?php
        include("common/sd.php");
		?>
        <!-- End of Sidebar -->

        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">

            <!-- Main Content -->
            <div id="content">

                <!-- Topbar -->
                <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">

                    <!-- Sidebar Toggle (Topbar) -->
                    <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
                        <i class="fa fa-bars"></i>
                    </button>

                    <!-- Topbar Search -->
                    
  <?php include('common/log.php');  ?>

                    <!-- Topbar Navbar -->
                    
                </nav>
<div class="container-fluid mt-5">
    <div class="row">
        <div class="col-sm-9">
               <h2 style="color:#060606; font-weight:700;">Expense Report</h2>  
        </div>
       
        <div class="col-sm-3"></div>
    </div>
    <br>
   
  
    <div class="row">
        <div class="col-sm-12">
            
              <form method="POST" action="">
                        <div class="row">
                            <div class="form-group col-3">
                                <label for="start_date">Start Date:</label>
                                <input type="date" id="start_date" name="start_date" class="form-control select" value="<?php echo $start_date; ?>">
                            </div>
                            <div class="form-group col-3">
                                <label for="end_date">End Date:</label>
                                <input type="date" id="end_date" name="end_date" class="form-control select" value="<?php echo $end_date; ?>">
                            </div>
                            <div class="form-group col-4" style="margin-top:30px;">
                                <button type="submit" class="btn btn-dark">Filter</button>
                                  <button type="button" class="btn btn-dark" id="downloadExcel">Download</button>
                                <a href="report_exp.php"><button type="button" class="btn btn-dark"><i class="fas fa-sync-alt fa-1x"></i></button></a>
                           
                            </div>
                        </div>
                    </form>
            
        </div>
    </div>
 
</div>
<div class="container-fluid" id="table-container-wrapper">
<table id="patientTable" class="table table-bordered table-hover text-center bg-white text-capitalize ">
                        <tr class="bg-dark text-white" style="font-weight:700;">
                            <td>Sr#</td>
                            <td>
                                <a href="?order=<?php echo $order === 'ASC' ? 'DESC' : 'ASC'; ?>" style="color: #fff; text-decoration: none;">
                                    Date <i class="fas fa-sort-<?php echo $order === 'ASC' ? 'up' : 'down'; ?>"></i>
                                </a>
                            </td>
                            <td style="background:#0A4657; color:#fff;">Expence</td>
                            <td>Detail</td>
                            <td>Amount (Rs)</td>
                            <td>Method</td>
                            <td>By.</td>
                        </tr>
                        <?php
                        $sr_no = 1;
                        while ($row = mysqli_fetch_array($rec)) {
                        ?>
                            <tr style="color:#000;">
                                <td><?php echo $sr_no++; ?></td>
                                <td><?php echo $row["date_time"]; ?></td>
                                <td style="font-weight:700;color:#0A4657;"><?php echo $row["name_detail"]; ?></td>
                                <td><?php echo $row["desc_name"]; ?></td>
                                <td style="font-weight:700;color:#666;"><?php echo $row["amount"]; ?></td>
                                <td><?php echo $row["paid_by"]; ?></td>
                                <td><?php echo $row["login_user"]; ?></td>
                            </tr>
                        <?php } ?>
                    </table>

</div>



    
            
                <!-- /.container-fluid -->

            </div>
            <br><br>
            <!-- End of Main Content -->

            <!-- Footer -->
            <?php include("common/main_ft.php");  ?>
            <!-- End of Footer -->

        </div>
        <!-- End of Content Wrapper -->

    </div>
    <!-- End of Page Wrapper -->

    <!-- Scroll to Top Button-->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <!-- Logout Modal-->
    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                    <a class="btn btn-primary" href="">Logout</a>
                </div>
            </div>
        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.9/xlsx.full.min.js"></script>

<!-- JavaScript for exporting the table data to Excel -->
<script>
    document.getElementById('downloadExcel').addEventListener('click', function() {
        // Get the table element
        var table = document.getElementById('patientTable');

        // Clean the table to avoid potential issues with hidden rows or formatting
        var clone = table.cloneNode(true); // Clone the table
        var rows = clone.querySelectorAll('tr');

        // Remove hidden or empty rows if necessary
        rows.forEach(function(row) {
            if (row.style.display === 'none' || row.innerText.trim() === '') {
                row.remove();
            }
        });

        // Convert the table into a worksheet using SheetJS
        var workbook = XLSX.utils.table_to_book(clone, { sheet: "Patients" });

        // Export the Excel file with a proper name
        try {
            XLSX.writeFile(workbook, 'ExpenseReport_data.xlsx');
        } catch (error) {
            console.error("Error while writing the file: ", error);
            alert("Error generating Excel file. Please check if the SheetJS library is properly loaded.");
        }
    });
</script>  
      
   <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></script>
    <!-- Bootstrap core JavaScript-->
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Core plugin JavaScript-->
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>

    <!-- Custom scripts for all pages-->
    <script src="../js/sb-admin-2.min.js"></script>

</body>

</html>