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

// error_reporting(E_ALL);
// ini_set('display_errors', 1);


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>View Products</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;
        }

        .custom_select {
            position: relative;
            display: inline-block;
        }

        .select-button {
            background-color: #007BFF;
            color: white;
            padding: 4px 8px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 70px;
            text-align: left;
        }

        .arrow {
            margin-left: 3px;
        }

        .select-options {
            display: none;
            position: absolute;
            background-color: #f9f9f9;
            min-width: 120px;
            box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
            z-index: 1;
            border-radius: 4px;
            top: 100%;
            left: 0;
        }

        .select-options a {
            color: black;
            padding: 6px 10px;
            text-decoration: none;
            display: block;
            font-size: 12px;
        }

        .select-options a:hover {
            background-color: #f1f1f1;
        }

        /* Style for the popup background overlay */
        .popup {
            display: none;
            /* Hidden by default */
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            /* Semi-transparent background */
            z-index: 1000;
            /* Ensure it's above other content */
            overflow: auto;
            /* Scroll if needed */
        }

        /* Style for the popup content box */
        .popup-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            /* Center the box */
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            /* Rounded corners */
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            /* Shadow effect */
            width: 90%;
            max-width: 500px;
            /* Responsive max width */
            box-sizing: border-box;
            /* Include padding in width calculation */
        }

        /* Close button styling */
        .close {
            position: absolute;
            top: 10px;
            right: 10px;
            font-size: 24px;
            font-weight: bold;
            color: #333;
            cursor: pointer;
            transition: color 0.3s;
        }

        .close:hover {
            color: #e74c3c;
            /* Change color on hover */
        }

        /* Styling for headings */
        .popup-content h2 {
            margin-top: 0;
            font-size: 24px;
            color: #333;
        }

        /* Table styling */
        .popup-content table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }

        .popup-content th,
        .popup-content td {
            padding: 10px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        .popup-content th {
            background-color: #f4f4f4;
        }

        /* Input field styling */
        input[type="number"] {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
            /* Include padding in width calculation */
        }

        /* Button styling */
        button {
            background-color: #3498db;
            /* Primary color */
            color: #fff;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #2980b9;
            /* Darker shade on hover */
        }

        .loading_data {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            /* background-color: rgba(255, 255, 255, 0.8); */
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            /* Ensures the loader is on top */
        }

        .spinner {
            border: 8px solid rgba(0, 0, 0, 0.1);
            border-left-color: #3498db;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }
    </style>

</head>

<body>
    <!--<div id="loading_data" class="loading_data">-->
    <!--    <div class="spinner"></div>-->
    <!--</div>-->
    <!-- Popup Modal -->
    <!-- HTML for the Modal Popup -->
    <div id="stockPopup" class="popup">
        <div class="popup-content">
            <span class="close" onclick="closePopupstock()">&times;</span>
            <h2>Edit Stock</h2>
            <table>
                <tr>
                    <th>Product Name</th>
                    <th>Overall Purchase Stock</th>
                    <th>Opening Stock</th>
                    <th style="display: none;">Difference Stock</th>
                    <th>Opening Value</th>
                </tr>
                <tr id="productDetailsRow">
                    <td id="productName"></td>
                    <td id="overallStock"></td>
                    <td id="OpeningStock"></td>
                    <!-- Input field for current stock -->
                    <td id="currentStock" style="display: none;"></td>
                    <td><input type="number" id="currentStocksaleInput" /></td>
                </tr>
            </table>
            <!-- Button to submit the stock update -->
            <button onclick="updateStock()">Edit Stock</button>
        </div>
    </div>

    <!-- PHP button for editing stock -->
    <a href="#" onclick="openPopup(<?php echo htmlentities($product['product_id']); ?>)">
        <ion-icon name="server-outline"></ion-icon> &nbsp; Edit Stock
    </a>

    <!-- loader Start -->

    <!-- 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"><a href="list_products.php">Reports</a> > Audit Report
                                    </h4>
                                </div>
                                <div class="col-lg-6">
                                    <!-- <button class="btn btn-primary  ps-5 pe-5" style="float:inline-end;">
                                        <a href="add_products.php" class="text-white">
                                            <ion-icon name="add-outline" style="font-size:20px; margin-bottom:-4px">
                                            </ion-icon> Add
                                        </a>
                                    </button> -->
                                    <!-- <button class="btn btn-primary  ps-5 pe-5 me-2" style="float:inline-end;">
                                        <a href="list_stock_report.php" class="text-white">Stock Report</a>
                                    </button> -->
                                </div>
                            </div>
                            <!-- search bar -->

             
                            <!-- <form method="get" id="recordsPerPageForm" style="margin-left:2em;">
                                <label for="recordsPerPage">Show</label>
                                <select name="records_per_page" id="recordsPerPage" class="form-control" style="width: 8em;" onchange="document.getElementById('recordsPerPageForm').submit();">
                                    <option value="50" <?php if ($records_per_page == 50) echo 'selected'; ?>>50</option>
                                    <option value="100" <?php if ($records_per_page == 100) echo 'selected'; ?>>100</option>
                                    <option value="200" <?php if ($records_per_page == 200) echo 'selected'; ?>>200</option>
                                    <option value="500" <?php if ($records_per_page == 500) echo 'selected'; ?>>500</option>
                                    <option value="50" <?php if ($records_per_page == 1000) echo 'selected'; ?>>1000</option>
                                </select>
                                <input type="hidden" name="page" value="<?php echo $page; ?>">
                                <input type="hidden" name="search" value="<?php echo htmlspecialchars($search); ?>">
                            </form> -->
                     



                            <!-- searchbar end -->
                            <!-- buttons for export -->
                            <div class="row mt-5">
                                <div class="col-lg-2"></div>
                                <!--<div class="col-lg-8">-->
                                <!--    <button class="btn btn-primary" onclick="exportToCSV()">-->
                                <!--        <ion-icon name="document-outline"></ion-icon>Export to CSV-->
                                <!--    </button>-->
                                <!--    <button class="btn btn-info" onclick="exportToExcel()">-->
                                <!--        <ion-icon name="document-outline"></ion-icon>Export to Excel-->
                                <!--    </button>-->
                                <!--    <button class="btn btn-warning">-->
                                <!--        <ion-icon name="print-outline"></ion-icon>Print-->
                                <!--    </button>-->
                                <!--    <button class="btn btn-danger">-->
                                <!--        <ion-icon name="stop-outline"></ion-icon>Column Visibility-->
                                <!--    </button>-->
                                <!--    <button class="btn btn-dark" onclick="exportToPDF()">-->
                                <!--        <ion-icon name="document-outline"></ion-icon>Export to PDF-->
                                <!--    </button>-->
                                <!--</div>-->

                            </div>

                            <!-- buttons for export end -->
                            <div class="iq-card-body" style="overflow:auto;">

                                <!-- HTML Table -->




<button id="printButton" class="btn btn-primary" style="margin-bottom: 10px;">🖨️ Print Report</button>

    <style>
        #stockSummary {
            margin-top: 20px;
            padding: 20px;
            background: #f9fafb;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            max-width: 400px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        #stockSummary h3 {
            margin-bottom: 15px;
            font-size: 20px;
            color: #333;
            text-align: center;
            border-bottom: 1px solid #ddd;
            padding-bottom: 8px;
        }

        #stockSummary .summary-item {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            font-size: 16px;
            color: #444;
        }

        #stockSummary .summary-label {
            font-weight: 600;
        }

        #stockSummary .summary-value {
            font-weight: bold;
            color: #007bff;
        }
    </style>
