<?php
include("db/cn.php");

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'];
}

// Check connection
if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

// Check if the necessary POST variables are set
$product = isset($_POST['product']) ? $_POST['product'] : '';
$company = isset($_POST['company']) ? $_POST['company'] : '';
$startDate = isset($_POST['startDate']) ? $_POST['startDate'] : '';
$endDate = isset($_POST['endDate']) ? $_POST['endDate'] : '';

// Prepare SQL statement based on filters
$sql = "SELECT supplier_name, product_name, total_amount, product_price, date_time 
        FROM log_user_sales 
        WHERE 1=1";

if ($product != 'all') {
    $sql .= " || product_name = '$product'";
}

if ($company != 'all') {
    $sql .= " || supplier_name = '$company'";
}

$sql .= " AND date_time BETWEEN '$startDate' AND '$endDate'";

$result = $connection->query($sql);
$rows = array();

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
}

// Fetch product names
$productQuery = "SELECT name FROM products";
$productResult = $connection->query($productQuery);
$products = array();
if ($productResult->num_rows > 0) {
    while($row = $productResult->fetch_assoc()) {
        $products[] = $row['name'];
    }
}
// Fetch product names
$categoryQuery = "SELECT category FROM products";
$categoryResult = $connection->query($categoryQuery);
$categorys = array();
if ($categoryResult->num_rows > 0) {
    while($row1 = $categoryResult->fetch_assoc()) {
        $categorys[] = $row1['category'];
    }
}

