<?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'];
}
ob_end_flush();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sale Report</title>
    <!-- Bootstrap CSS -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <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" />
</head>
<style>
 #table-container-wrapper {
    max-height: 460px; /* Adjust the maximum height as needed */
    overflow-y: auto; /* Enable vertical scroll when content overflows */
}


@media (max-width: 880px) {
    .col-4 {
        width: 33.33% !important;
    }
    .fa-wifi {
        display: none !important;
    }
    .col-6 {
        width: 50% !important;
    }
}

@media (min-width: 880px) {
    .sidebar {
        width: 100%;
        /* Change sidebar width to 100% on mobile */
        max-width: 120px; /* Set maximum width for the sidebar */
    }
}

@media (min-width: 880px) {
    .main-content {
        margin-left: ; /* Width of the sidebar */
    }
}

/* Added new class to control overlay */
.overlay {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.6);
    z-index: 999;
    display: none; /* Initially hidden */
}
    /* Custom styles for sidebar */
    .sidebar {
        width: 100px;
       background: linear-gradient(360deg, #060606, #3C2F23);
        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: #503F2E;
    }

    /* 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(90deg, #3C2F23, #060606);
        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 */
    margin-left: 70px; /* Initially, set margin-left to 0 */
    padding-top: 30px; /* Height of fixed header */
    transition: margin-left 0.3s ease-in-out; /* Add transition for smoother animation */
}


    /* Custom styles for search bar */
    .search-container {
        display: flex;
        align-items: center;
       width:100%;
        margin: 2px auto;


        float:left;
	}