<div class="container mt-4">
    <div class="row mt-3 mb-2">
        <div class="col-lg-3">
            <input type="search" id="auditSearchInput" placeholder="Search product or voucher..." class="form-control">
        </div>
        <div class="col-lg-2">
            <select id="statusFilter" class="form-control">
                <option value="all" selected>All Status</option>
                <option value="sale">Sale</option>
                <option value="purchase">Purchase</option>
            </select>
        </div>
        <div class="col-lg-2">
            <input type="date" id="startDate" class="form-control" placeholder="Start Date">
        </div>
        <div class="col-lg-2">
<input type="date" id="endDate" class="form-control" placeholder="End Date" value="<?php echo date('Y-m-d'); ?>">
        </div>
        <div class="col-lg-2">
            <button id="dateFilterBtn" class="btn btn-primary">Filter</button>
        </div>
    </div>

    <div id="stockSummary" class="mb-3">
        <h3>Audit Summary Report</h3>
        <div class="summary-item"><span class="summary-label">Total Sales:</span> <span class="summary-value" id="totalSale">0</span></div>
        <div class="summary-item"><span class="summary-label">Total Purchases:</span> <span class="summary-value" id="totalPurchase">0</span></div>
    </div>

    <table class="table table-hover table-bordered" id="auditTable"> 
        <thead class="thead-light">
            <tr>
                <th>Voucher</th>
                <th>Product</th>
                <th>Unit</th>
                <th>Quantity Adjust</th>
                <th>Price</th>
                <th>Total Amount</th>
                <th>Type Audit</th>
                <th>Stock After Adjustment</th>
                <th>Date</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>  

    <!-- <button id="printButton" class="btn btn-success mt-2">Print Report</button> -->
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {

    function loadAuditTable(filterStatus = 'all', searchKeyword = '', startDate = '', endDate = '') {
        $.ajax({
            url: 'fetch_audit_report.php',
            method: 'GET',
            data: { 
                status: filterStatus, 
                search: searchKeyword,
                start_date: startDate,
                end_date: endDate
            },
            dataType: 'json',
            success: function(data) {
                const tbody = $('#auditTable tbody');
                tbody.empty();

                let totalSale = 0;
                let totalPurchase = 0;

                if(data.length === 0){
                    tbody.append('<tr><td colspan="8" class="text-center">No records found</td></tr>');
                } else {
                    data.forEach(item => {
                        const totalAmount = parseFloat(item.price) * parseFloat(item.qty);
                        if(item.adjustment_type.toLowerCase() === 'sale'){
                            totalSale += totalAmount;
                        } else if(item.adjustment_type.toLowerCase() === 'purchase'){
                            totalPurchase += totalAmount;
                        }

                        const row = `<tr>
                            <td>${parseInt(item.voucher_no, 10)}</td>
                            <td>${item.product_name}</td>
                            <td>${item.unit_name}</td>
                            <td>${item.qty}</td>
                            <td>${item.price}</td>
                            <td>${totalAmount.toFixed(2)}</td>
                            <td>${item.adjustment_type}</td>
                             <td>${item.stock_after_adjustment}</td>
                            <td>${item.created_at}</td>
                        </tr>`;
                        tbody.append(row);
                    });
                }

                $('#totalSale').text(totalSale.toFixed(2));
                $('#totalPurchase').text(totalPurchase.toFixed(2));
            },
            error: function(xhr) {
                alert("Error loading audit report: " + xhr.responseText);
            }
        });
    }

    loadAuditTable();

    $('#auditSearchInput').on('keyup', function() {
        const keyword = $(this).val();
        const status = $('#statusFilter').val();
        const startDate = $('#startDate').val();
        const endDate = $('#endDate').val();
        loadAuditTable(status, keyword, startDate, endDate);
    });

    $('#statusFilter').on('change', function() {
        const status = $(this).val();
        const keyword = $('#auditSearchInput').val();
        const startDate = $('#startDate').val();
        const endDate = $('#endDate').val();
        loadAuditTable(status, keyword, startDate, endDate);
    });

    $('#dateFilterBtn').click(function() {
        const status = $('#statusFilter').val();
        const keyword = $('#auditSearchInput').val();
        const startDate = $('#startDate').val();
        const endDate = $('#endDate').val();
        loadAuditTable(status, keyword, startDate, endDate);
    });

    $('#printButton').click(function() {
        const printContents = document.getElementById('auditTable').outerHTML;
        const newWindow = window.open('', '', 'width=900,height=600');
        newWindow.document.write('<html><head><title>Audit Report</title>');
        newWindow.document.write('<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">');
        newWindow.document.write('<style> table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid #000; padding: 8px; text-align: left; } </style>');
        newWindow.document.write('</head><body>');
        newWindow.document.write('<h3>Audit Summary Report</h3>');
        newWindow.document.write(printContents);
        newWindow.document.write('</body></html>');
        newWindow.document.close();
        newWindow.focus();
        newWindow.print();
    });

});
</script>

                     


                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
    </div>
   
   

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