
<!----------------------------------Login------------------------------------>
<?php
include 'php/db_connection.php';

// শুধুমাত্র লগইন করা ইউজার পেজ দেখতে পারবে
if (!isset($_SESSION['user_id'])) {
    header("Location: pos/login.php");
    exit();
}

$userName = $_SESSION['user_name'];
$role = $_SESSION['role']; // ✅ এখানে role সেভ করা হচ্ছে
$userId = $_SESSION['user_id'];


$isAdmin = ($_SESSION['role'] == 'admin');

?>

<!---------------------------------কন্টেন------------------------------------>
<?php
// Function to get aggregated product data
function getProductAggregatedData() {
    global $con; // Use the global database connection

    // Query to fetch total quantity and total price grouped by Product ID
    $query = "
        SELECT 
            product_id, 
            SUM(quantity) AS total_quantity, 
            SUM(price * quantity) AS total_price 
        FROM sales_items 
        GROUP BY product_id";
    
    $result = mysqli_query($con, $query);
    
    // Return results if any rows found, otherwise return an empty array
    if ($result && mysqli_num_rows($result) > 0) {
        return mysqli_fetch_all($result, MYSQLI_ASSOC);
    }
    return [];
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Product Report</title>
    <script>
        function printProductReport(productId) {
            var url = "print_product_report.php?product_id=" + productId;
            window.open(url, "_blank");
        }
    </script>
</head>
<body>

<h2 style="text-align: center;">Product Report</h2>

<!-----------------------------------Product Report Table---------------------------------->
<table>
    <thead>
        <tr>
            <th>Product ID</th>
            <th>Total Quantity</th>
            <th>Total Price</th>
            <th style="text-align: center;">Action</th>
        </tr>
    </thead>
    <tbody>
        <?php
        $productDataList = getProductAggregatedData();

        if (count($productDataList) > 0) {
            foreach ($productDataList as $productData) {
                ?>
                <tr>
                    <td><?php echo htmlspecialchars($productData['product_id']); ?></td>
                    <td><?php echo number_format($productData['total_quantity']); ?></td>
                    <td><?php echo number_format($productData['total_price'], 2); ?></td>
                    <td style="text-align: center;">
                        <button onclick="printProductReport('<?php echo $productData['product_id']; ?>')" class="print-button">Print</button>
                    </td>
                </tr>
                <?php
            }
        } else {
            ?>
            <tr>
                <td colspan="4" style="text-align: center;">No data available</td>
            </tr>
            <?php
        }
        ?>
    </tbody>
</table>

</body>
</html>