// Fetch supplier names
$supplierQuery = "SELECT supplier_name FROM supplier";
$supplierResult = $connection->query($supplierQuery);
$suppliers = array();
if ($supplierResult->num_rows > 0) {
    while($row = $supplierResult->fetch_assoc()) {
        $suppliers[] = $row['supplier_name'];
    }
}
?>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sale Report</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<link rel="stylesheet" href="css/custom_css.css" />
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<style>
 #product-container-wrapper {
    max-height: 700px; /* Adjust the maximum height as needed */
    overflow-y: auto; /* Enable vertical scroll when content overflows */
}
/* Custom styles for sidebar */    /* Custom styles for sidebar */
    .sidebar {
        width: 100px;
        background: linear-gradient(360deg, #060606, #0A5064);
        position: fixed;
        bottom: 0;
        top: 60px;
        transition: transform 0.3s ease-in-out;
        transform: translateX(0);
        z-index: 1;
        height: 100%;
        border-radius: 0px;
		   transition: transform 0.3s ease-in-out, width 0.3s ease-in-out;
    }.sidebar.hide {
      transform: translateX(-100px); /* Move sidebar out of the viewport when it is hidden */
    }
      .sidebar .nav-item {
    padding: 10px 0 ;
    text-align: center;
    position: relative;
	font-size:12px;
}
    .sidebar .nav-link {
      color: #fff;
      position: relative; /* Ensure icon and text are positioned relative to the nav link */
      z-index: 2; /* Ensure the text and icon are above the hover background */
    }
    .sidebar .nav-link i {
      margin-bottom: 5px; /* Adjust the margin of the icon */
    }
    /* Custom styles for hover effect */
    .sidebar .nav-item:hover:after {
      background-color: #fff;
      content: '';
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 100%;
      z-index: 1; /* Ensure the hover background is below the text and icon */
    }
    .sidebar .nav-item:hover .nav-link {
      color: #0A5064;
    }
    /* Custom styles for divider */
    .sidebar .nav-item:after {
      content: "";
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 1px;
      background-color: #fff;
      transition: height 0.3s ease-in-out; /* Transition effect for smooth animation */
    }
    /* Custom styles for header */    .header {
        background: linear-gradient(270deg, #060606, #0A5064);
        color: #fff;
        padding: 10px;
        position: fixed;
        top: 0;
        width: 100%;
        z-index: 2;
        height: 69px;
        box-shadow: #FFF 2px 0px 0px 0px;
        /* Ensure header appears above sidebar */
    }
    .header .navbar-toggler {
      color: #fff;
    }
    .header .navbar-toggler-icon {
      color: #fff; /* Set the color of the toggle button to white */
    }
    .header .navbar-toggler.white {
      color: #fff !important; /* Ensure the toggle button is white */
    }
    .header .navbar-brand {
      color: #fff; /* Set navbar brand text color to white */
    }
    .header .nav-item .nav-link {
      color: #fff; /* Set nav link text color to white */
    }
    .main-content {
      margin-top: 50px; /* Height of fixed header + padding */
      margin-left: 100px; /* Width of sidebar */
      padding-top: 30px; /* Height of fixed header */
    }
	/* Custom styles for search bar */
    .search-container {
      display: flex;
      align-items: center;
      width: 300px;
      margin: 2px auto;
    }
    .search-input {
      width: 100%;
      padding: 10px 30px 10px 10px; /* Adjust padding to accommodate the icon */
      border: 1px solid #ccc;
      border-radius: 20px;
      font-size: 16px;
    }
    .search-icon {
      position: relative;
      left: -25px; /* Adjust the position of the icon */
      color: #aaa;
    }
    .search-icon i {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
.btn-dark
         {
			 background:#0A5064;
			 color:#fff;
			 border: 1px solid #0A5064;
                 	}
		.btn-dark:hover{
			background:#fff;
			 color:#0A5064;
			 border:1px solid #0A5064;
			}	
			.bg-dark2{
			background:#8A1218;
			color:#fff;	
				}	
	
	 .modal-content {
            animation: modal-animation 0.5s;
        }

        @keyframes modal-animation {
            from {
                opacity: 0;
                transform: scale(0.8);
            }
            to {
                opacity: 1;
                transform: scale(1);
            }
        }
		</style>
<body>

<?php include("common/hd.php"); ?>
<!-- Sidebar -->
<?php include("common/sd.php"); ?>
<div class="main-content">
<div class="container">
    <div class="row">
        <div class="col-sm-9">
            <h3 style="color:#212529;">Sale Report</h3>
        </div>
        <div class="col-sm-3">
            <button id="applyFiltersBtn" class="btn btn-primary" style="float: right;">Apply Filters</button>
        </div>
    </div>

    <div class="row">
        <div class="col-sm-3">
         <label for="companyDropdown">Supplier:</label>
            <select id="companyDropdown" class="form-control">
                <option value="all">All Suppliers</option>
                <?php foreach ($suppliers as $supplier) { ?>
                    <option value="<?php echo $supplier; ?>"><?php echo $supplier; ?></option>
                <?php } ?>
            </select>
            
        </div>
        <div class="col-sm-3">
            <label for="productDropdown">Company:</label>
            <select id="productDropdown" class="form-control">
                <option value="all">All Company</option>
                <?php foreach ($categorys as $category) { ?>
                    <option value="<?php echo $category; ?>"><?php echo $category; ?></option>
                <?php } ?>
            </select>
        </div>

        <div class="col-sm-2">
           <label for="productDropdown">Product:</label>
            <select id="productDropdown" class="form-control">
                <option value="all">All Products</option>
                <?php foreach ($products as $product) { ?>
                    <option value="<?php echo $product; ?>"><?php echo $product; ?></option>
                <?php } ?>
            </select>
        </div>

        <div class="col-sm-2">
            <label for="startDate">Start Date:</label>
            <input type="date" id="startDate" class="form-control" />
        </div>

        <div class="col-sm-2">
            <label for="endDate">End Date:</label>
            <input type="date" id="endDate" class="form-control" />
        </div>
    </div>
<br><br>
    <div class="row">
        <div class="col-sm-12">
            <table id="salesTable" class="table table-stripped table-hover">
                <thead>
                    <tr class="bg-dark text-white">
                        <th>Supplier Name</th>
                        <th>Product Name</th>
                        <th>Total Amount</th>
                        <th>Product Price</th>
                        <th>Date</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($rows as $row) { ?>
                        <tr>
                            <td><?php echo $row['supplier_name']; ?></td>
                            <td><?php echo $row['product_name']; ?></td>
                            <td><?php echo $row['total_amount']; ?></td>
                            <td><?php echo $row['product_price']; ?></td>
                            <td><?php echo $row['date_time']; ?></td>
                        </tr>
                    <?php } ?>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="2"><strong>Product Total</strong></td>
                        <td id="productTotal">0</td>
                        <td colspan="2"><strong>Total Amount Grand Sum: <span id="grandTotal">0</span></strong></td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>
<script>
document.addEventListener("DOMContentLoaded", function() {
    // Function to fetch data based on filters and populate the table
    function fetchSalesData() {
        var product = document.getElementById('productDropdown').value;
        var company = document.getElementById('companyDropdown').value;
        var startDate = document.getElementById('startDate').value;
        var endDate = document.getElementById('endDate').value;

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.DONE) {
                if (xhr.status === 200) {
                    var data = JSON.parse(xhr.responseText);
                    var tableBody = document.querySelector('#salesTable tbody');
                    tableBody.innerHTML = '';
                    var productTotal = 0;

                    data.forEach(function(row) {
                        var newRow = document.createElement('tr');
                        newRow.innerHTML = '<td>' + row.supplier_name + '</td>' +
                            '<td>' + row.product_name + '</td>' +
                            '<td>' + row.total_amount + '</td>' +
                            '<td>' + row.product_price + '</td>' +
                            '<td>' + row.date_time + '</td>';
                        tableBody.appendChild(newRow);
                        productTotal += parseFloat(row.total_amount);
                    });

                    document.getElementById('productTotal').textContent = productTotal.toFixed(2);
                    document.getElementById('grandTotal').textContent = productTotal.toFixed(2);
                } else {
                    console.error('Error fetching data');
                }
            }
        };

        xhr.open('POST', 'sale_report.php');
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.send('product=' + product + '&company=' + company + '&startDate=' + startDate + '&endDate=' + endDate);
    }

    // Fetch data when filters change
    var filters = document.querySelectorAll('#productDropdown, #companyDropdown, #startDate, #endDate');
    filters.forEach(function(filter) {
        filter.addEventListener('change', fetchSalesData);
    });

    // Initial fetch
    fetchSalesData();
});
</script>
</body>
</html>