/* Updated hide class to apply to the overlay */
.sidebar.hide, .overlay.hide {
    transform: translateX(-100%);
}

    .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: #503F2E;
        color: #fff;
        border: 1px solid #503F2E;
    }

    .btn-dark:hover {
        background: #fff;
        color: #503F2E;
        border: 1px solid #503F2E;
    }

    .bg-dark2 {
        background: #503F2E;
        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>

</style>

<body>

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

    // Fetch distinct customer names
    $rec_customer_names = mysqli_query($connection, "SELECT DISTINCT customer_name FROM log_user_sales");

    // Fetch other filter options
    $rec_suplier_name = mysqli_query($connection, "SELECT DISTINCT supplier FROM products");
    $rec_suplier_company = mysqli_query($connection, "SELECT DISTINCT company FROM products");
    $rec_suplier_company_category = mysqli_query($connection, "SELECT DISTINCT category FROM products");
    $rec_products = mysqli_query($connection, "SELECT DISTINCT product_name FROM products");

    // Fetch filter parameters from the form
    $supplier = isset($_POST['supplier']) ? $_POST['supplier'] : '';
    $company = isset($_POST['company']) ? $_POST['company'] : '';
    $product = isset($_POST['product']) ? $_POST['product'] : '';
    $company_category = isset($_POST['company_category']) ? $_POST['company_category'] : '';
    $customer_name = isset($_POST['customer_name']) ? $_POST['customer_name'] : '';
    $startDate = isset($_POST['startDate']) ? $_POST['startDate'] : '';
    $endDate = isset($_POST['endDate']) ? $_POST['endDate'] : '';

    // Base SQL query
    $sql = "SELECT 
                SUM(product_quantity) AS total_quantity, 
                SUM(net_amount) AS total_amount  
            FROM 
                log_user_sales 
            WHERE 1=1 ";

    // Add filters based on selected options
    if (!empty($supplier)) {
        $sql .= " AND supplier_name = '$supplier'";
    }
    if (!empty($company_category)) {
        $sql .= " AND company = '$company_category'";
    }
    if (!empty($product)) {
        $sql .= " AND product_name = '$product'";
    }
    if (!empty($customer_name)) {
        $sql .= " AND customer_name = '$customer_name'";
    }
    if (!empty($startDate) && !empty($endDate)) {
        $sql .= " AND date_time BETWEEN '$startDate' AND '$endDate'";
    }

    // Execute the query
    $sum_result = mysqli_query($connection, $sql);
    $row = mysqli_fetch_assoc($sum_result);

    // Checking if the keys exist before accessing them
    $total_quantity = isset($row['total_quantity']) ? $row['total_quantity'] : 0;
    $total_amount = isset($row['total_amount']) ? $row['total_amount'] : 0;

    $final = $total_quantity != 0 ? $total_amount / $total_quantity : "Undefined";

    // Execute the main query
    $sql = "SELECT * FROM log_user_sales WHERE 1=1 ";
    if (!empty($supplier)) {
        $sql .= " AND supplier_name = '$supplier'";
    }
    if (!empty($company_category)) {
        $sql .= " AND company = '$company_category'";
    }
    if (!empty($product)) {
        $sql .= " AND product_name = '$product'";
    }
    if (!empty($customer_name)) {
        $sql .= " AND customer_name = '$customer_name'";
    }
    if (!empty($startDate) && !empty($endDate)) {
        $sql .= " AND date_time BETWEEN '$startDate' AND '$endDate'";
    }

    $rec_purchases = mysqli_query($connection, $sql);
    ?>


<div class="main-content">
    
<div class="container mt-5">
    <div class="row">
        <div class="col-sm-3">
               <h3 style="width:305px; height:66px; text-align:center; background:#503F2E; color:#fff; padding:12px; border-radius:10px;">Sales Report</h3>  
        </div>
        <div class="col-sm-6"></div>
        <div class="col-sm-3">
             <a href="report_p.php" class="btn btn-dark" style="margin-top:10px;float:right;">Back</a>
        </div>
    </div>
    <br>
       

    <form method="post">
        <div class="row">
            <!-- Customer Name Filter -->
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="customer_name">Customer Name:</label>
                        <select class="form-control" name="customer_name">
                            <option value="">Select Customer</option>
                            <?php while ($row_customer = mysqli_fetch_array($rec_customer_names)) { ?>
                                <option value="<?php echo $row_customer['customer_name']; ?>" 
                                <?php echo ($row_customer['customer_name'] == $customer_name) ? 'selected' : ''; ?>>
                                    <?php echo $row_customer['customer_name']; ?>
                                </option>
                            <?php } ?>
                        </select>
                    </div>
                </div>
            <div class="col-md-3">
                <div class="form-group">
                    <label for="supplier">Supplier Name:</label>
                    <select class="form-control" name="supplier">
                        <option value="">Select Supplier</option>
                        <?php while($row_supplier_name = mysqli_fetch_array($rec_suplier_name)){ ?>
                            <option value="<?php echo $row_supplier_name['supplier'];?>"><?php echo $row_supplier_name['supplier'];?></option>
                        <?php } ?>
                    </select>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    <label for="company">Supplier Company:</label>
                    <select class="form-control" name="company">
                        <option value="">Select Company</option>
                        <?php while($row_supplier_company = mysqli_fetch_array($rec_suplier_company)){ ?>
                            <option value="<?php echo $row_supplier_company['company'];?>"><?php echo $row_supplier_company['company'];?></option>
                        <?php } ?>
                    </select>
                </div>
            </div>
           
            <div class="col-md-3">
                <div class="form-group">
                    <label for="product">Category</label>
                    <select class="form-control" name="company_category">
                        <option value="">Select Category</option>
                        <?php while($row_supplier_category = mysqli_fetch_array($rec_suplier_company_category)){ ?>
                            <option value="<?php echo $row_supplier_category['category'];?>"><?php echo $row_supplier_category['category'];?></option>
                        <?php } ?>
                    </select>
                </div>
            </div>
             
        </div>
                
        <div class="row">
            <div class="col-md-3">
                <div class="form-group">
                    <label for="product">Product Name:</label>
                    <select class="form-control" name="product">
                        <option value="">Select Product</option>
                        <?php while($row_products = mysqli_fetch_array($rec_products)){ ?>
                            <option value="<?php echo $row_products['product_name'];?>"><?php echo $row_products['product_name'];?></option>
                        <?php } ?>
                    </select>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    <label for="startDate">Start Date:</label>
                    <input type="date" class="form-control" name="startDate">
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    <label for="endDate">End Date:</label>
                    <input type="date" class="form-control" name="endDate">
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    
                    <button type="submit" class="btn btn-dark " style="margin-top:30px;" name="filter">Filter</button>
                    <button id="downloadExcel" class="btn btn-dark " style="margin-top:30px;">Download </button>
                    <a href="report_s.php"><button type="button" class="btn btn-dark" style="margin-top:30px;"><i class="fas fa-sync-alt fa-1x"></i></button></a>

                </div>
            </div>
        </div>
        
        <div class="col-sm-12 " id="table-container-wrapper">
            <table id="patientTable"  class="table table-stripped table-hover text-center table-sm">
                <thead>
                    <tr class="bg-dark text-white">
                        <th>Date</th>
                        <th>Supplier</th>
                        <th>Company</th>                 
                        <th>Product Name</th>
                        <th>Total Quantity </th>
                        <th>Total Amount(Rs)</th>
                        <th>Sale Price.(Rs)</th>
                    </tr>
                </thead>
                    
                <tbody>
                    <?php
					ob_start();
					 while($row = mysqli_fetch_array($rec_purchases)) { ?>
                        <tr>
                            <td><?php echo $row['date_time']; ?></td>
                            <td class="text-capitalize"><?php echo $row['supplier_name']; ?></td>
                            
                            
                            <td class="text-capitalize"><?php echo $row['company']; ?></td>
                            <td class="text-capitalize"><?php echo $row['product_name']; ?></td>
                            <td><?php echo $row['product_quantity'];?></td>
                            <td><?php echo $row['net_amount']; ?></td>
                                
                            <td><?php
                                $total_quantity2 = (int)$row["product_quantity"];
                                $total_amount2 = (int)$row["product_price"];
                                if ($total_quantity2 != 0) {
                                    $in_tr = $total_amount2 / $total_quantity2;
                                } else {
                                    $in_tr = "Undefined";
                                }
                                echo $in_tr;
                            ?></td>
                        </tr>
                    <?php } 
					ob_end_flush();
					?>
                </tbody>
            </table>
        </div>
        <div class="row">
            <div class="col-sm-12">
                <table class="table">
                    <tfoot>
                        <tr>
                            <th>Total Quantity :</th>
                            <td><?php echo $total_quantity; ?></td>
                        </tr>
                        <tr>
                            <th>Total Amount:</th>
                            <td>Rs <?php
// Assuming you have a valid connection to the database in $connection
$query = mysqli_query($connection, "SELECT net_amount  FROM log_user_sales ");

// Initialize total sum variable
$total_sum = 0;

// Fetch rows from the query result set
while ($row = mysqli_fetch_assoc($query)) {
    // Multiply quantity by trade_price and add to total sum
    $total_sum += $row['net_amount'] ;

    // Echo the result for each row if needed
    echo '';
}

// Output the final total sum
echo ' ' . $total_sum;
?></td>
                        </tr>
                        
                    </tfoot>
                </table>
            </div>
        </div>
    </form>
</div>
</div>
</body>
<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, 'Sales_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>
</html>