<?php
include 'includes/config.php';
session_start();

if (!$_SESSION['email']) {
    header('location:login.php');
}
?>
<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Product Purchase Report</title>
    <!-- Favicon -->
    <link rel="shortcut icon" href="images/favicon.ico" />
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <!-- Typography CSS -->
    <link rel="stylesheet" href="css/typography.css">
    <!-- Style CSS -->
    <link rel="stylesheet" href="css/style.css">
    <!-- Responsive CSS -->
    <link rel="stylesheet" href="css/responsive.css">
    <style>
        ion-icon {
            font-size: 20px;
            margin-bottom: -5px;
        }
    </style>
</head>

<body>
    <!-- loader Start -->
    <div id="loading">
        <div id="loading-center">
        </div>
    </div>
    <!-- loader END -->
    <!-- Wrapper Start -->
    <div class="wrapper">
        <!-- Sidebar  -->
        <?php
        include 'includes/sidebar.php';
        ?>
        <!-- TOP Nav Bar -->
        <?php include 'includes/header.php'; ?>
        <!-- TOP Nav Bar END -->
        <!-- Page Content  -->
        <div id="content-page" class="content-page">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-sm-12">
                        <div class="iq-card">
                            <div class="iq-card-header d-flex justify-content-between row">
                                <div class="iq-header-title col-lg-6">
                                    <h4 class="card-title">Product Purchase Report</h4>
                                </div>
                            </div>

                            <!-- Searchbar -->
                            <div class="row mt-5">
                                <div class="col-lg-2"></div>
                                <div class="col-lg-8">
                                    <input type="search" placeholder="Search here......." class="form-control" id="searchInput">
                                </div>
                            </div>

                            <div class="iq-card-body" style="overflow:auto;">
                                <table class="table table-hover table-bordered">
                                    <thead>
                                        <tr>
                                            <th>Product</th>
                                            <th>Supplier</th>
                                            <th>Reference No</th>
                                            <th>Date</th>
                                            <th>Quantity</th>
                                            <th>Unit Purchase Price</th>
                                            <th>Sub Total</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- Data will be populated here by JavaScript -->
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <td colspan="4"><strong>Total</strong></td>
                                            <td id="totalQuantity">0</td>
                                            <td></td>
                                            <td id="totalSubtotal">0 ₨</td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script>
            $(document).ready(function() {
                function formatCurrency(value) {
                    return `${Number(value).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} ₨`;
                }

                function fetchPurchaseReport() {
                    $.ajax({
                        url: 'fetch_purchase_report.php',
                        method: 'GET',
                        dataType: 'json',
                        success: function(data) {
                            let tableBody = $('table tbody');
                            let totalQuantity = 0;
                            let totalSubtotal = 0;

                            tableBody.empty();

                            data.forEach(row => {
                                let quantity = parseFloat(row.QuantityValue);
                                let unitPrice = parseFloat(row.UnitPurchasePrice.replace(/,/g, '')); 
                                let subTotal = parseFloat(row.SubTotal.replace(/,/g, '')); 
                                totalQuantity += quantity;
                                totalSubtotal += subTotal;

                                let formattedUnitPrice = `${unitPrice.toFixed(2)} ₨`;
                                let formattedSubTotal = formatCurrency(subTotal);

                                let tableRow = `
                        <tr>
                            <td>${row.Product}</td>
                            <td>${row.Supplier}</td>
                            <td>${row.ref_no}</td>
                            <td>${row.Date}</td>
                            <td>${quantity.toFixed(2)}</td>
                            <td>${formattedUnitPrice}</td>
                            <td>${formattedSubTotal}</td>
                        </tr>
                    `;
                                tableBody.append(tableRow);
                            });

                            // Update footer with totals
                            $('#totalQuantity').text(totalQuantity.toFixed(2));
                            $('#totalSubtotal').text(formatCurrency(totalSubtotal));
                        },
                        error: function(xhr, status, error) {
                            console.error("Error fetching data:", error);
                        }
                    });
                }

                fetchPurchaseReport();

                $('#searchInput').on('keyup', function() {
                    const value = $(this).val().toLowerCase();
                    $('table tbody tr').filter(function() {
                        $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
                    });
                });
            });
        </script>

        <!-- Wrapper END -->
        <!-- Footer -->
        <footer class="iq-footer">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-lg-6">
                        <ul class="list-inline mb-0">
                            <li class="list-inline-item"><a href="privacy-policy.html">Privacy Policy</a></li>
                            <li class="list-inline-item"><a href="terms-of-service.html">Terms of Use</a></li>
                        </ul>
                    </div>
                    <div class="col-lg-6 text-right">
                        Copyright <span id="copyright">
                            <script>
                                document.getElementById('copyright').appendChild(document.createTextNode(new Date()
                                    .getFullYear()))
                            </script>
                        </span> <a href="#">Vito</a> All Rights Reserved.
                    </div>
                </div>
            </div>
        </footer>
        <nav class="iq-float-menu">
            <input type="checkbox" href="#" class="iq-float-menu-open" name="menu-open" id="menu-open" />
            <label class="iq-float-menu-open-button" for="menu-open">
                <span class="lines line-1"></span>
                <span class="lines line-2"></span>
                <span class="lines line-3"></span>
            </label>
            <button class="iq-float-menu-item bg-info" data-toggle="tooltip" data-placement="top" title="Direction Mode"
                data-mode="rtl"><i class="ri-text-direction-r"></i></button>
            <button class="iq-float-menu-item bg-danger" data-toggle="tooltip" data-placement="top" title="Color Mode"
                id="dark-mode" data-active="true"><i class="ri-sun-line"></i></button>
            <button class="iq-float-menu-item bg-warning" data-toggle="tooltip" data-placement="top" title="Comming Soon"><i
                    class="ri-palette-line"></i></button>
        </nav>
        <!-- Footer END -->
        <!-- Optional JavaScript -->
        <!-- jQuery first, then Popper.js, then Bootstrap JS -->
        <script src="js/jquery.min.js"></script>
        <!-- Rtl and Darkmode -->
        <script src="js/rtl.js"></script>
        <script src="js/customizer.js"></script>
        <script src="js/popper.min.js"></script>
        <script src="js/bootstrap.min.js"></script>
        <!-- Appear JavaScript -->
        <script src="js/jquery.appear.js"></script>
        <!-- Countdown JavaScript -->
        <script src="js/countdown.min.js"></script>
        <!-- Counterup JavaScript -->
        <script src="js/waypoints.min.js"></script>
        <script src="js/jquery.counterup.min.js"></script>
        <!-- Wow JavaScript -->
        <script src="js/wow.min.js"></script>
        <!-- Apexcharts JavaScript -->
        <script src="js/apexcharts.js"></script>
        <!-- Slick JavaScript -->
        <script src="js/slick.min.js"></script>
        <!-- Select2 JavaScript -->
        <script src="js/select2.min.js"></script>
        <!-- Owl Carousel JavaScript -->
        <script src="js/owl.carousel.min.js"></script>
        <!-- Magnific Popup JavaScript -->
        <script src="js/jquery.magnific-popup.min.js"></script>
        <!-- Smooth Scrollbar JavaScript -->
        <script src="js/smooth-scrollbar.js"></script>
        <!-- lottie JavaScript -->
        <script src="js/lottie.js"></script>
        <!-- Chart Custom JavaScript -->
        <script src="js/chart-custom.js"></script>
        <!-- Custom JavaScript -->
        <script src="js/custom.js"></script>
</body>

</html>