<?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>

                         

                            <div class="iq-card-body" style="overflow:auto;">
                            <div class="row mt-5">
    <div class="col-lg-4">
        <input type="date" id="fromDate" class="form-control">
    </div>
    <div class="col-lg-4">
        <input type="date" id="toDate" class="form-control" value="<?php echo date('Y-m-d'); ?>">
    </div>
    <div class="col-lg-3">
            <select id="brandFilter" class="form-control">
                <option value="">All Brands</option>
                <?php
                $brands = $conn->query("SELECT id, name FROM brands ORDER BY name ASC");
                while ($b = $brands->fetch(PDO::FETCH_ASSOC)) {
                    echo '<option value="' . htmlspecialchars($b['id']) . '">' . htmlspecialchars($b['name']) . '</option>';
                }
                ?>
            </select>
        </div>
    <div class="col-lg-4 mt-2">
        <button id="filterButton" class="btn btn-primary">Filter</button>
            <a href="purchase_season_report.php" class="btn btn-secondary" id="clearFilterButton">Clear Filter</a>

    </div>
</div>
   <div class="col-lg-4 mt-4">
<input type="search" placeholder="Search here......." class="form-control mt-3" id="searchInput">
</div>
<br>
<button id="printButton" class="btn btn-primary" style="margin-bottom: 10px;">🖨️ Print Report</button>
<script>
    document.getElementById('printButton').addEventListener('click', function () {
        const printContent = document.getElementById('productTable').outerHTML;
        const originalContent = document.body.innerHTML;

        document.body.innerHTML = `
            <html>
            <head>
                <title>Print Report</title>
                <style>
                    table {
                        width: 100%;
                        border-collapse: collapse;
                        font-size: 12px;
                    }
                    table th, table td {
                        border: 1px solid #000;
                        padding: 6px;
                        text-align: left;
                    }
                    th {
                        background-color: #f2f2f2;
                    }
                    input[type="checkbox"] {
                        display: none;
                    }
                </style>
            </head>
            <body>
                <h2 style="text-align: center;">Stock Report</h2>
                ${printContent}
            </body>
            </html>
        `;

        window.print();
        document.body.innerHTML = originalContent;
        location.reload(); // reload to restore interactivity
    });
</script>
       <table class="table table-hover table-bordered mt-3" id="productTable">
    <thead>
        <tr>
         <th>Date Purchase</th>
            <th>Product</th>
            <th>Supplier</th>
            <th>Reference No</th>
            <th>Quantity</th>
            <th>Unit Price</th>
            <th>Sub Total</th>
        </tr>
    </thead>
    <tbody></tbody>
    <tfoot class="table-light font-weight-bold">
        <tr>
            <td colspan="4" class="text-right">Total:</td>
            <td id="totalQuantity" class="text-end"></td>
            <td></td>
            <td id="totalSubtotal" class="text-end"></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 || 0).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} ₨`;
    }

    function fetchPurchaseReport(fromDate = '', toDate = '', brand_id = '') {
        $.ajax({
            url: 'fetch_purchase_season_report.php',
            method: 'GET',
            data: { fromDate, toDate, brand_id }, 
            dataType: 'json',
            success: function (data) {
                const tbody = $('#productTable tbody');
                tbody.empty();

                let totalQuantity = 0;
                let totalSubtotal = 0;

                if (data.error) {
                    tbody.html(`<tr><td colspan="7" class="text-danger text-center">${data.error}</td></tr>`);
                    $('#totalQuantity').text('0.00');
                    $('#totalSubtotal').text(formatCurrency(0));
                    return;
                }

                data.forEach(row => {
                    const quantity = parseFloat(row.QuantityValue || 0);
                    const unitPrice = parseFloat((row.UnitPurchasePrice || '0').replace(/,/g, ''));
                    const subTotal = parseFloat((row.SubTotal || '0').replace(/,/g, ''));

                    totalQuantity += quantity;
                    totalSubtotal += subTotal;

                    tbody.append(`
                        <tr>
                        <td>${row.Date ? new Date(row.Date).toLocaleDateString('en-GB') : '-'}</td>
                            <td>${row.Product}</td>
                            <td>${row.Supplier}</td>
                            <td>${row.ref_no}</td>
                            <td class="text-end">${quantity.toFixed(2)}</td>
                            <td class="text-end">${formatCurrency(unitPrice)}</td>
                            <td class="text-end">${formatCurrency(subTotal)}</td>
                        </tr>
                    `);
                });

                $('#totalQuantity').text(totalQuantity.toFixed(2));
                $('#totalSubtotal').text(formatCurrency(totalSubtotal));
            },
            error: function (xhr, status, error) {
                console.error("AJAX Error:", error);
                $('#productTable tbody').html(`<tr><td colspan="7" class="text-danger text-center">Error fetching data.</td></tr>`);
            }
        });
    }

    fetchPurchaseReport();

    $('#filterButton').on('click', function () {
        const fromDate = $('#fromDate').val();
        const toDate = $('#toDate').val();
        const brand_id = $('#brandFilter').val();
        fetchPurchaseReport(fromDate, toDate, brand_id);
    });
    
$('#searchInput').on('keyup', function () {
    const value = $(this).val().toLowerCase();
    let totalQuantity = 0;
    let totalSubtotal = 0;

    $('#productTable tbody tr').filter(function () {
        const match = $(this).text().toLowerCase().includes(value);
        $(this).toggle(match);

        if (match) {
            const qty = parseFloat($(this).find('td').eq(4).text()) || 0;
            const subtotalText = $(this).find('td').eq(6).text().replace(/[^0-9.-]+/g, '');
            const subtotal = parseFloat(subtotalText) || 0;

            totalQuantity += qty;
            totalSubtotal += subtotal;
        }
    });

    $('#totalQuantity').text(totalQuantity.toFixed(2));
    $('#totalSubtotal').text(formatCurrency(totalSubtotal));
});

});
</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>